Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2016-11-22 22:08:46 -06:00
commit 91b1b3c650
32 changed files with 823 additions and 112 deletions

View File

@ -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 <T> List<T> fromArrayToList(T[] a) {
List<T> 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 <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
List<T> list = new ArrayList<>();
Arrays.stream(a).forEach(list::add);
return list;
}
}

View File

@ -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<Integer> 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<String> 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<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
}

View File

@ -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"));
}
}

View File

@ -1,20 +1,15 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
@ -49,6 +44,4 @@
</plugin>
</plugins>
</build>
</project>

View File

@ -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!
remote.connection.default.password=admin1234!

View File

@ -12,11 +12,12 @@
<!-- <name>ejb-remote</name> -->
<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

View File

@ -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!";
}
}

View File

@ -36,11 +36,10 @@
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>1.0.1.Final</version>
<type>pom</type>
<scope>import</scope>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>

View File

@ -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)

View File

@ -47,6 +47,11 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
</dependencies>
<build>

View File

@ -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;
}
}

View File

@ -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<Tool>, 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;
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.factorybean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
public class NonSingleToolFactory extends AbstractFactoryBean<Tool> {
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;
}
}

View File

@ -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<Tool> {
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;
}
}

View File

@ -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<Tool> {
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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.factorybean;
import org.springframework.beans.factory.FactoryBean;
public class ToolFactory implements FactoryBean<Tool> {
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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="singleTool" class="com.baeldung.factorybean.SingleToolFactory">
<property name="factoryId" value="3001"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="nonSingleTool" class="com.baeldung.factorybean.NonSingleToolFactory">
<property name="factoryId" value="3002"/>
<property name="toolId" value="2"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="worker1" class="com.baeldung.factorybean.Worker">
<property name="number" value="50001"/>
<property name="tool" ref="singleTool"/>
</bean>
<bean id="worker2" class="com.baeldung.factorybean.Worker">
<property name="number" value="50002"/>
<property name="tool" ref="singleTool"/>
</bean>
<bean id="worker3" class="com.baeldung.factorybean.Worker">
<property name="number" value="50003"/>
<property name="tool" ref="nonSingleTool"/>
</bean>
<bean id="worker4" class="com.baeldung.factorybean.Worker">
<property name="number" value="50004"/>
<property name="tool" ref="nonSingleTool"/>
</bean>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="initializationTool" class="com.baeldung.factorybean.InitializationToolFactory">
<property name="factoryId" value="1010"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="-1"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="36"/>
<property name="tool" ref="initializationTool"/>
</bean>
</beans>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="postConstructTool" class="com.baeldung.factorybean.PostConstructToolFactory">
<property name="factoryId" value="2020"/>
<property name="toolId" value="1"/>
<property name="toolName" value=""/>
<property name="toolPrice" value="2.2"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="37"/>
<property name="tool" ref="postConstructTool"/>
</bean>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="tool" class="com.baeldung.factorybean.ToolFactory">
<property name="factoryId" value="9090"/>
<property name="toolId" value="1"/>
<property name="toolName" value="screwdriver"/>
<property name="toolPrice" value="1.5"/>
</bean>
<bean id="worker" class="com.baeldung.factorybean.Worker">
<property name="number" value="1001"/>
<property name="tool" ref="tool"/>
</bean>
</beans>

View File

@ -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());
}
}

View File

@ -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");
}
}

View File

@ -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));
}
}

View File

@ -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")

View File

@ -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();

View File

@ -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();
}
}

View File

@ -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);
}

View File

@ -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")

View File

@ -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);
}
}

View File

@ -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() {