This commit is contained in:
DOHA
2017-04-19 13:10:07 +02:00
parent 0f532fa429
commit 51d28bcc95
170 changed files with 866 additions and 173 deletions

View File

@@ -5,3 +5,4 @@
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)

View File

@@ -12,3 +12,4 @@
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)

View File

@@ -92,3 +92,9 @@
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)

3
cucumber/README.md Normal file
View File

@@ -0,0 +1,3 @@
### Relevant articles
- [Cucumber and Scenario Outline](http://www.baeldung.com/cucumber-scenario-outline)

3
groovy-spock/README.md Normal file
View File

@@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Testing with Spock and Groovy](http://www.baeldung.com/groovy-spock)

View File

@@ -1 +1,2 @@
## Relevant articles:
### Relevant articles:
- [New Stream, Comparator and Collector Functionality in Guava 21](http://www.baeldung.com/guava-21-new)

View File

@@ -27,3 +27,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional)
- [Map Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-map)
- [Jackson Streaming API](http://www.baeldung.com/jackson-streaming-api)

View File

@@ -2,3 +2,4 @@
- [Introduction to Javaslang](http://www.baeldung.com/javaslang)
- [Guide to Try in Javaslang](http://www.baeldung.com/javaslang-try)
- [Guide to Pattern Matching in Javaslang](http://www.baeldung.com/javaslang-pattern-matching)
- [Property Testing Example With Javaslang](http://www.baeldung.com/javaslang-property-testing)

View File

@@ -1,3 +1,4 @@
### Relevant Articles:
- [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition)
- [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json)
- [Converters, Listeners and Validators in Java EE 7](http://www.baeldung.com/java-ee7-converter-listener-validator)

View File

@@ -1,3 +1,8 @@
### Relevant articles
- [Intro to JHipster](http://www.baeldung.com/jhipster)
# baeldung
This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8).

3
jws/README.md Normal file
View File

@@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to the Java Web Start](http://www.baeldung.com/java-web-start)

View File

@@ -1,3 +1,10 @@
### Relevant articles
- [Guide to Reactive Microservices Using Lagom Framework](http://www.baeldung.com/lagom-reactive-microservices)
Steps to setup from scratch
1) Create sbt build file "build.sbt"

View File

@@ -7,6 +7,8 @@
- [Introduction to Javassist](http://www.baeldung.com/javassist)
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
- [Intro to JaVer](http://www.baeldung.com/javers)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

16
mybatis/.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
*.class
.settings
.project
*.log
#folders#
/target
/src/main/webapp/WEB-INF/classes
*/META-INF/*
/testdb1
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -3,7 +3,6 @@ package com.baeldung.mybatis.utils;
import com.baeldung.mybatis.mapper.AddressMapper;
import com.baeldung.mybatis.mapper.PersonMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
@@ -12,8 +11,6 @@ import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtil {
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

View File

@@ -1,145 +0,0 @@
package com.baeldung.mybatis.mapper;
import com.baeldung.mybatis.model.Address;
import com.baeldung.mybatis.model.Person;
import com.baeldung.mybatis.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import static junit.framework.TestCase.assertEquals;
public class PersonMapperTest {
SqlSession session;
@Before
public void setup() throws SQLException {
session = MyBatisUtil.buildqlSessionFactory().openSession();
createTables(session);
}
private void createTables(SqlSession session) throws SQLException {
String createPersonTable = "create table person (" + "personId integer not null generated always as"
+ " identity (start with 1, increment by 1), " + "name varchar(30) not null, "
+ "constraint primary_key_person primary key (personId))";
String createAddressTable = "create table address (" + "addressId integer not null generated always as"
+ " identity (start with 1, increment by 1), " + "streetAddress varchar(300), personId integer, "
+ "constraint primary_key_address primary key (addressId))";
String alterTable = "ALTER TABLE "
+ " address ADD CONSTRAINT fk_person FOREIGN KEY (personId) REFERENCES person (personId)";
session.getConnection().createStatement().execute(createPersonTable);
session.getConnection().createStatement().execute(createAddressTable);
session.getConnection().createStatement().execute(alterTable);
}
@Test
public void whenPersonAdressSaved_ThenPersonAddressCanBeQueried() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
addressMapper.saveAddress(address);
Person returnedPerson = personMapper.getPersonById(id);
assertEquals("Baljeet S", returnedPerson.getName());
assertEquals("Pune", returnedPerson.getAddresses().get(0).getStreetAddress());
}
@Test
public void whenPersonSaved_ThenPersonCanBeQueried() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
addressMapper.saveAddress(address);
Person returnedPerson = personMapper.getPerson(id);
assertEquals("Baljeet S", returnedPerson.getName());
}
@Test
public void whenPersonUpdated_ThenPersonIsChanged() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
addressMapper.saveAddress(address);
personMapper.updatePerson(new Person(id, "Baljeet1"));
Person returnedPerson = personMapper.getPerson(id);
assertEquals("Baljeet1", returnedPerson.getName());
}
@Test
public void whenPersoSaved_ThenMapIsReturned() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
addressMapper.saveAddress(address);
Map<Integer, Person> returnedPerson = personMapper.getAllPerson();
assertEquals(1, returnedPerson.size());
}
@Test
public void whenPersonSearched_ThenResultIsReturned() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
addressMapper.saveAddress(address);
Person returnedPerson = personMapper.getPersonByName("Baljeet S");
assertEquals("Baljeet S", returnedPerson.getName());
}
@Test
public void whenAddressSearched_ThenResultIsReturned() {
Person person = new Person("Baljeet S");
Address address = new Address("Pune");
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Integer id = personMapper.save(person);
address.setPersonId(id);
AddressMapper addressMapper = session.getMapper(AddressMapper.class);
Integer addressId = addressMapper.saveAddress(address);
Address returnedAddress = addressMapper.getAddresses(addressId);
assertEquals("Pune", returnedAddress.getStreetAddress());
}
@After
public void cleanup() throws SQLException {
session.getConnection().createStatement().execute("drop table address");
session.getConnection().createStatement().execute("drop table person");
session.close();
}
}

View File

@@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Ratpack](http://www.baeldung.com/ratpack)
- [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice)

View File

@@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/)
- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock)
- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing)
- [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing)

View File

@@ -6,3 +6,4 @@
### Relevant Articles:
- [A Guide to RESTEasy](http://www.baeldung.com/resteasy-tutorial)
- [RESTEasy Client API](http://www.baeldung.com/resteasy-client-tutorial)
- [CORS in JAX-RS](http://www.baeldung.com/cors-in-jax-rs)

3
solr/README.md Normal file
View File

@@ -0,0 +1,3 @@
### Relevant articles
- [Full-text Search with Solr](http://www.baeldung.com/full-text-search-with-solr)

View File

@@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles
- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests)
- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web)

View File

@@ -20,3 +20,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler)
- [Guide to Spring Retry](http://www.baeldung.com/spring-retry)
- [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli)
- [JasperReports with Spring](http://www.baeldung.com/spring-jasper)

View File

@@ -2,7 +2,11 @@ package com.baeldung.springamqpsimple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<<<<<<< HEAD
=======
import org.springframework.amqp.rabbit.annotation.RabbitListener;
>>>>>>> eugenp/master
import org.springframework.stereotype.Component;
@Component
@@ -10,6 +14,7 @@ public class MessageConsumer {
private static final Logger logger = LoggerFactory.getLogger(MessageConsumer.class);
@RabbitListener(queues = {SpringAmqpConfig.queueName})
public void receiveMessage(String message) {
logger.info("Received Message: " + message);
}

View File

@@ -1,6 +1,10 @@
package com.baeldung.springamqpsimple;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
@@ -32,7 +36,7 @@ public class SpringAmqpConfig {
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
@@ -44,5 +48,4 @@ public class SpringAmqpConfig {
MessageListenerAdapter listenerAdapter(MessageConsumer messageReceiver) {
return new MessageListenerAdapter(messageReceiver, "receiveMessage");
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.springamqpsimple.broadcast;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Declarable;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.util.Arrays;
import java.util.List;
@Configuration
@Profile("!test")
public class BroadcastConfig {
public final static String fanoutQueue1Name = "com.baeldung.spring-amqp-simple.fanout.queue1";
public final static String fanoutQueue2Name = "com.baeldung.spring-amqp-simple.fanout.queue2";
public final static String fanoutExchangeName = "com.baeldung.spring-amqp-simple.fanout.exchange";
public final static String topicQueue1Name = "com.baeldung.spring-amqp-simple.topic.queue1";
public final static String topicQueue2Name = "com.baeldung.spring-amqp-simple.topic.queue2";
public final static String topicExchangeName = "com.baeldung.spring-amql-simple.topic.exchange";
@Bean
public List<Declarable> topicBindings() {
Queue topicQueue1 = new Queue(topicQueue1Name, false);
Queue topicQueue2 = new Queue(topicQueue2Name, false);
TopicExchange topicExchange = new TopicExchange(topicExchangeName);
return Arrays.asList(
topicQueue1,
topicQueue2,
topicExchange,
BindingBuilder.bind(topicQueue1).to(topicExchange).with("*.important.*"),
BindingBuilder.bind(topicQueue2).to(topicExchange).with("user.#")
);
}
@Bean
public List<Declarable> fanoutBindings() {
Queue fanoutQueue1 = new Queue(fanoutQueue1Name, false);
Queue fanoutQueue2 = new Queue(fanoutQueue2Name, false);
FanoutExchange fanoutExchange = new FanoutExchange(fanoutExchangeName);
return Arrays.asList(
fanoutQueue1,
fanoutQueue2,
fanoutExchange,
BindingBuilder.bind(fanoutQueue1).to(fanoutExchange),
BindingBuilder.bind(fanoutQueue2).to(fanoutExchange)
);
}
@Bean
public SimpleRabbitListenerContainerFactory container(ConnectionFactory connectionFactory, SimpleRabbitListenerContainerFactoryConfigurer configurer) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.springamqpsimple.broadcast;
import com.baeldung.springamqpsimple.MessageConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class BroadcastMessageConsumers {
private static final Logger logger = LoggerFactory.getLogger(MessageConsumer.class);
@RabbitListener(queues = {BroadcastConfig.fanoutQueue1Name})
public void receiveMessageFromFanout1(String message) {
logger.info("Received fanout 1 message: " + message);
}
@RabbitListener(queues = {BroadcastConfig.fanoutQueue2Name})
public void receiveMessageFromFanout2(String message) {
logger.info("Received fanout 2 message: " + message);
}
@RabbitListener(queues = {BroadcastConfig.topicQueue1Name})
public void receiveMessageFromTopic1(String message) {
logger.info("Received topic 1 message: " + message);
}
@RabbitListener(queues = {BroadcastConfig.topicQueue2Name})
public void receiveMessageFromTopic2(String message) {
logger.info("Received topic 2 message: " + message);
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.springamqpsimple.broadcast;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class BroadcastMessageController {
private final BroadcastMessageProducer messageProducer;
@Autowired
public BroadcastMessageController(BroadcastMessageProducer messageProducer) {
this.messageProducer = messageProducer;
}
@RequestMapping(value="/broadcast", method= RequestMethod.POST)
@ResponseStatus(value= HttpStatus.CREATED)
public void sendMessage(@RequestBody String message) {
messageProducer.sendMessages(message);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.springamqpsimple.broadcast;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BroadcastMessageProducer {
private final RabbitTemplate rabbitTemplate;
@Autowired
public BroadcastMessageProducer(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessages(String message) {
rabbitTemplate.convertAndSend(BroadcastConfig.fanoutExchangeName, "", message);
rabbitTemplate.convertAndSend(BroadcastConfig.topicExchangeName, "user.not-important.info", message);
rabbitTemplate.convertAndSend(BroadcastConfig.topicExchangeName, "user.important.error", message);
}
}

View File

@@ -1,4 +1,5 @@
spring:
rabbitmq:
username: baeldung
password: baeldung
username: guest
password: guest
host: 10.10.10.105

View File

@@ -0,0 +1,48 @@
package broadcast;
import com.baeldung.springamqpsimple.broadcast.BroadcastConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class BroadcastMessageControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private RabbitTemplate rabbitTemplate;
@Test
public void whenPostingMessage_thenMessageIsCreated() {
final String message = "Hello World!";
ResponseEntity<Void> responseEntity = restTemplate.postForEntity("/broadcast", message, Void.class);
assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
}
@Test
public void whenPostingMessage_thenMessageIsSentToBroker() {
final String message = "Hello World!";
restTemplate.postForEntity("/broadcast", message, Void.class);
verify(rabbitTemplate).convertAndSend(BroadcastConfig.fanoutExchangeName, "", message);
verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.not-important.info", message);
verify(rabbitTemplate).convertAndSend(BroadcastConfig.topicExchangeName, "user.important.error", message);
}
}

3
spring-aop/README.md Normal file
View File

@@ -0,0 +1,3 @@
### Relevant articles
- [Implementing a Custom Spring AOP Annotation](http://www.baeldung.com/spring-aop-annotation)

View File

@@ -0,0 +1,59 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>greeter-spring-boot-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
<greeter.version>0.0.1-SNAPSHOT</greeter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>greeter</artifactId>
<version>${greeter.version}</version>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,48 @@
package com.baeldung.greeter.autoconfigure;
import static com.baeldung.greeter.GreeterConfigParams.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.greeter.Greeter;
import com.baeldung.greeter.GreetingConfig;
@Configuration
@ConditionalOnClass(Greeter.class)
@EnableConfigurationProperties(GreeterProperties.class)
public class GreeterAutoConfiguration {
@Autowired
private GreeterProperties greeterProperties;
@Bean
@ConditionalOnMissingBean
public GreetingConfig greeterConfig() {
String userName = greeterProperties.getUserName() == null ? System.getProperty("user.name") : greeterProperties.getUserName();
String morningMessage = greeterProperties.getMorningMessage() == null ? "Good Morning" : greeterProperties.getMorningMessage();
String afternoonMessage = greeterProperties.getAfternoonMessage() == null ? "Good Afternoon" : greeterProperties.getAfternoonMessage();
String eveningMessage = greeterProperties.getEveningMessage() == null ? "Good Evening" : greeterProperties.getEveningMessage();
String nightMessage = greeterProperties.getNightMessage() == null ? "Good Night" : greeterProperties.getNightMessage();
GreetingConfig greetingConfig = new GreetingConfig();
greetingConfig.put(USER_NAME, userName);
greetingConfig.put(MORNING_MESSAGE, morningMessage);
greetingConfig.put(AFTERNOON_MESSAGE, afternoonMessage);
greetingConfig.put(EVENING_MESSAGE, eveningMessage);
greetingConfig.put(NIGHT_MESSAGE, nightMessage);
return greetingConfig;
}
@Bean
@ConditionalOnMissingBean
public Greeter greeter(GreetingConfig greetingConfig) {
return new Greeter(greetingConfig);
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.greeter.autoconfigure;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "baeldung.greeter")
public class GreeterProperties {
private String userName;
private String morningMessage;
private String afternoonMessage;
private String eveningMessage;
private String nightMessage;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMorningMessage() {
return morningMessage;
}
public void setMorningMessage(String morningMessage) {
this.morningMessage = morningMessage;
}
public String getAfternoonMessage() {
return afternoonMessage;
}
public void setAfternoonMessage(String afternoonMessage) {
this.afternoonMessage = afternoonMessage;
}
public String getEveningMessage() {
return eveningMessage;
}
public void setEveningMessage(String eveningMessage) {
this.eveningMessage = eveningMessage;
}
public String getNightMessage() {
return nightMessage;
}
public void setNightMessage(String nightMessage) {
this.nightMessage = nightMessage;
}
}

View File

@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration

View File

@@ -0,0 +1,39 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>greeter-spring-boot-sample-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath></relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<greeter-starter.version>0.0.1-SNAPSHOT</greeter-starter.version>
</properties>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>greeter-spring-boot-starter</artifactId>
<version>${greeter-starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,25 @@
package com.baeldung.greeter.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.greeter.Greeter;
@SpringBootApplication
public class GreeterSampleApplication implements CommandLineRunner {
@Autowired
private Greeter greeter;
public static void main(String[] args) {
SpringApplication.run(GreeterSampleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
String message = greeter.greet();
System.out.println(message);
}
}

View File

@@ -0,0 +1,2 @@
baeldung.greeter.userName=Baeldung
baeldung.greeter.afternoonMessage=Woha\ Afternoon

View File

@@ -0,0 +1,50 @@
package com.baeldung.greeter.sample;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.greeter.Greeter;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = GreeterSampleApplication.class)
public class GreeterSampleApplicationTest {
@Autowired
private Greeter greeter;
@Test
public void givenMorningTime_ifMorningMessage_thenSuccess() {
String expected = "Hello Baeldung, Good Morning";
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 6, 0));
assertEquals(expected, actual);
}
@Test
public void givenAfternoonTime_ifAfternoonMessage_thenSuccess() {
String expected = "Hello Baeldung, Woha Afternoon";
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 13, 0));
assertEquals(expected, actual);
}
@Test
public void givenEveningTime_ifEveningMessage_thenSuccess() {
String expected = "Hello Baeldung, Good Evening";
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 19, 0));
assertEquals(expected, actual);
}
@Test
public void givenNightTime_ifNightMessage_thenSuccess() {
String expected = "Hello Baeldung, Good Night";
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 21, 0));
assertEquals(expected, actual);
}
}

View File

@@ -0,0 +1,51 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>greeter-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<greeter.version>0.0.1-SNAPSHOT</greeter.version>
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>greeter-spring-boot-autoconfigure</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>greeter</artifactId>
<version>${greeter.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,19 @@
# Greeter App
This app takes in the user's name and messages for different times of day as configuration parameters and outptus the greeting messge. For example it will take the name **John** and the message for morning time as **Good Morning** and output the message **Hello John, Good Morning**.
## Usage
Create and populate the class `GreetingConfig`, instantiate a `Greeter` using the `GreetingConfig` and use it get greeting messages:
```java
GreetingConfig greetingConfig = new GreetingConfig();
greetingConfig.put(USER_NAME, "World");
greetingConfig.put(MORNING_MESSAGE, "Good Morning");
greetingConfig.put(AFTERNOON_MESSAGE, "Good Afternoon");
greetingConfig.put(EVENING_MESSAGE, "Good Evening");
greetingConfig.put(NIGHT_MESSAGE, "Good Night");
Greeter greeter = new Greeter(greetingConfig);
greeter.greet();
```

View File

@@ -0,0 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>greeter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,35 @@
package com.baeldung.greeter;
import static com.baeldung.greeter.GreeterConfigParams.*;
import java.time.LocalDateTime;
public class Greeter {
private GreetingConfig greetingConfig;
public Greeter(GreetingConfig greetingConfig) {
this.greetingConfig = greetingConfig;
}
public String greet(LocalDateTime localDateTime) {
String name = greetingConfig.getProperty(USER_NAME);
int hourOfDay = localDateTime.getHour();
if (hourOfDay >= 5 && hourOfDay < 12) {
return String.format("Hello %s, %s", name, greetingConfig.get(MORNING_MESSAGE));
} else if (hourOfDay >= 12 && hourOfDay < 17) {
return String.format("Hello %s, %s", name, greetingConfig.get(AFTERNOON_MESSAGE));
} else if (hourOfDay >= 17 && hourOfDay < 20) {
return String.format("Hello %s, %s", name, greetingConfig.get(EVENING_MESSAGE));
} else {
return String.format("Hello %s, %s", name, greetingConfig.get(NIGHT_MESSAGE));
}
}
public String greet() {
return greet(LocalDateTime.now());
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.greeter;
public class GreeterConfigParams {
public static final String USER_NAME = "user.name";
public static final String MORNING_MESSAGE = "morning.message";
public static final String AFTERNOON_MESSAGE = "afternoon.message";
public static final String EVENING_MESSAGE = "evening.message";
public static final String NIGHT_MESSAGE = "night.message";
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.greeter;
import java.util.Properties;
public class GreetingConfig extends Properties{
private static final long serialVersionUID = 5662570853707247891L;
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.greeter;
import static com.baeldung.greeter.GreeterConfigParams.*;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import org.junit.BeforeClass;
import org.junit.Test;
public class GreeterTest {
private static GreetingConfig greetingConfig;
@BeforeClass
public static void initalizeGreetingConfig() {
greetingConfig = new GreetingConfig();
greetingConfig.put(USER_NAME, "World");
greetingConfig.put(MORNING_MESSAGE, "Good Morning");
greetingConfig.put(AFTERNOON_MESSAGE, "Good Afternoon");
greetingConfig.put(EVENING_MESSAGE, "Good Evening");
greetingConfig.put(NIGHT_MESSAGE, "Good Night");
}
@Test
public void givenMorningTime_ifMorningMessage_thenSuccess() {
String expected = "Hello World, Good Morning";
Greeter greeter = new Greeter(greetingConfig);
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 6, 0));
assertEquals(expected, actual);
}
@Test
public void givenAfternoonTime_ifAfternoonMessage_thenSuccess() {
String expected = "Hello World, Good Afternoon";
Greeter greeter = new Greeter(greetingConfig);
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 13, 0));
assertEquals(expected, actual);
}
@Test
public void givenEveningTime_ifEveningMessage_thenSuccess() {
String expected = "Hello World, Good Evening";
Greeter greeter = new Greeter(greetingConfig);
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 19, 0));
assertEquals(expected, actual);
}
@Test
public void givenNightTime_ifNightMessage_thenSuccess() {
String expected = "Hello World, Good Night";
Greeter greeter = new Greeter(greetingConfig);
String actual = greeter.greet(LocalDateTime.of(2017, 3, 1, 21, 0));
assertEquals(expected, actual);
}
}

View File

@@ -0,0 +1,34 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-boot-custom-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<modules>
<module>greeter</module>
<module>greeter-spring-boot-autoconfigure</module>
<module>greeter-spring-boot-starter</module>
<module>greeter-spring-boot-sample-app</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -18,3 +18,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Create a Custom FailureAnalyzer with Spring Boot](http://www.baeldung.com/spring-boot-failure-analyzer)
- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
- [Dynamic DTO Validation Config Retrieved from DB](http://www.baeldung.com/spring-dynamic-dto-validation)
- [Custom Information in Spring Boot Info Endpoint](http://www.baeldung.com/spring-boot-info-actuator-custom)
- [Using @JsonComponent in Spring Boot](http://www.baeldung.com/spring-boot-jsoncomponent)

View File

@@ -5,9 +5,10 @@ import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@@ -15,16 +16,16 @@ import org.springframework.web.bind.annotation.RestController;
public class EmployeeRestController {
@Autowired
EmployeeService employeeService;
private EmployeeService employeeService;
@RequestMapping(value = "/employees", method = RequestMethod.POST)
@PostMapping("/employees")
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
HttpStatus status = HttpStatus.CREATED;
Employee saved = employeeService.save(employee);
return new ResponseEntity<>(saved, status);
}
@RequestMapping(value = "/employees", method = RequestMethod.GET)
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}

View File

@@ -13,7 +13,7 @@ import org.springframework.stereotype.Service;
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
private EmployeeRepository employeeRepository;
@Override
public Optional<Employee> getEmployeeById(Long id) {

View File

@@ -20,10 +20,10 @@ import org.springframework.test.context.junit4.SpringRunner;
public class EmployeeRepositoryTest {
@Autowired
TestEntityManager entityManager;
private TestEntityManager entityManager;
@Autowired
EmployeeRepository employeeRepository;
private EmployeeRepository employeeRepository;
@Test
public void whenFindByName_thenReturnEmployee() {

View File

@@ -34,10 +34,10 @@ import org.springframework.test.web.servlet.MockMvc;
public class EmployeeRestControllerIntTest {
@Autowired
MockMvc mvc;
private MockMvc mvc;
@Autowired
EmployeeRepository repository;
private EmployeeRepository repository;
@After
public void resetDb() {

View File

@@ -33,10 +33,10 @@ import org.springframework.test.web.servlet.MockMvc;
public class EmployeeRestControllerTest {
@Autowired
MockMvc mvc;
private MockMvc mvc;
@MockBean
EmployeeService service;
private EmployeeService service;
@Before
public void setUp() throws Exception {

View File

@@ -34,10 +34,10 @@ public class EmployeeServiceImplTest {
}
@Autowired
EmployeeService employeeService;
private EmployeeService employeeService;
@MockBean
EmployeeRepository employeeRepository;
private EmployeeRepository employeeRepository;
@Before
public void setUp() {

View File

@@ -1,5 +1,6 @@
package com.baeldung.value;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
@@ -30,6 +31,9 @@ public class ValuesApp {
@Value("${priority}")
private String prioritySystemProperty;
@Value("${listOfValues}")
private String[] valuesArray;
@Value("#{systemProperties['priority']}")
private String spelValue;
@@ -60,6 +64,7 @@ public class ValuesApp {
System.out.println(systemValue);
System.out.println(someDefault);
System.out.println(prioritySystemProperty);
System.out.println(Arrays.toString(valuesArray));
System.out.println(spelValue);
System.out.println(spelSomeDefault);
System.out.println(someBeanValue);

View File

@@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to GemFire with Spring Data](http://www.baeldung.com/spring-data-gemfire)

View File

@@ -1,4 +1,10 @@
# Spring Kakfa
### Relevant articles
- [Intro to Apache Kafka with Spring](http://www.baeldung.com/spring-kafka)
# Spring Kafka
This is a simple Spring Boot app to demonstrate sending and receiving of messages in Kafka using spring-kafka.
@@ -12,18 +18,18 @@ As Kafka topics are not created automatically by default, this application requi
When the application runs successfully, following output is logged on to console (along with spring logs):
#### Message received from the 'baeldung' topic by the basic listeners with groups foo and bar
>Received Messasge in group 'foo': Hello, World!<br>
Received Messasge in group 'bar': Hello, World!
>Received Message in group 'foo': Hello, World!<br>
Received Message in group 'bar': Hello, World!
#### Message received from the 'baeldung' topic, with the partition info
>Received Messasge: Hello, World! from partition: 0
>Received Message: Hello, World! from partition: 0
#### Message received from the 'partitioned' topic, only from specific partitions
>Received Message: Hello To Partioned Topic! from partition: 0<br>
Received Message: Hello To Partioned Topic! from partition: 3
#### Message received from the 'filtered' topic after filtering
>Recieved Message in filtered listener: Hello Baeldung!
>Received Message in filtered listener: Hello Baeldung!
#### Message (Serialized Java Object) received from the 'greeting' topic
>Recieved greeting message: Greetings, World!!
>Received greeting message: Greetings, World!!

View File

@@ -21,3 +21,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts)
- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings)
- [Uploading and Displaying Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files)
- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator)

View File

@@ -13,3 +13,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder)
- [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs)
- [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type)
- [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring)
- [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate)

View File

@@ -0,0 +1,3 @@
### Relevant articles
- [Returning an Image or a File with Spring](http://www.baeldung.com/spring-controller-return-image-file)

Some files were not shown because too many files have changed in this diff Show More