diff --git a/core-java/src/main/java/com/baeldung/generics/Generics.java b/core-java/src/main/java/com/baeldung/generics/Generics.java new file mode 100644 index 0000000000..69c7baddd3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/generics/Generics.java @@ -0,0 +1,23 @@ +package com.baeldung.generics; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Generics { + + // definition of a generic method + public static List fromArrayToList(T[] a) { + List list = new ArrayList<>(); + Arrays.stream(a).forEach(list::add); + return list; + } + + // example of a generic method that has Number as an upper bound for T + public static List fromArrayToListWithUpperBound(T[] a) { + List list = new ArrayList<>(); + Arrays.stream(a).forEach(list::add); + return list; + } + +} diff --git a/core-java/src/test/java/com/baeldung/generics/GenericsTest.java b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java new file mode 100644 index 0000000000..9eb459ccb5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/generics/GenericsTest.java @@ -0,0 +1,41 @@ +package com.baeldung.generics; + +import org.junit.Test; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.MatcherAssert.assertThat; + +public class GenericsTest { + + // testing the generic method with Integer + @Test + public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() { + Integer[] intArray = {1, 2, 3, 4, 5}; + List list = Generics.fromArrayToList(intArray); + + assertThat(list, hasItems(intArray)); + } + + // testing the generic method with String + @Test + public void givenArrayOfStrings_thanListOfStringsReturnedOK() { + String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"}; + List list = Generics.fromArrayToList(stringArray); + + assertThat(list, hasItems(stringArray)); + } + + // testing the generic method with Number as upper bound with Integer + // if we test fromArrayToListWithUpperBound with any type that doesn't + // extend Number it will fail to compile + @Test + public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() { + Integer[] intArray = {1, 2, 3, 4, 5}; + List list = Generics.fromArrayToListWithUpperBound(intArray); + + assertThat(list, hasItems(intArray)); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java index 4b56a97325..d4b63beaa4 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileUnitTest.java @@ -1,7 +1,9 @@ package org.baeldung.java.io; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertTrue; +import org.apache.commons.io.FileUtils; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; import java.io.File; import java.io.IOException; @@ -9,17 +11,29 @@ import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.UUID; -import org.apache.commons.io.FileUtils; -import org.junit.Test; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertTrue; public class JavaFileUnitTest { - // create a file + private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString(); + + + @BeforeClass + public static void setup() throws IOException { + Files.createDirectory(Paths.get(TEMP_DIR)); + } + + @AfterClass + public static void cleanup() throws IOException { + FileUtils.deleteDirectory(new File(TEMP_DIR)); + } @Test public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException { - final File newFile = new File("src/test/resources/newFile_jdk6.txt"); + final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt"); final boolean success = newFile.createNewFile(); assertTrue(success); @@ -27,48 +41,48 @@ public class JavaFileUnitTest { @Test public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException { - final Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt"); + final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt"); Files.createFile(newFilePath); } @Test public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt")); + FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt")); } @Test public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException { - com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt")); + com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt")); } // move a file @Test public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException { - final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt"); + final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt"); fileToMove.createNewFile();// .exists(); - final File destDir = new File("src/test/resources/"); + final File destDir = new File(TEMP_DIR + "/"); destDir.mkdir(); - final boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt")); + final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt")); if (!isMoved) { - throw new FileSystemException("src/test/resources/movedFile_jdk6.txt"); + throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt"); } } @Test public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException { - final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt")); - final Path targetPath = Paths.get("src/main/resources/"); + final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt")); + final Path targetPath = Paths.get(TEMP_DIR + "/"); Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName())); } @Test public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException { - final File fileToMove = new File("src/test/resources/fileToMove.txt"); + final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt"); fileToMove.createNewFile(); - final File destDir = new File("src/main/resources/"); + final File destDir = new File(TEMP_DIR + "/temp"); final File targetFile = new File(destDir, fileToMove.getName()); com.google.common.io.Files.createParentDirs(targetFile); com.google.common.io.Files.move(fileToMove, targetFile); @@ -76,23 +90,24 @@ public class JavaFileUnitTest { @Test public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); - FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt")); + FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt")); } @Test public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt")); - FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true); + FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt")); + Files.createDirectory(Paths.get(TEMP_DIR + "/temp")); + FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true); } // delete a file @Test public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException { - new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile(); + new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile(); - final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt"); + final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt"); final boolean success = fileToDelete.delete(); assertTrue(success); @@ -100,17 +115,17 @@ public class JavaFileUnitTest { @Test public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { - Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt")); - final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); + final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"); Files.delete(fileToDeletePath); } @Test public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt")); - final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt"); + final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt"); final boolean success = FileUtils.deleteQuietly(fileToDelete); assertTrue(success); @@ -118,9 +133,9 @@ public class JavaFileUnitTest { @Test public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { - FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt")); - FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); + FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt")); } } diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 772e4056d3..6ece63572d 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -1,20 +1,15 @@ - 4.0.0 - - com.baeldung.ejb - ejb - 1.0-SNAPSHOT - - ejb-client - EJB3 Client Maven - EJB3 Client Maven - - 4.12 - 2.19.1 - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.baeldung.ejb + ejb + 1.0-SNAPSHOT + + ejb-client + EJB3 Client Maven + EJB3 Client Maven org.wildfly @@ -49,6 +44,4 @@ - - \ No newline at end of file diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties index 077cd7583f..a01a675e44 100755 --- a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -5,4 +5,4 @@ remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMO remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} remote.connection.default.username=testUser -remote.connection.default.password=admin1234! \ No newline at end of file +remote.connection.default.password=admin1234! diff --git a/ejb/ejb-remote/pom.xml b/ejb/ejb-remote/pom.xml index 65bfc6dbec..d102edd8e3 100755 --- a/ejb/ejb-remote/pom.xml +++ b/ejb/ejb-remote/pom.xml @@ -12,11 +12,12 @@ - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.2_spec - provided - + + javax + javaee-api + 7.0 + provided + diff --git a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java index 4b88747e6a..f34153d83a 100755 --- a/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/tutorial/HelloWorldBean.java @@ -1,13 +1,19 @@ package com.baeldung.ejb.tutorial; +import javax.annotation.Resource; +import javax.ejb.SessionContext; import javax.ejb.Stateless; @Stateless(name = "HelloWorld") public class HelloWorldBean implements HelloWorld { + @Resource + private SessionContext context; + @Override public String getHelloWorld() { return "Welcome to EJB Tutorial!"; } + } diff --git a/ejb/pom.xml b/ejb/pom.xml index 5c54cdcf72..8176de7936 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -36,11 +36,10 @@ - org.jboss.spec - jboss-javaee-7.0 - 1.0.1.Final - pom - import + javax + javaee-api + 7.0 + provided diff --git a/spring-core/README.md b/spring-core/README.md index 5554412c31..53842ecb1a 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Wiring in Spring: @Autowired, @Resource and @Inject](http://www.baeldung.com/spring-annotations-resource-inject-autowire) +- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 84a492bbe4..bf8c8f3ebc 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -47,6 +47,11 @@ 4.12 test + + com.google.guava + guava + 20.0 + diff --git a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java new file mode 100644 index 0000000000..40e181b7a7 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.factorybean; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FactoryBeanAppConfig { + + @Bean + public ToolFactory tool() { + ToolFactory factory = new ToolFactory(); + factory.setFactoryId(7070); + factory.setToolId(2); + factory.setToolName("wrench"); + factory.setToolPrice(3.7); + return factory; + } + + @Bean + public Worker worker() throws Exception { + Worker worker = new Worker(); + worker.setNumber("1002"); + worker.setTool(tool().getObject()); + return worker; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java new file mode 100644 index 0000000000..15e2b01f49 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java @@ -0,0 +1,68 @@ +package com.baeldung.factorybean; + +import static com.google.common.base.Preconditions.checkArgument; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.StringUtils; + +public class InitializationToolFactory implements FactoryBean, InitializingBean { + + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; + + @Override + public void afterPropertiesSet() throws Exception { + checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); + checkArgument(toolPrice >= 0, "tool price should not be less than 0"); + } + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java new file mode 100644 index 0000000000..158318649c --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -0,0 +1,57 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.config.AbstractFactoryBean; + +public class NonSingleToolFactory extends AbstractFactoryBean { + + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; + + public NonSingleToolFactory() { + setSingleton(false); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + protected Tool createInstance() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java new file mode 100644 index 0000000000..696545a70a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.factorybean; + +import static com.google.common.base.Preconditions.checkArgument; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.StringUtils; + +public class PostConstructToolFactory implements FactoryBean { + + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + @PostConstruct + public void checkParams() { + checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); + checkArgument(toolPrice >= 0, "tool price should not be less than 0"); + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java new file mode 100644 index 0000000000..37fd978a3c --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -0,0 +1,54 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.config.AbstractFactoryBean; + +//no need to set singleton property because default value is true +public class SingleToolFactory extends AbstractFactoryBean { + + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + protected Tool createInstance() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java new file mode 100644 index 0000000000..2a69cbaf2a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -0,0 +1,38 @@ +package com.baeldung.factorybean; + +public class Tool { + + private int id; + private String name; + private double price; + + public Tool(int id, String name, double price) { + this.id = id; + this.name = name; + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java new file mode 100644 index 0000000000..5e6385c679 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -0,0 +1,58 @@ +package com.baeldung.factorybean; + +import org.springframework.beans.factory.FactoryBean; + +public class ToolFactory implements FactoryBean { + + private int factoryId; + private int toolId; + private String toolName; + private double toolPrice; + + @Override + public Tool getObject() throws Exception { + return new Tool(toolId, toolName, toolPrice); + } + + @Override + public Class getObjectType() { + return Tool.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + public int getFactoryId() { + return factoryId; + } + + public void setFactoryId(int factoryId) { + this.factoryId = factoryId; + } + + public int getToolId() { + return toolId; + } + + public void setToolId(int toolId) { + this.toolId = toolId; + } + + public String getToolName() { + return toolName; + } + + public void setToolName(String toolName) { + this.toolName = toolName; + } + + public double getToolPrice() { + return toolPrice; + } + + public void setToolPrice(double toolPrice) { + this.toolPrice = toolPrice; + } +} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java new file mode 100644 index 0000000000..0d1dc5d7d6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java @@ -0,0 +1,30 @@ +package com.baeldung.factorybean; + +public class Worker { + + private String number; + private Tool tool; + + public Worker() {} + + public Worker(String number, Tool tool) { + this.number = number; + this.tool = tool; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public Tool getTool() { + return tool; + } + + public void setTool(Tool tool) { + this.tool = tool; + } +} diff --git a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml new file mode 100644 index 0000000000..33b3051cae --- /dev/null +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml new file mode 100644 index 0000000000..1ff492e5df --- /dev/null +++ b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml new file mode 100644 index 0000000000..f34325160f --- /dev/null +++ b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml new file mode 100644 index 0000000000..2987b67d94 --- /dev/null +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java new file mode 100644 index 0000000000..a7ba6d9a68 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java @@ -0,0 +1,36 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class AbstractFactoryBeanTest { + + @Test + public void testSingleToolFactory() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); + + Worker worker1 = (Worker) context.getBean("worker1"); + Worker worker2 = (Worker) context.getBean("worker2"); + + assertThat(worker1.getNumber(), equalTo("50001")); + assertThat(worker2.getNumber(), equalTo("50002")); + assertTrue(worker1.getTool() == worker2.getTool()); + } + + @Test + public void testNonSingleToolFactory() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); + + Worker worker3 = (Worker) context.getBean("worker3"); + Worker worker4 = (Worker) context.getBean("worker4"); + + assertThat(worker3.getNumber(), equalTo("50003")); + assertThat(worker4.getNumber(), equalTo("50004")); + assertTrue(worker3.getTool() != worker4.getTool()); + } +} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java new file mode 100644 index 0000000000..87947b148a --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java @@ -0,0 +1,18 @@ +package com.baeldung.factorybean; + +import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class FactoryBeanInitializeTest { + + @Test(expected = BeanCreationException.class) + public void testInitializationToolFactory() { + new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); + } + + @Test(expected = BeanCreationException.class) + public void testPostConstructToolFactory() { + new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); + } +} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java new file mode 100644 index 0000000000..f35503794a --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java @@ -0,0 +1,40 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class FactoryBeanTest { + + @Test + public void testConstructWorkerByXml() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-spring-ctx.xml"); + + Worker worker = (Worker) context.getBean("worker"); + assertThat(worker.getNumber(), equalTo("1001")); + assertThat(worker.getTool().getId(), equalTo(1)); + assertThat(worker.getTool().getName(), equalTo("screwdriver")); + assertThat(worker.getTool().getPrice(), equalTo(1.5)); + + ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); + assertThat(toolFactory.getFactoryId(), equalTo(9090)); + } + + @Test + public void testConstructWorkerByJava() { + ApplicationContext context = new AnnotationConfigApplicationContext(FactoryBeanAppConfig.class); + + Worker worker = (Worker) context.getBean("worker"); + assertThat(worker.getNumber(), equalTo("1002")); + assertThat(worker.getTool().getId(), equalTo(2)); + assertThat(worker.getTool().getName(), equalTo("wrench")); + assertThat(worker.getTool().getPrice(), equalTo(3.7)); + + ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); + assertThat(toolFactory.getFactoryId(), equalTo(7070)); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 2c88408017..d5765b9756 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -8,6 +8,7 @@ import java.io.File; import java.io.IOException; import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -22,11 +23,16 @@ public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + OkHttpClient client; + + @Before + public void init() { + client = new OkHttpClient(); + } + @Test public void whenUploadFile_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "file.txt", @@ -47,22 +53,17 @@ public class OkHttpFileUploadingLiveTest { @Test public void whenGetUploadFileProgress_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) .build(); + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { - ProgressRequestWrapper.ProgressListener listener = (bytesWritten, contentLength) -> { - - float percentage = 100f * bytesWritten / contentLength; + float percentage = 100f * bytesWritten / contentLength; assertFalse(Float.compare(percentage, 100) > 0); - }; - - ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); + }); Request request = new Request.Builder() .url(BASE_URL + "/users/upload") diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 3f773bf35e..08d41fe7ab 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -4,20 +4,30 @@ import okhttp3.*; import org.junit.Test; import java.io.IOException; +import org.junit.Before; +import org.junit.Test; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenGetRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/date") .build(); @@ -30,9 +40,6 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); urlBuilder.addQueryParameter("id", "1"); @@ -50,9 +57,6 @@ public class OkHttpGetLiveTest { @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/date") .build(); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java index 8eddfcb135..8888f7d4a7 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpHeaderLiveTest.java @@ -2,6 +2,7 @@ package org.baeldung.okhttp; import java.io.IOException; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -13,11 +14,16 @@ public class OkHttpHeaderLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSetHeader_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() .url(SAMPLE_URL) .addHeader("Content-Type", "application/json") @@ -31,7 +37,7 @@ public class OkHttpHeaderLiveTest { @Test public void whenSetDefaultHeader_thenCorrect() throws IOException { - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientWithInterceptor = new OkHttpClient.Builder() .addInterceptor(new DefaultContentTypeInterceptor("application/json")) .build(); @@ -39,10 +45,8 @@ public class OkHttpHeaderLiveTest { .url(SAMPLE_URL) .build(); - Call call = client.newCall(request); + Call call = clientWithInterceptor.newCall(request); Response response = call.execute(); response.close(); } - - } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index 9c38c8da51..34e1554908 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -4,22 +4,37 @@ import okhttp3.*; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.io.File; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import okhttp3.Cache; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSetRequestTimeout_thenFail() throws IOException { - - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientWithTimeout = new OkHttpClient.Builder() .readTimeout(1, TimeUnit.SECONDS) .build(); @@ -27,18 +42,15 @@ public class OkHttpMiscLiveTest { .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. .build(); - Call call = client.newCall(request); + Call call = clientWithTimeout.newCall(request); Response response = call.execute(); response.close(); } @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. .build(); @@ -69,7 +81,7 @@ public class OkHttpMiscLiveTest { File cacheDirectory = new File("src/test/resources/cache"); Cache cache = new Cache(cacheDirectory, cacheSize); - OkHttpClient client = new OkHttpClient.Builder() + OkHttpClient clientCached = new OkHttpClient.Builder() .cache(cache) .build(); @@ -77,10 +89,10 @@ public class OkHttpMiscLiveTest { .url("http://publicobject.com/helloworld.txt") .build(); - Response response1 = client.newCall(request).execute(); + Response response1 = clientCached.newCall(request).execute(); logResponse(response1); - Response response2 = client.newCall(request).execute(); + Response response2 = clientCached.newCall(request).execute(); logResponse(response2); } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index 18bd4cdcb3..dce3bb174f 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; +import org.junit.Before; import org.junit.Test; import okhttp3.Call; @@ -23,11 +24,16 @@ public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:8080/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; + OkHttpClient client; + + @Before + public void init() { + + client = new OkHttpClient(); + } + @Test public void whenSendPostRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - RequestBody formBody = new FormBody.Builder() .add("username", "test") .add("password", "test") @@ -46,11 +52,8 @@ public class OkHttpPostingLiveTest { @Test public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - String postBody = "test post"; - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() .url(URL_SECURED_BY_BASIC_AUTHENTICATION) .addHeader("Authorization", Credentials.basic("test", "test")) @@ -65,9 +68,6 @@ public class OkHttpPostingLiveTest { @Test public void whenPostJson_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - String json = "{\"id\":1,\"name\":\"John\"}"; RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); @@ -85,9 +85,6 @@ public class OkHttpPostingLiveTest { @Test public void whenSendMultipartRequest_thenCorrect() throws IOException { - - OkHttpClient client = new OkHttpClient(); - RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username", "test") diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java index 468c99cb2a..1901489305 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java @@ -1,17 +1,40 @@ package org.baeldung.security.filter.configuration; +import org.baeldung.security.basic.MyBasicAuthenticationEntryPoint; import org.baeldung.security.filter.CustomFilter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration +@EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + @Autowired + private MyBasicAuthenticationEntryPoint authenticationEntryPoint; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) + throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1").password("user1Pass") + .authorities("ROLE_USER"); + } @Override protected void configure(HttpSecurity http) throws Exception { - http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); - } + http.authorizeRequests() + .antMatchers("/securityNone").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); + http.addFilterAfter(new CustomFilter(), + BasicAuthenticationFilter.class); + } } diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4ce80dab9f..5aa14c1051 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -2,11 +2,10 @@ package org.baeldung.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; @Configuration -@ImportResource({ "classpath:webSecurityConfig.xml" }) @ComponentScan("org.baeldung.security") +//@ImportResource({ "classpath:webSecurityConfig.xml" }) public class SecSecurityConfig { public SecSecurityConfig() {