Merge branch 'master' into pr/470-alexB-logging

This commit is contained in:
Slavisa Baeldung 2016-07-08 09:52:23 +02:00
commit 16295e6f7b
81 changed files with 2465 additions and 568 deletions

View File

@ -9,10 +9,16 @@
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@ -20,6 +26,11 @@
<version>3.4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,96 @@
package com.baeldung.assertj.introduction;
import com.google.common.base.Optional;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.TreeRangeMap;
import com.google.common.io.Files;
import org.assertj.guava.data.MapEntry;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import static org.assertj.guava.api.Assertions.assertThat;
import static org.assertj.guava.api.Assertions.entry;
public class AssertJGuavaTest {
@Test
public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
final File temp = File.createTempFile("bael", "dung");
final File temp2 = File.createTempFile("bael", "dung2");
assertThat(Files.asByteSource(temp))
.hasSize(0)
.hasSameContentAs(Files.asByteSource(temp2));
}
@Test
public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
final Multimap<Integer, String> mmap = Multimaps.newMultimap(new HashMap<>(), Sets::newHashSet);
mmap.put(1, "one");
mmap.put(1, "1");
assertThat(mmap)
.hasSize(2)
.containsKeys(1)
.contains(entry(1, "one"))
.contains(entry(1, "1"));
}
@Test
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
final Optional<String> something = Optional.of("something");
assertThat(something)
.isPresent()
.extractingValue()
.isEqualTo("something");
}
@Test
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
final Range<String> range = Range.openClosed("a", "g");
assertThat(range)
.hasOpenedLowerBound()
.isNotEmpty()
.hasClosedUpperBound()
.contains("b");
}
@Test
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
final TreeRangeMap<Integer, String> map = TreeRangeMap.create();
map.put(Range.closed(0, 60), "F");
map.put(Range.closed(61, 70), "D");
assertThat(map)
.isNotEmpty()
.containsKeys(0)
.contains(MapEntry.entry(34, "F"));
}
@Test
public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
final Table<Integer, String, String> table = HashBasedTable.create(2, 2);
table.put(1, "A", "PRESENT");
table.put(1, "B", "ABSENT");
assertThat(table)
.hasRowCount(1)
.containsValues("ABSENT")
.containsCell(1, "B", "ABSENT");
}
}

View File

@ -1,43 +0,0 @@
apply plugin: 'java'
apply plugin: 'eclipse'
allprojects {
apply plugin: 'java'
sourceCompatibility = 1.6
targetCompatibility = 1.6
}
repositories {
mavenCentral()
}
sourceSets {
main {
resources.srcDirs = ["src/main/java","src/main/resources"]
}
test {
resources.srcDirs = ["src/main/java", "src/main/resources", "src/test/resources"]
}
}
configurations {
compile
}
test {
testLogging {
events 'started', 'passed'
}
}
dependencies {
testCompile('junit:junit:4.11')
testCompile('org.mockito:mockito-all:1.10.19')
testCompile group: 'org.springframework', name: 'spring-test', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-core', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-beans', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-context', version: '4.2.6.RELEASE'
testCompile group: 'javax.inject', name: 'javax.inject', version: '1'
testRuntime('junit:junit:4.11')
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" version="5.5.2.3" editor="www.draw.io" type="device"><diagram>7VptbyI3EP41SO2Hi1iWl+RjAuSuUpqml6jX+xQZ1uz6zrumXhPC/fqb8Y7ZV0IaXqpGICTWw3hsz/N4Zmxo+cP4+aNm8+h3FXDZ6rSD55Y/anU6XrvvwwdKVpmk3yZBqEVASrngXvzgridJFyLgaUnRKCWNmJeFU5UkfGpKMqa1WpbVZkqWR52z0I2YC+6nTNalX0Rgokx63unn8k9chJEb2etfZN9M2PR7qNUiofFaHX9mX9nXMXO2aKFpxAK1LIj8MfhVKwWW8Sl+HnKJvnVuy/pdb/h2PW/NE5rblg5uHmbl1s4DcAU1lTaRClXC5DiXXtn1cbTQhlZkYgmPHjzCoHr1N8lt4ys2znq2GVwiMmh1zpOHSCSZ9FrAjLIu37gxK2IDWxgFonwGN0rNaZz6KmnhqVroKa0D2pY3TIectAaZCFdY6Eae+chVzGHKoKC5ZEY8lcnAiFPhWi/3KzyQa5vdTHN5YnJBRq8Fl8GfCybFTHD9W/INaDzisarBkS5FLFmCfi94eqYS40DCNtgJwZ+jKXiEaxA8cW0EEPqSvjDovKtpJGRww1ZqgR5JDbDVta4ipcUPMMvcGPC1NoQGML+ocY89CTTNU9C5c2Bgz0x0w1IUoM5UScnmqZisJxwDLCK5UsaomJTcSpEQQyUVLAMc4PbPC6jjWrmLPc2IUhwaEAOW+abuuq0YFTd0h+LVLqCTiQLoH1qdPosRiGSS4ge0Jfo+nbMEnkN8Bj7IYMRhjwQ8ma5gQZkODFdUa/mXYPxST4TRTK/yDk4/EE9O9y3jwtQ3j1u29sIkoHNhHjVyA2yWejmxU6PVd+7gT5Ql/qzACBI5wks+QwvNdId5T0US3lidUTeXfCaoUbSMhOH3IMc5LSGfYdQBezNpg1UkAliRjXqGGZYxGOk6VyIxlh69K3gDi4YY6XqwriG0ATfXhjeqazNUCayPQT/oxmF7LDlukQZmu4Dxama71LSN2d3u7sQmEwVi14CVohqxMmBdNrUx7F+jGgMWNgMRjA82I3yw5ktQ+3WoUVSFULIJl3cqFUYotK8z3Qq0R0BvQEhtQ+98d/B6DeA1xoMQEmByCVl4KTTPU9UfiU1djw+fxrePo/Hd+HY0vh1+9R7/AoVgU9BosP/Lry9GtieVWyuFkD1MtvOmyQJjqhPb0PMU9Y4U9Qa0IbZGvT2kc48i7P+rVObPwthhzroX1MSBvLP2gJp3XAtwBlaN1vKrimuKIsXi2iP09lddU9c7pByoOEacE8Au8/nUdiayeVKvHF9wKcPhnRoxeeM4nXZlnHY21fVRaot+t505KadXNoOcbGufvIp/RL9C4G6su07HhwMcH+jbfq8MsTs9F8KP128IPxcVhr4l/NDJpXyaaNsKJstL90ZDjD8lm9cmG7efdimxG9F2erugTXntVGLvDb0eeXAbensosekusFpiwxVmtkehmDzt2GNg7vA9xo71qCTad3l4NvBwX61LRKjc/HMnqNZuhcpxIhXm2EPesHruar5QBRL3j3/F6iZTrI8SZSKuT2XSscskVxfRNvT79cy5rpZL165OuBMR6pftp0ppp7i73lq7lEqNgO8l8Nbv2U+10o74NRRLjfjtoVjymm6TT9XSf7FrG8qlw+3a+nn2M/9nAbe39kpmC8Q29W10JPoKixtMj5XM/RqsaRsjsHtIht3KdZVf31qNJek+MmH9FPlOfVy5l/HPj+jk+mnPlcrvxLveBR1tXkoOh3Gus/F+ndt3t9euciI6HcO59RPTO3Nu/Qq/KcMdyLv1Y8g7827PXWu7qDs4GHehmf8nLvvtJP/joT/+CQ==</diagram></mxfile>

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>
@ -9,8 +9,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>@Resource vs @Inject vs @Autowired</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely @Resource, @Inject, and @Autowired</description>
<name>Resource vs Inject vs Autowired</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
Resource, Inject, and Autowired
</description>
<dependencies>
<dependency>
@ -56,8 +58,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>

View File

@ -0,0 +1,24 @@
package com.baeldung.configuration;
import com.baeldung.dependency.AnotherArbitraryDependency;
import com.baeldung.dependency.ArbitraryDependency;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationContextTestAutowiredQualifier {
@Bean
public ArbitraryDependency autowiredFieldDependency() {
ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency();
return autowiredFieldDependency;
}
@Bean
public ArbitraryDependency anotherAutowiredFieldDependency() {
ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency();
return anotherAutowiredFieldDependency;
}
}

View File

@ -1,10 +1,9 @@
package com.baeldung.configuration;
import com.baeldung.dependency.ArbitraryDependency;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.dependency.ArbitraryDependency;
@Configuration
public class ApplicationContextTestAutowiredType {

View File

@ -1,10 +1,9 @@
package com.baeldung.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.dependency.ArbitraryDependency;
import com.baeldung.dependency.YetAnotherArbitraryDependency;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationContextTestInjectName {

View File

@ -1,10 +1,9 @@
package com.baeldung.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.dependency.AnotherArbitraryDependency;
import com.baeldung.dependency.ArbitraryDependency;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationContextTestInjectQualifier {

View File

@ -1,10 +1,9 @@
package com.baeldung.configuration;
import com.baeldung.dependency.ArbitraryDependency;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.dependency.ArbitraryDependency;
@Configuration
public class ApplicationContextTestInjectType {

View File

@ -1,10 +1,10 @@
package com.baeldung.configuration;
import java.io.File;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class ApplicationContextTestResourceNameType {

View File

@ -1,10 +1,10 @@
package com.baeldung.configuration;
import java.io.File;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class ApplicationContextTestResourceQualifier {

View File

@ -1,8 +1,7 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.baeldung.configuration.ApplicationContextTestAutowiredName;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -10,8 +9,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestAutowiredName;
import com.baeldung.dependency.ArbitraryDependency;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
@ -25,7 +24,6 @@ public class FieldAutowiredNameTest {
@Test
public void givenAutowiredAnnotation_WhenOnField_ThenDependencyValid() {
assertNotNull(autowiredFieldDependency);
assertEquals("Arbitrary Dependency",
autowiredFieldDependency.toString());
assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString());
}
}

View File

@ -1,8 +1,7 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.baeldung.configuration.ApplicationContextTestAutowiredType;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -10,8 +9,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestAutowiredType;
import com.baeldung.dependency.ArbitraryDependency;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,8 +1,7 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.baeldung.configuration.ApplicationContextTestAutowiredQualifier;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -11,8 +10,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestAutowiredQualifier;
import com.baeldung.dependency.ArbitraryDependency;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
@ -37,7 +36,6 @@ public class FieldQualifierAutowiredTest {
@Test
public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid() {
assertNotNull(fieldDependency2);
assertEquals("Another Arbitrary Dependency",
fieldDependency2.toString());
assertEquals("Another Arbitrary Dependency", fieldDependency2.toString());
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.dependency.AnotherArbitraryDependency;
import com.baeldung.dependency.ArbitraryDependency;
@Configuration
public class ApplicationContextTestAutowiredQualifier {
@Bean
public ArbitraryDependency autowiredFieldDependency() {
ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency();
return autowiredFieldDependency;
}
@Bean
public ArbitraryDependency anotherAutowiredFieldDependency() {
ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency();
return anotherAutowiredFieldDependency;
}
}

View File

@ -1,19 +1,18 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import javax.inject.Named;
import com.baeldung.configuration.ApplicationContextTestInjectName;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestInjectName;
import com.baeldung.dependency.ArbitraryDependency;
import javax.inject.Inject;
import javax.inject.Named;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
@ -28,7 +27,6 @@ public class FieldByNameInjectTest {
@Test
public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid() {
assertNotNull(yetAnotherFieldInjectDependency);
assertEquals("Yet Another Arbitrary Dependency",
yetAnotherFieldInjectDependency.toString());
assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString());
}
}

View File

@ -1,17 +1,17 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import com.baeldung.configuration.ApplicationContextTestInjectType;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestInjectType;
import com.baeldung.dependency.ArbitraryDependency;
import javax.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
@ -25,7 +25,6 @@ public class FieldInjectTest {
@Test
public void givenInjectAnnotation_WhenOnField_ThenValidDependency() {
assertNotNull(fieldInjectDependency);
assertEquals("Arbitrary Dependency",
fieldInjectDependency.toString());
assertEquals("Arbitrary Dependency", fieldInjectDependency.toString());
}
}

View File

@ -1,10 +1,7 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import com.baeldung.configuration.ApplicationContextTestInjectQualifier;
import com.baeldung.dependency.ArbitraryDependency;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
@ -12,8 +9,10 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestInjectQualifier;
import com.baeldung.dependency.ArbitraryDependency;
import javax.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
@ -31,14 +30,12 @@ public class FieldQualifierInjectTest {
@Test
public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid() {
assertNotNull(defaultDependency);
assertEquals("Arbitrary Dependency",
defaultDependency.toString());
assertEquals("Arbitrary Dependency", defaultDependency.toString());
}
@Test
public void givenInjectQualifier_WhenOnField_ThenNamedFileValid() {
assertNotNull(defaultDependency);
assertEquals("Another Arbitrary Dependency",
namedDependency.toString());
assertEquals("Another Arbitrary Dependency", namedDependency.toString());
}
}

View File

@ -1,18 +1,17 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,12 +1,6 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
@ -14,7 +8,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,19 +1,17 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,19 +1,17 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,18 +1,17 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,

View File

@ -1,11 +1,6 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
@ -13,7 +8,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(

View File

@ -1,19 +1,17 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,10 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -1,11 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="yetAnotherFieldInjectDependency" class="com.baeldung.dependency.YetAnotherArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="defaultFile" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="namedFile" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,10 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="injectDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

View File

@ -1,16 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd">
<bean id="defaultFile" class="java.io.File">
<constructor-arg value="defaultFile.txt"/>
</bean>
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

View File

@ -0,0 +1,33 @@
package org.baeldung.hamcrest;
public class Animal {
String name;
boolean wild;
String sound;
public Animal(String name, boolean wild, String sound) {
super();
this.name = name;
this.wild = wild;
this.sound = sound;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isWild() {
return wild;
}
public void setWild(boolean wild) {
this.wild = wild;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
}

View File

@ -0,0 +1,13 @@
package org.baeldung.hamcrest;
public class Cat extends Animal {
public Cat() {
super("cat", false, "meow");
}
public String makeSound() {
return getSound();
}
}

View File

@ -0,0 +1,331 @@
package org.baeldung.hamcrest;
import org.junit.Test;
import java.util.*;
import static org.baeldung.hamcrest.IsPositiveInteger.isAPositiveInteger;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.beans.HasProperty.hasProperty;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIn.isIn;
import static org.hamcrest.collection.IsIn.isOneOf;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.hamcrest.collection.IsMapContaining.hasValue;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.hamcrest.object.HasToString.hasToString;
import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith;
import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
import static org.hamcrest.text.IsEmptyString.isEmptyString;
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder;
public class HamcrestMatcherTest {
@Test
public void given2Strings_whenEqual_thenCorrect() {
String a = "foo";
String b = "FOO";
assertThat(a, equalToIgnoringCase(b));
}
@Test
public void givenBean_whenHasValue_thenCorrect() {
Person person = new Person("Baeldung", "New York");
assertThat(person, hasProperty("name"));
}
@Test
public void givenBean_whenHasCorrectValue_thenCorrect() {
Person person = new Person("Baeldung", "New York");
assertThat(person, hasProperty("address", equalTo("New York")));
}
@Test
public void given2Beans_whenHavingSameValues_thenCorrect() {
Person person1 = new Person("Baeldung", "New York");
Person person2 = new Person("Baeldung", "New York");
assertThat(person1, samePropertyValuesAs(person2));
}
@Test
public void givenAList_whenChecksSize_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers, hasSize(4));
}
@Test
public void givenArray_whenChecksSize_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers, arrayWithSize(4));
}
@Test
public void givenAListAndValues_whenChecksListForGivenValues_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers,
containsInAnyOrder("beans", "text", "collections", "number"));
}
@Test
public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() {
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers,
contains("collections", "beans", "text", "number"));
}
@Test
public void givenArrayAndValue_whenValueFoundInArray_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers, hasItemInArray("text"));
}
@Test
public void givenValueAndArray_whenValueIsOneOfArrayElements_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat("text", isOneOf(hamcrestMatchers));
}
@Test
public void givenArrayAndValues_whenValuesFoundInArray_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(
hamcrestMatchers,
arrayContainingInAnyOrder("beans", "collections", "number",
"text"));
}
@Test
public void givenArrayAndValues_whenValuesFoundInArrayInOrder_thenCorrect() {
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
assertThat(hamcrestMatchers,
arrayContaining("collections", "beans", "text", "number"));
}
@Test
public void givenCollection_whenEmpty_thenCorrect() {
List<String> emptyList = new ArrayList<>();
assertThat(emptyList, empty());
}
@Test
public void givenValueAndArray_whenValueFoundInArray_thenCorrect() {
String[] array = new String[] { "collections", "beans", "text",
"number" };
assertThat("beans", isIn(array));
}
@Test
public void givenMapAndKey_whenKeyFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasKey("blogname"));
}
@Test
public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasEntry("blogname", "baeldung"));
}
@Test
public void givenMapAndValue_whenValueFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasValue("baeldung"));
}
@Test
public void givenString_whenEmpty_thenCorrect() {
String str = "";
assertThat(str, isEmptyString());
}
@Test
public void givenString_whenEmptyOrNull_thenCorrect() {
String str = null;
assertThat(str, isEmptyOrNullString());
}
@Test
public void given2Strings_whenEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " text ";
assertThat(str1, equalToIgnoringWhiteSpace(str2));
}
@Test
public void givenString_whenContainsGivenSubstring_thenCorrect() {
String str = "calligraphy";
assertThat(str, stringContainsInOrder(Arrays.asList("call", "graph")));
}
@Test
public void givenBean_whenToStringReturnsRequiredString_thenCorrect() {
Person person = new Person("Barrack", "Washington");
String str = person.toString();
assertThat(person, hasToString(str));
}
@Test
public void given2Classes_whenOneInheritsFromOther_thenCorrect() {
assertThat(Cat.class, typeCompatibleWith(Animal.class));
}
@Test
public void given2Strings_whenIsEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " text ";
assertThat(str1, is(equalToIgnoringWhiteSpace(str2)));
}
@Test
public void given2Strings_whenIsNotEqualRegardlessWhiteSpace_thenCorrect() {
String str1 = "text";
String str2 = " texts ";
assertThat(str1, not(equalToIgnoringWhiteSpace(str2)));
}
@Test
public void given2Strings_whenNotEqual_thenCorrect() {
String str1 = "text";
String str2 = "texts";
assertThat(str1, not(str2));
}
@Test
public void given2Strings_whenIsEqual_thenCorrect() {
String str1 = "text";
String str2 = "text";
assertThat(str1, is(str2));
}
@Test
public void givenAStrings_whenContainsAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "call";
assertThat(str1, containsString(str2));
}
@Test
public void givenAString_whenEndsWithAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "phy";
assertThat(str1, endsWith(str2));
}
@Test
public void givenAString_whenStartsWithAnotherGivenString_thenCorrect() {
String str1 = "calligraphy";
String str2 = "call";
assertThat(str1, startsWith(str2));
}
@Test
public void given2Objects_whenSameInstance_thenCorrect() {
Cat cat = new Cat();
assertThat(cat, sameInstance(cat));
}
@Test
public void givenAnObject_whenInstanceOfGivenClass_thenCorrect() {
Cat cat = new Cat();
assertThat(cat, instanceOf(Cat.class));
}
@Test
public void givenList_whenEachElementGreaterThan0_thenCorrect() {
List<Integer> list = Arrays.asList(1, 2, 3);
int baseCase = 0;
assertThat(list, everyItem(greaterThan(baseCase)));
}
@Test
public void givenString_whenNotNull_thenCorrect() {
String str = "notnull";
assertThat(str, notNullValue());
}
@Test
public void givenString_whenMeetsAnyOfGivenConditions_thenCorrect() {
String str = "calligraphy";
String start = "call";
String end = "foo";
assertThat(str, anyOf(startsWith(start), containsString(end)));
}
@Test
public void givenString_whenMeetsAllOfGivenConditions_thenCorrect() {
String str = "calligraphy";
String start = "call";
String end = "phy";
assertThat(str, allOf(startsWith(start), endsWith(end)));
}
@Test
public void givenInteger_whenAPositiveValue_thenCorrect() {
int num = 1;
assertThat(num, isAPositiveInteger());
}
@Test
public void givenAnInteger_whenGreaterThan0_thenCorrect() {
int num = 1;
assertThat(num, greaterThan(0));
}
@Test
public void givenAnInteger_whenGreaterThanOrEqTo5_thenCorrect() {
int num = 5;
assertThat(num, greaterThanOrEqualTo(5));
}
@Test
public void givenAnInteger_whenLessThan0_thenCorrect() {
int num = -1;
assertThat(num, lessThan(0));
}
@Test
public void givenAnInteger_whenLessThanOrEqTo5_thenCorrect() {
assertThat(-1, lessThanOrEqualTo(5));
}
@Test
public void givenADouble_whenCloseTo_thenCorrect() {
assertThat(1.2, closeTo(1, 0.5));
}
}

View File

@ -0,0 +1,24 @@
package org.baeldung.hamcrest;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsPositiveInteger extends TypeSafeMatcher<Integer> {
public void describeTo(Description description) {
description.appendText("a positive integer");
}
@Factory
public static Matcher<Integer> isAPositiveInteger() {
return new IsPositiveInteger();
}
@Override
protected boolean matchesSafely(Integer integer) {
return integer > 0;
}
}

View File

@ -0,0 +1,37 @@
package org.baeldung.hamcrest;
public class Person {
String name;
String address;
public Person(String personName, String personAddress) {
name = personName;
address = personAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
String str="[address:"+address+",name:"+name+"]";
return str;
}
}

View File

@ -25,6 +25,12 @@
<artifactId>jsf-impl</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>${javax.el.version}</version>
</dependency>
<!-- Spring -->
@ -114,6 +120,7 @@
<!-- JSF -->
<com.sun.faces.version>2.1.7</com.sun.faces.version>
<javax.el.version>2.2</javax.el.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>

View File

@ -0,0 +1,110 @@
package com.baeldung.springintegration.controllers;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
@ManagedBean(name = "ELBean")
@ViewScoped
public class ELSampleBean {
private String firstName;
private String lastName;
private String pageDescription = "This page demos JSF EL Basics";
private int pageCounter;
private Random randomIntGen = new Random();
@PostConstruct
public void init() {
pageCounter = randomIntGen.nextInt();
}
public void save() {
}
public void saveFirstName(String firstName) {
this.firstName = firstName;
}
public void saveByELEvaluation() {
firstName = (String) evaluateEL("#{firstName.value}", String.class);
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName);
theMessage.setSeverity(FacesMessage.SEVERITY_INFO);
ctx.addMessage(null, theMessage);
}
private Object evaluateEL(String elExpression, Class<?> clazz) {
Object toReturn = null;
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz);
return toReturn;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the pageDescription
*/
public String getPageDescription() {
return pageDescription;
}
/**
* @param pageDescription the pageDescription to set
*/
public void setPageDescription(String pageDescription) {
this.pageDescription = pageDescription;
}
/**
* @return the pageCounter
*/
public int getPageCounter() {
return pageCounter;
}
/**
* @param pageCounter the pageCounter to set
*/
public void setPageCounter(int pageCounter) {
this.pageCounter = pageCounter;
}
}

View File

@ -0,0 +1,38 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Baeldung | The EL Intro</title>
</h:head>
<h:body>
<h:form id="elForm">
<h:messages />
<h:panelGrid columns="2">
<h:outputText value="First Name"/>
<h:inputText id="firstName" binding="#{firstName}" required="true" value="#{ELBean.firstName}"/>
<h:outputText value="Last Name"/>
<h:inputText id="lastName" required="true" value="#{ELBean.lastName}"/>
<h:outputText value="Save by value binding"/>
<h:commandButton value="Save" action="#{ELBean.save}">
</h:commandButton>
<h:outputText value="Evaluate backing bean EL"/>
<h:commandButton value="Save" action="#{ELBean.saveByELEvaluation}">
</h:commandButton>
<h:outputText value="Save by passing value to method"/>
<h:commandButton value="Save" action="#{ELBean.saveFirstName(firstName.value.toString().concat('(passed)'))}"/>
<h:outputText value="JavaScript (click after saving First Name)"/>
<h:button value="Alert" onclick="alert('Hello #{ELBean.firstName}')"/>
</h:panelGrid>
</h:form>
</h:body>
</html>

7
mocks/jmockit/README.md Normal file
View File

@ -0,0 +1,7 @@
=========
## JMockit related tutorials
### Relevant Articles:
- [JMockit 101](http://www.baeldung.com/jmockit-101)

68
mocks/jmockit/pom.xml Normal file
View File

@ -0,0 +1,68 @@
<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>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>jmockit</artifactId>
<name>jmockit</name>
<properties>
<junit.version>4.12</junit.version>
<jmockit.version>1.24</jmockit.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jmockit</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,10 @@
package org.baeldung.mocks.jmockit;
public class Collaborator {
public boolean collaborate(String string){
return false;
}
public void receive(boolean bool){
//NOOP
}
}

View File

@ -0,0 +1,7 @@
package org.baeldung.mocks.jmockit;
public class Model {
public String getInfo(){
return "info";
}
}

View File

@ -0,0 +1,10 @@
package org.baeldung.mocks.jmockit;
public class Performer {
private Collaborator collaborator;
public void perform(Model model){
boolean value = collaborator.collaborate(model.getInfo());
collaborator.receive(value);
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.mocks.jmockit;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.*;
import mockit.integration.junit4.JMockit;
@RunWith(JMockit.class)
public class PerformerTest {
@Injectable
private Collaborator collaborator;
@Tested
private Performer performer;
@Test
public void testThePerformMethod(@Mocked Model model) {
new Expectations() {{
model.getInfo();result = "bar";
collaborator.collaborate("bar"); result = true;
}};
performer.perform(model);
new Verifications() {{
collaborator.receive(true);
}};
}
}

View File

@ -1,11 +1,16 @@
<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>org.baeldung</groupId>
<artifactId>mock-comparisons</artifactId>
<version>0.1-SNAPSHOT</version>
<name>mockito</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>mock-comparisons</artifactId>
<name>mock-comparisons</name>
<properties>
<junit.version>4.12</junit.version>

20
mocks/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<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>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>mocks</artifactId>
<name>mocks</name>
<packaging>pom</packaging>
<modules>
<module>mock-comparisons</module>
<module>jmockit</module>
</modules>
</project>

View File

@ -7,8 +7,12 @@
<name>parent-modules</name>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modules>
<module>apache-fop</module>
<module>assertj</module>
<module>core-java</module>
@ -25,7 +29,7 @@
<module>jooq-spring</module>
<module>json-path</module>
<module>mockito</module>
<module>mock-comparisons</module>
<module>mocks</module>
<module>jee7schedule</module>
<!-- <module>jpa-storedprocedure</module> -->
<module>querydsl</module>

View File

@ -14,30 +14,25 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.10</junit.version>
<spring.version>3.1.0.RELEASE</spring.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<querydsl.version>2.5.0</querydsl.version>
<slf4j.version>1.5.10</slf4j.version>
<java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<spring.version>4.3.1.RELEASE</spring.version>
<hibernate.version>5.2.1.Final</hibernate.version>
<querydsl.version>4.1.3</querydsl.version>
<slf4j.version>1.7.21</slf4j.version>
</properties>
<dependencies>
<!-- QueryDSL -->
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-core</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<scope>provided</scope>
@ -53,7 +48,7 @@
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
<scope>compile</scope>
</dependency>
@ -69,7 +64,7 @@
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.5</version>
<version>1.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
@ -77,8 +72,8 @@
<!-- HSQLDB Dependencies -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb-j5</artifactId>
<version>2.2.4</version>
<artifactId>hsqldb</artifactId>
<version>2.3.4</version>
</dependency>
<!-- Spring Dependencies -->
@ -118,9 +113,9 @@
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@ -128,17 +123,6 @@
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
@ -157,7 +141,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.5.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
@ -168,16 +152,16 @@
<!-- QueryDSL plugin -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>maven-apt-plugin</artifactId>
<version>1.0.3</version>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/metamodel</outputDirectory>
<processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>

View File

@ -10,8 +10,8 @@ import org.baeldung.entity.Person;
import org.baeldung.entity.QPerson;
import org.springframework.stereotype.Repository;
import com.mysema.query.group.GroupBy;
import com.mysema.query.jpa.impl.JPAQuery;
import com.querydsl.core.group.GroupBy;
import com.querydsl.jpa.impl.JPAQuery;
@Repository
public class PersonDaoImpl implements PersonDao {
@ -27,39 +27,39 @@ public class PersonDaoImpl implements PersonDao {
@Override
public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).list(person);
return query.from(person).where(person.firstname.eq(firstname)).fetch();
}
@Override
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person);
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch();
}
@Override
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person);
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch();
}
@Override
public int findMaxAge() {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).list(person.age.max()).get(0);
return query.from(person).select(person.age.max()).fetchFirst();
}
@Override
public Map<String, Integer> findMaxAgeByName() {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));

View File

@ -0,0 +1,56 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class BlogPost {
@Id
@GeneratedValue
private Long id;
private String title;
private String body;
@ManyToOne
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String code) {
this.title = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,55 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String login;
private Boolean disabled;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user")
private Set<BlogPost> blogPosts = new HashSet<>(0);
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String name) {
this.login = name;
}
public Set<BlogPost> getBlogPosts() {
return blogPosts;
}
public void setBlogPosts(Set<BlogPost> blogPosts) {
this.blogPosts = blogPosts;
}
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
}

View File

@ -16,4 +16,17 @@
</properties>
</persistence-unit>
<!-- PersistenceUnit for Intro to QueryDSL -->
<persistence-unit name="org.baeldung.querydsl.intro">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
</properties>
</persistence-unit>
</persistence>

View File

@ -1,12 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<configuration>
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n</Pattern>
</layout>
</appender>
@ -33,10 +30,8 @@
<level value="warn" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
<root level="warn">
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
</configuration>

View File

@ -0,0 +1,215 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.baeldung.querydsl.intro.entities.BlogPost;
import org.baeldung.querydsl.intro.entities.QBlogPost;
import org.baeldung.querydsl.intro.entities.QUser;
import org.baeldung.querydsl.intro.entities.User;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.junit.*;
import static org.junit.Assert.*;
public class QueryDSLTest {
private static EntityManagerFactory emf;
private EntityManager em;
private JPAQueryFactory queryFactory;
@BeforeClass
public static void populateDatabase() {
emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
User user1 = new User();
user1.setLogin("David");
em.persist(user1);
User user2 = new User();
user2.setLogin("Ash");
em.persist(user2);
User user3 = new User();
user3.setLogin("Call");
em.persist(user3);
User user4 = new User();
user4.setLogin("Bishop");
em.persist(user4);
BlogPost blogPost1 = new BlogPost();
blogPost1.setTitle("Hello World!");
blogPost1.setUser(user1);
em.persist(blogPost1);
BlogPost blogPost2 = new BlogPost();
blogPost2.setTitle("My Second Post");
blogPost2.setUser(user1);
em.persist(blogPost2);
BlogPost blogPost3 = new BlogPost();
blogPost3.setTitle("Hello World!");
blogPost3.setUser(user3);
em.persist(blogPost3);
em.getTransaction().commit();
em.close();
}
@Before
public void setUp() {
em = emf.createEntityManager();
em.getTransaction().begin();
queryFactory = new JPAQueryFactory(em);
}
@Test
public void whenFindByLogin_thenShouldReturnUser() {
QUser user = QUser.user;
User aUser = queryFactory.selectFrom(user)
.where(user.login.eq("David"))
.fetchOne();
assertNotNull(aUser);
assertEquals(aUser.getLogin(), "David");
}
@Test
public void whenUsingOrderBy_thenResultsShouldBeOrdered() {
QUser user = QUser.user;
List<User> users = queryFactory.selectFrom(user)
.orderBy(user.login.asc())
.fetch();
assertEquals(users.size(), 4);
assertEquals(users.get(0).getLogin(), "Ash");
assertEquals(users.get(1).getLogin(), "Bishop");
assertEquals(users.get(2).getLogin(), "Call");
assertEquals(users.get(3).getLogin(), "David");
}
@Test
public void whenGroupingByTitle_thenReturnsTuples() {
QBlogPost blogPost = QBlogPost.blogPost;
NumberPath<Long> count = Expressions.numberPath(Long.class, "c");
List<Tuple> userTitleCounts = queryFactory.select(blogPost.title, blogPost.id.count().as(count))
.from(blogPost)
.groupBy(blogPost.title)
.orderBy(count.desc())
.fetch();
assertEquals("Hello World!", userTitleCounts.get(0).get(blogPost.title));
assertEquals(new Long(2), userTitleCounts.get(0).get(count));
assertEquals("My Second Post", userTitleCounts.get(1).get(blogPost.title));
assertEquals(new Long(1), userTitleCounts.get(1).get(count));
}
@Test
public void whenJoiningWithCondition_thenResultCountShouldMatch() {
QUser user = QUser.user;
QBlogPost blogPost = QBlogPost.blogPost;
List<User> users = queryFactory.selectFrom(user)
.innerJoin(user.blogPosts, blogPost)
.on(blogPost.title.eq("Hello World!"))
.fetch();
assertEquals(2, users.size());
}
@Test
public void whenRefiningWithSubquery_thenResultCountShouldMatch() {
QUser user = QUser.user;
QBlogPost blogPost = QBlogPost.blogPost;
List<User> users = queryFactory.selectFrom(user)
.where(user.id.in(
JPAExpressions.select(blogPost.user.id)
.from(blogPost)
.where(blogPost.title.eq("Hello World!"))))
.fetch();
assertEquals(2, users.size());
}
@Test
public void whenUpdating_thenTheRecordShouldChange() {
QUser user = QUser.user;
queryFactory.update(user)
.where(user.login.eq("Ash"))
.set(user.login, "Ash2")
.set(user.disabled, true)
.execute();
em.getTransaction().commit();
em.getTransaction().begin();
assertEquals(Boolean.TRUE,
queryFactory.select(user.disabled)
.from(user)
.where(user.login.eq("Ash2"))
.fetchOne());
}
@Test
public void whenDeleting_thenTheRecordShouldBeAbsent() {
QUser user = QUser.user;
queryFactory.delete(user)
.where(user.login.eq("Bishop"))
.execute();
em.getTransaction().commit();
em.getTransaction().begin();
assertNull(queryFactory.selectFrom(user)
.where(user.login.eq("Bishop"))
.fetchOne());
}
@After
public void tearDown() {
em.getTransaction().commit();
em.close();
}
@AfterClass
public static void afterClass() {
emf.close();
}
}

View File

@ -8,7 +8,7 @@
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa)
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
### Quick Start

View File

@ -11,9 +11,14 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import org.hibernate.envers.Audited;
@NamedNativeQueries({
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
@Entity
@Audited
// @Proxy(lazy = false)
@ -99,5 +104,4 @@ public class Foo implements Serializable {
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,20 @@
DELIMITER //
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
SELECT * FROM foo WHERE name = fooName;
END //
DELIMITER ;
DELIMITER //
CREATE PROCEDURE GetAllFoos()
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
SELECT * FROM foo;
END //
DELIMITER ;

View File

@ -0,0 +1,126 @@
package com.baeldung.persistence.service;
import java.util.List;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertEquals;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.SQLGrammarException;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class)
public class FooStoredProceduresIntegrationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
@Autowired
private SessionFactory sessionFactory;
@Autowired
private IFooService fooService;
private Session session;
@Before
public final void before() {
session = sessionFactory.openSession();
Assume.assumeTrue(getAllFoosExists());
Assume.assumeTrue(getFoosByNameExists());
}
private boolean getFoosByNameExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
.addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
return false;
}
}
private boolean getAllFoosExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
.addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
return false;
}
}
@After
public final void after() {
session.close();
}
@Test
public final void getAllFoosUsingStoredProcedures() {
fooService.create(new Foo(randomAlphabetic(6)));
// Stored procedure getAllFoos using createSQLQuery
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(
Foo.class);
@SuppressWarnings("unchecked")
List<Foo> allFoos = sqlQuery.list();
for (Foo foo : allFoos) {
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
}
assertEquals(allFoos.size(), fooService.findAll().size());
// Stored procedure getAllFoos using a Named Query
Query namedQuery = session.getNamedQuery("callGetAllFoos");
@SuppressWarnings("unchecked")
List<Foo> allFoos2 = namedQuery.list();
for (Foo foo : allFoos2) {
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
}
assertEquals(allFoos2.size(), fooService.findAll().size());
}
@Test
public final void getFoosByNameUsingStoredProcedures() {
fooService.create(new Foo("NewFooName"));
// Stored procedure getFoosByName using createSQLQuery()
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)")
.addEntity(Foo.class).setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName = sqlQuery.list();
for (Foo foo : allFoosByName) {
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
}
// Stored procedure getFoosByName using getNamedQuery()
Query namedQuery = session.getNamedQuery("callGetFoosByName")
.setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) {
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
}
}
}

View File

@ -146,6 +146,17 @@
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware.kryo</groupId>
<artifactId>kryo</artifactId>
<version>2.24.0</version>
</dependency>
</dependencies>
<build>

View File

@ -3,11 +3,13 @@ package org.baeldung.config;
import java.text.SimpleDateFormat;
import java.util.List;
import org.baeldung.config.converter.KryoHttpMessageConverter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@ -33,7 +35,8 @@ public class WebConfig extends WebMvcConfigurerAdapter {
builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
messageConverters.add(new ProtobufHttpMessageConverter());
messageConverters.add(new KryoHttpMessageConverter());
super.configureMessageConverters(messageConverters);
}

View File

@ -0,0 +1,57 @@
package org.baeldung.config.converter;
import java.io.IOException;
import org.baeldung.web.dto.Foo;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* An {@code HttpMessageConverter} that can read and write Kryo messages.
*/
public class KryoHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final MediaType KRYO = new MediaType("application", "x-kryo");
private static final ThreadLocal<Kryo> kryoThreadLocal = new ThreadLocal<Kryo>() {
@Override
protected Kryo initialValue() {
final Kryo kryo = new Kryo();
kryo.register(Foo.class, 1);
return kryo;
}
};
public KryoHttpMessageConverter() {
super(KRYO);
}
@Override
protected boolean supports(final Class<?> clazz) {
return Object.class.isAssignableFrom(clazz);
}
@Override
protected Object readInternal(final Class<? extends Object> clazz, final HttpInputMessage inputMessage) throws IOException {
final Input input = new Input(inputMessage.getBody());
return kryoThreadLocal.get().readClassAndObject(input);
}
@Override
protected void writeInternal(final Object object, final HttpOutputMessage outputMessage) throws IOException {
final Output output = new Output(outputMessage.getBody());
kryoThreadLocal.get().writeClassAndObject(output, object);
output.flush();
}
@Override
protected MediaType getDefaultContentType(final Object object) {
return KRYO;
}
}

View File

@ -4,6 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import org.baeldung.web.dto.Foo;
import org.baeldung.web.dto.FooProtos;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
@ -38,4 +39,9 @@ public class FooController {
return foo;
}
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" })
@ResponseBody
public FooProtos.Foo findProtoById(@PathVariable final long id) {
return FooProtos.Foo.newBuilder().setId(1).setName("Foo Name").build();
}
}

View File

@ -0,0 +1,620 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: FooProtos.proto
package org.baeldung.web.dto;
public final class FooProtos {
private FooProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface FooOrBuilder extends
// @@protoc_insertion_point(interface_extends:baeldung.Foo)
com.google.protobuf.MessageOrBuilder {
/**
* <code>required int64 id = 1;</code>
*/
boolean hasId();
/**
* <code>required int64 id = 1;</code>
*/
long getId();
/**
* <code>required string name = 2;</code>
*/
boolean hasName();
/**
* <code>required string name = 2;</code>
*/
java.lang.String getName();
/**
* <code>required string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
}
/**
* Protobuf type {@code baeldung.Foo}
*/
public static final class Foo extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:baeldung.Foo)
FooOrBuilder {
// Use Foo.newBuilder() to construct.
private Foo(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Foo defaultInstance;
public static Foo getDefaultInstance() {
return defaultInstance;
}
public Foo getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Foo(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
id_ = input.readInt64();
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
name_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class);
}
public static com.google.protobuf.Parser<Foo> PARSER =
new com.google.protobuf.AbstractParser<Foo>() {
public Foo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Foo(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<Foo> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private long id_;
/**
* <code>required int64 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 id = 1;</code>
*/
public long getId() {
return id_;
}
public static final int NAME_FIELD_NUMBER = 2;
private java.lang.Object name_;
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
id_ = 0L;
name_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasName()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt64(1, id_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getNameBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, id_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getNameBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.baeldung.web.dto.FooProtos.Foo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code baeldung.Foo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:baeldung.Foo)
org.baeldung.web.dto.FooProtos.FooOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class);
}
// Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
id_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor;
}
public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() {
return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance();
}
public org.baeldung.web.dto.FooProtos.Foo build() {
org.baeldung.web.dto.FooProtos.Foo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.baeldung.web.dto.FooProtos.Foo buildPartial() {
org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.id_ = id_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.name_ = name_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.baeldung.web.dto.FooProtos.Foo) {
return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) {
if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this;
if (other.hasId()) {
setId(other.getId());
}
if (other.hasName()) {
bitField0_ |= 0x00000002;
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasId()) {
return false;
}
if (!hasName()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.baeldung.web.dto.FooProtos.Foo parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private long id_ ;
/**
* <code>required int64 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 id = 1;</code>
*/
public long getId() {
return id_;
}
/**
* <code>required int64 id = 1;</code>
*/
public Builder setId(long value) {
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
/**
* <code>required int64 id = 1;</code>
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = 0L;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:baeldung.Foo)
}
static {
defaultInstance = new Foo(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:baeldung.Foo)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_baeldung_Foo_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_baeldung_Foo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" +
"\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" +
".dtoB\tFooProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_baeldung_Foo_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_baeldung_Foo_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_baeldung_Foo_descriptor,
new java.lang.String[] { "Id", "Name", });
}
// @@protoc_insertion_point(outer_class_scope)
}

View File

@ -7,7 +7,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.baeldung.config.converter.KryoHttpMessageConverter;
import org.baeldung.web.dto.Foo;
import org.baeldung.web.dto.FooProtos;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.http.HttpEntity;
@ -17,6 +19,7 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.client.RestTemplate;
@ -94,6 +97,38 @@ public class SpringHttpMessageConvertersIntegrationTestsCase {
Assert.assertEquals(resource.getId(), fooResponse.getId());
}
@Test
public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() {
final String URI = BASE_URI + "foos/{id}";
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter()));
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF));
final HttpEntity<String> entity = new HttpEntity<String>(headers);
final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1");
final FooProtos.Foo resource = response.getBody();
assertThat(resource, notNullValue());
}
@Test
public void givenConsumingKryo_whenReadingTheFoo_thenCorrect() {
final String URI = BASE_URI + "foos/{id}";
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new KryoHttpMessageConverter()));
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(KryoHttpMessageConverter.KRYO));
final HttpEntity<String> entity = new HttpEntity<String>(headers);
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
final Foo resource = response.getBody();
assertThat(resource, notNullValue());
}
// UTIL
private List<HttpMessageConverter<?>> getMessageConverters() {