How to stop container when all the partitions are paused? - java

I have a use case where I am creating dynamic listeners based on API calls. After receiving a certain message, I am pausing the partition individually. For example, If I received a message with offset 100, then that partition will be paused. And this will be done for all partitions.
After all the partitions are paused, I want to stop the container.
This is my code -
public class OffsetBasedMessageListener implements ConsumerAwareMessageListener<String, String> {
#Override
public void onMessage(ConsumerRecord<String, String> consumerRecord, Consumer<?, ?> consumer) {
if (consumerRecord.offset() == 100) {
consumer.pause(Collections.singleton(new TopicPartition(consumerRecord.topic(),
consumerRecord.partition())));
}
}
Now, I have an EventListener configured which will be triggered when the container is Idle.
#EventListener
public void onIdle(ListenerContainerIdleEvent event) {
Collection<TopicPartition> collection = event.getContainer(ConcurrentMessageListenerContainer.class).getAssignedPartitions();
for (TopicPartition topicPartition: collection) {
System.out.println(
event.getContainer(ConcurrentMessageListenerContainer.class).isPartitionPaused(topicPartition));
}
}
So, what I am doing now is checking if all partitions are paused then I'll stop the container. But isPartitionPaused always returns false, even though it should return true.
I am using SpringBoot with SpringKafka.
Can someone tell me what I am doing wrong? or Is there another way to achieve this?
Thanks

You shouldn't pause the consumer directly - the container doesn't know that you have paused it; hence it returns false.
Call pausePartition on the container instead.
Note that either way, the consumer won't actually pause until all the records from the previous poll are processed. Set max.poll.records to 1 to pause immediately.
EDIT
This works just fine for me...
#SpringBootApplication
#RestController
public class So67430862Application {
private static final Logger LOG = LoggerFactory.getLogger(So67430862Application.class);
public static void main(String[] args) {
SpringApplication.run(So67430862Application.class, args);
}
Set<ConcurrentMessageListenerContainer<String, String>> containers = ConcurrentHashMap.newKeySet();
int id;
#Autowired
Creator creator;
#PostMapping(path = "/send/{topic}")
public void sendFoo(#PathVariable String topic) {
ConcurrentMessageListenerContainer<String, String> container = this.creator.create(topic);
container.getContainerProperties().setGroupId("group" + ++id);
container.getContainerProperties().setMessageListener(new Listener(container));
this.containers.add(container);
container.start();
}
#EventListener
public void idle(ListenerContainerIdleEvent event) {
ConcurrentMessageListenerContainer<String, String> container =
event.getContainer(ConcurrentMessageListenerContainer.class);
if (this.containers.contains(container)) {
boolean allPaused = container.getAssignedPartitions()
.stream()
.map(part -> container.isPartitionPaused(part))
.allMatch(paused -> paused);
LOG.info("All paused? {}", allPaused);
if (allPaused) {
container.stop(() -> { });
this.containers.remove(container);
}
}
}
// #Bean
// public NewTopic topic() {
// return TopicBuilder.name("so67430862").partitions(5).replicas(1).build();
// }
//
//
// #Bean
// public ApplicationRunner runner(KafkaTemplate<String, String> template) {
// return args -> {
// IntStream.range(0, 5).forEach(p -> {
// IntStream.range(0, 10).forEach(i ->template.send("so67430862", p, null, "test"));
// });
// };
// }
}
#Component
class Creator {
private final ConcurrentKafkaListenerContainerFactory<String, String> factory;
Creator(ConcurrentKafkaListenerContainerFactory<String, String> factory) {
this.factory = factory;
}
ConcurrentMessageListenerContainer<String, String> create(String topic) {
return this.factory.createContainer(topic);
}
}
class Listener extends AbstractConsumerSeekAware implements MessageListener<String, String> {
private static final Logger LOG = LoggerFactory.getLogger(Listener.class);
final ConcurrentMessageListenerContainer<String, String> container;
Listener(ConcurrentMessageListenerContainer<String, String> container) {
this.container = container;
}
#Override
public void onMessage(ConsumerRecord<String, String> data) {
LOG.info(ListenerUtils.recordToString(data, true));
if (data.offset() == 5) {
LOG.info("Pausing partition {}", data.partition());
this.container.pausePartition(new TopicPartition(data.topic(), data.partition()));
}
}
#Override
public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
callback.seekToBeginning(assignments.keySet());
}
}
spring.kafka.consumer.max-poll-records=1
spring.kafka.listener.idle-event-interval=5000
2021-05-10 11:51:15.792 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#0
2021-05-10 11:51:15.797 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#1
2021-05-10 11:51:15.799 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#2
2021-05-10 11:51:15.801 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#3
2021-05-10 11:51:15.803 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#4
2021-05-10 11:51:15.809 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-0#5
2021-05-10 11:51:15.809 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : Pausing partition 0
2021-05-10 11:51:15.814 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#0
2021-05-10 11:51:15.816 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#1
2021-05-10 11:51:15.819 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#2
2021-05-10 11:51:15.823 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#3
2021-05-10 11:51:15.828 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#4
2021-05-10 11:51:15.831 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-1#5
2021-05-10 11:51:15.831 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : Pausing partition 1
2021-05-10 11:51:15.835 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#0
2021-05-10 11:51:15.838 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#1
2021-05-10 11:51:15.841 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#2
2021-05-10 11:51:15.844 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#3
2021-05-10 11:51:15.846 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#4
2021-05-10 11:51:15.849 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-4#5
2021-05-10 11:51:15.850 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : Pausing partition 4
2021-05-10 11:51:15.854 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#0
2021-05-10 11:51:15.858 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#1
2021-05-10 11:51:15.861 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#2
2021-05-10 11:51:15.864 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#3
2021-05-10 11:51:15.866 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#4
2021-05-10 11:51:15.871 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-2#5
2021-05-10 11:51:15.871 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : Pausing partition 2
2021-05-10 11:51:15.875 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#0
2021-05-10 11:51:15.877 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#1
2021-05-10 11:51:15.880 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#2
2021-05-10 11:51:15.883 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#3
2021-05-10 11:51:15.886 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#4
2021-05-10 11:51:15.889 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : so67430862-3#5
2021-05-10 11:51:15.889 INFO 58682 --- [ consumer-0-C-1] com.example.demo.Listener : Pausing partition 3
2021-05-10 11:51:20.893 INFO 58682 --- [ consumer-0-C-1] com.example.demo.So67430862Application : All paused? true
2021-05-10 11:51:20.895 INFO 58682 --- [ consumer-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator : [Consumer clientId=consumer-group1-1, groupId=group1] Revoke previously assigned partitions so67430862-0, so67430862-1, so67430862-4, so67430862-2, so67430862-3
2021-05-10 11:51:20.895 INFO 58682 --- [ consumer-0-C-1] o.s.k.l.KafkaMessageListenerContainer : group1: partitions revoked: [so67430862-0, so67430862-1, so67430862-4, so67430862-2, so67430862-3]
2021-05-10 11:51:20.895 INFO 58682 --- [ consumer-0-C-1] o.a.k.c.c.internals.AbstractCoordinator : [Consumer clientId=consumer-group1-1, groupId=group1] Member consumer-group1-1-be137c2c-2bbf-4235-a143-15d33a0cfe52 sending LeaveGroup request to coordinator localhost:9092 (id: 2147483647 rack: null) due to the consumer unsubscribed from all topics
2021-05-10 11:51:20.896 INFO 58682 --- [ consumer-0-C-1] o.a.k.clients.consumer.KafkaConsumer : [Consumer clientId=consumer-group1-1, groupId=group1] Unsubscribed all topics or patterns and assigned partitions
2021-05-10 11:51:20.896 INFO 58682 --- [ consumer-0-C-1] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService
2021-05-10 11:51:20.897 INFO 58682 --- [ consumer-0-C-1] org.apache.kafka.common.metrics.Metrics : Metrics scheduler closed
2021-05-10 11:51:20.897 INFO 58682 --- [ consumer-0-C-1] org.apache.kafka.common.metrics.Metrics : Closing reporter org.apache.kafka.common.metrics.JmxReporter
2021-05-10 11:51:20.898 INFO 58682 --- [ consumer-0-C-1] org.apache.kafka.common.metrics.Metrics : Metrics reporters closed
2021-05-10 11:51:20.901 INFO 58682 --- [ consumer-0-C-1] o.a.kafka.common.utils.AppInfoParser : App info kafka.consumer for consumer-group1-1 unregistered
2021-05-10 11:51:20.902 INFO 58682 --- [ consumer-0-C-1] essageListenerContainer$ListenerConsumer : group1: Consumer stopped
The commented out code creates a topic with 5 partitions and 10 records in each; the listener pauses each partition at offset 5. As you can see we don't get the rest of the records.

Related

Not able to update table contents through postman using Spring Boot

package com.shashank.topic;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
public Topic() {
}
public Topic(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Repository is configured like this
package com.shashank.topic;
import org.springframework.data.repository.CrudRepository;
public interface TopicRepository extends CrudRepository<Topic, String> {
/***
* CURD OPERATIONS
* getAllTopics()
* getTopic(String id)
* updateTopic(Topic topic)
* deleteTopic(String id)
* */
}
This is another class
package com.shashank.topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
public List<Topic> getAllTopics() {
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics::add);
return topics;
}
public Optional<Topic> getTopic(String id) {
return topicRepository.findById(id);
}
public void addTopic(Topic topic) {
topicRepository.save(topic);
}
public void updateTopic(String id, Topic topic) {
topicRepository.save(topic);
}
public void deleteTopic(String id) {
topicRepository.deleteById(id);
}
}
I'm able to post the topics in my table and get as well from the postman but when I try to use put, to update the contents of the table, nothing changes.
I was trying to put the below command to update the table
{
"id": "javascript",
"name": "Update javascript",
"description": "Update javascript Description"
}
where "javascript" was already in the table, with name as "javascript" and description as "javascript description"
Here is my spring console log
2021-03-03 17:33:05.625 INFO 9848 --- [ main]
com.shashank.CourseApiDataApplication : Starting
CourseApiDataApplication using Java 13.0.2 on DESKTOP-FGT8D3V with PID 9848
(D:\MavenProjects\course-api-data\target\classes started by shash in
D:\MavenProjects\course-api-data)
2021-03-03 17:33:05.628 INFO 9848 --- [ main]
com.shashank.CourseApiDataApplication : No active profile set, falling
back to default profiles: default
2021-03-03 17:33:06.262 INFO 9848 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA
repositories in DEFAULT mode.
2021-03-03 17:33:06.290 INFO 9848 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository
scanning in 23 ms. Found 1 JPA repository interfaces.
2021-03-03 17:33:06.618 INFO 9848 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s):
8080 (http)
2021-03-03 17:33:06.623 INFO 9848 --- [ main]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-03 17:33:06.624 INFO 9848 --- [ main]
org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache
Tomcat/9.0.43]
2021-03-03 17:33:06.720 INFO 9848 --- [ main] o.a.c.c.C.[Tomcat].
[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-03 17:33:06.720 INFO 9848 --- [ main]
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext:
initialization completed in 1039 ms
2021-03-03 17:33:06.876 INFO 9848 --- [ main]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2021-03-03 17:33:06.901 INFO 9848 --- [ main]
org.hibernate.Version : HHH000412: Hibernate ORM core
version 5.4.28.Final
2021-03-03 17:33:06.964 INFO 9848 --- [ main]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons
Annotations {5.1.2.Final}
2021-03-03 17:33:07.016 INFO 9848 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-03-03 17:33:07.018 WARN 9848 --- [ main]
com.zaxxer.hikari.util.DriverDataSource : Registered driver with
driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, trying
direct instantiation.
2021-03-03 17:33:07.269 INFO 9848 --- [ main]
com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not
support get/set network timeout for connections. (Feature not implemented: No
details.)
2021-03-03 17:33:07.271 INFO 9848 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-03-03 17:33:07.281 INFO 9848 --- [ main]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.DerbyTenSevenDialect
2021-03-03 17:33:07.911 INFO 9848 --- [ main]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform
implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-03-03 17:33:07.916 INFO 9848 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2021-03-03 17:33:08.134 WARN 9848 --- [ main]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled
by default. Therefore, database queries may be performed during view
rendering. Explicitly configure spring.jpa.open-in-view to disable this
warning
2021-03-03 17:33:08.220 INFO 9848 --- [ main]
o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService
'applicationTaskExecutor'
2021-03-03 17:33:08.460 INFO 9848 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080
(http) with context path ''
2021-03-03 17:33:08.469 INFO 9848 --- [ main]
com.shashank.CourseApiDataApplication : Started CourseApiDataApplication
in 3.207 seconds (JVM running for 3.973)
There is something unusual with your Id. Why did you consider Id as String?
It should be Long or int, So maybe your id is your main problem.
Also, It would be better that put the controller to help us to debug better. Anyway, there are some ideas.
public void updateTopic(String id, Topic topic) {
Topic myTopic = topicRepository.findById(id);
topicRepository.save(myTopic);
}
Controller
#PutMapping("/topics")
private Topic update(#RequestBody Topic topic){
topicService.updateTopic(topic);
return topic;
}
Strongly recommend you to change your ID from string to int or Long and try the above solution.

NullPointer Exception Repository Spring Boot Jpa

I am making a basic application to send an insert to a database, as a test I have been executing a simple findAll () to test the repository, but it always gives me NullPointer
I am aware that it is something very basic and also that I am missing something.
Thank you.
This is the main
#SpringBootApplication
public class ExampleApplication {
#Autowired
private static DataRepository dataRepository;
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
System.out.println(dataRepository.findAll());
}
}
Model
#Entity
public class Data {
#Id
private Long id;
private String content;
public Data(Long id, String content) {
super();
this.id = id;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public String toString() {
return "Data [id=" + id + ", content=" + content + "]";
}
}
Repository
#Repository
public interface DataRepository extends JpaRepository<Data, Long> {
}
Controller
#RestController
public class DataController {
#Autowired
private DataRepository dataRepository;
#GetMapping("/show")
public List<Data> findCities(Data data) {
return dataRepository.findAll();
}
}
Error
2020-04-07 10:27:14.323 INFO 19892 --- [ main] com.example.demo.ExampleApplication : Starting ExampleApplication on DESKTOP-ARNRCSA with PID 19892 (C:\Users\David\Documents\workspace-spring-tool-suite-4-4.5.1.RELEASE\example\target\classes started by David in C:\Users\David\Documents\workspace-spring-tool-suite-4-4.5.1.RELEASE\example)
2020-04-07 10:27:14.326 INFO 19892 --- [ main] com.example.demo.ExampleApplication : No active profile set, falling back to default profiles: default
2020-04-07 10:27:14.739 INFO 19892 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-07 10:27:14.794 INFO 19892 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 48ms. Found 1 JPA repository interfaces.
2020-04-07 10:27:15.147 INFO 19892 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-04-07 10:27:15.261 INFO 19892 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-04-07 10:27:15.300 INFO 19892 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-07 10:27:15.363 INFO 19892 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-04-07 10:27:15.490 INFO 19892 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-04-07 10:27:15.588 INFO 19892 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2020-04-07 10:27:15.832 INFO 19892 --- [ main] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.example.demo.Data (class must be instantiated by Interceptor)
2020-04-07 10:27:16.057 INFO 19892 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-04-07 10:27:16.063 INFO 19892 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-04-07 10:27:16.066 INFO 19892 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: private static com.example.demo.DataRepository com.example.demo.ExampleApplication.dataRepository
2020-04-07 10:27:16.417 INFO 19892 --- [ main] com.example.demo.ExampleApplication : Started ExampleApplication in 2.399 seconds (JVM running for 3.041)
Exception in thread "main" java.lang.NullPointerException
at com.example.demo.ExampleApplication.main(ExampleApplication.java:17)
2020-04-07 10:27:16.422 INFO 19892 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-07 10:27:16.424 INFO 19892 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-04-07 10:27:16.428 INFO 19892 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource
try this
#SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
DataRepository dataRepository = context.getBean(DataRepository.class);
System.out.println(dataRepository.findAll());
}
}
you can not use autowire with static field unless you use postConstruct
Jpa needs defaut constructor so put it into your Data class

Why Spring Integration Channel can't properly sort my messages?

I have this easy pipeline configuration. Just trying to tinker around with Spring Integration. However, the output is weird.
This is my code:
#Slf4j
#Configuration
#RequiredArgsConstructor
public class FileToConsoleIntegration {
#Bean public IntegrationFlow fileToConsoleIntegrationFlow() {
return IntegrationFlows.from(sameSourceDirectory(), spec -> spec.poller(this::getPollerSpec))
.log(LoggingHandler.Level.WARN, "before.sort", m -> m.getHeaders().get("file_name"))
.channel(MessageChannels.queue(5))
.log(LoggingHandler.Level.INFO, "after.sort", m -> m.getHeaders().get("file_name"))
.channel(alphabeticallyReversed())
.log(LoggingHandler.Level.ERROR, "after.sort", m -> m.getHeaders().get("file_name"))
.handle(logInfoMessageHandler())
.get();
}
private PollerSpec getPollerSpec(PollerFactory p) {
return p
.fixedRate(1000)
.maxMessagesPerPoll(10);
}
#Bean public MessageSource<File> sameSourceDirectory() {
FileReadingMessageSource messageSource = new FileReadingMessageSource();
messageSource.setDirectory(new File("input_dir"));
return messageSource;
}
#Bean public MessageHandler logInfoMessageHandler() {
return message ->
log.info("Handling message with headers: {} and payload: {}",
message.getHeaders(), message.getPayload());
}
#Bean
public PriorityChannel alphabeticallyReversed() {
return MessageChannels.priority()
.capacity(5)
.comparator(Comparator.comparing(getFilename(), Comparator.reverseOrder()))
.get();
}
private Function<Message<?>, String> getFilename() {
return a -> (String) a.getHeaders().get("file_name");
}
}
This is my input:
/input_dir
01_zhasdfha.txt
02_usfhahjf.txt
05_bsdfasdf.txt
06_asdfasdf.txt
This is my output:
2019-10-10 17:24:48.604 WARN 46024 --- [ask-scheduler-1] before.sort : 01_zhasdfha.txt
2019-10-10 17:24:48.605 INFO 46024 --- [ask-scheduler-1] after.sort : 01_zhasdfha.txt
2019-10-10 17:24:48.605 ERROR 46024 --- [ask-scheduler-2] after.sort : 01_zhasdfha.txt
2019-10-10 17:24:48.605 WARN 46024 --- [ask-scheduler-1] before.sort : 02_usfhahjf.txt
2019-10-10 17:24:48.605 INFO 46024 --- [ask-scheduler-1] after.sort : 02_usfhahjf.txt
2019-10-10 17:24:48.606 WARN 46024 --- [ask-scheduler-1] before.sort : 05_bsdfasdf.txt
2019-10-10 17:24:48.606 ERROR 46024 --- [ask-scheduler-2] after.sort : 02_usfhahjf.txt
2019-10-10 17:24:48.606 INFO 46024 --- [ask-scheduler-1] after.sort : 05_bsdfasdf.txt
2019-10-10 17:24:48.606 ERROR 46024 --- [ask-scheduler-2] after.sort : 05_bsdfasdf.txt
2019-10-10 17:24:48.606 WARN 46024 --- [ask-scheduler-1] before.sort : 06_asdfasdf.txt
2019-10-10 17:24:48.606 INFO 46024 --- [ask-scheduler-1] after.sort : 06_asdfasdf.txt
2019-10-10 17:24:48.606 ERROR 46024 --- [ask-scheduler-2] after.sort : 06_asdfasdf.txt
2019-10-10 17:24:48.605 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/01_zhasdfha.txt, id=5fcfb1cc-7187-86a8-dcf4-23e9b31b2376, file_name=01_zhasdfha.txt, file_relativePath=01_zhasdfha.txt, timestamp=1570728288603} and payload: input_dir/01_zhasdfha.txt
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/06_asdfasdf.txt, id=cf1a978b-c577-bb14-cf45-cf5b7ce8f2a7, file_name=06_asdfasdf.txt, file_relativePath=06_asdfasdf.txt, timestamp=1570728288606} and payload: input_dir/06_asdfasdf.txt
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/05_bsdfasdf.txt, id=c81dbcdc-6dd0-b549-4923-fe567ff6ca23, file_name=05_bsdfasdf.txt, file_relativePath=05_bsdfasdf.txt, timestamp=1570728288606} and payload: input_dir/05_bsdfasdf.txt
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/02_usfhahjf.txt, id=3371143b-a097-a9ee-e303-d4d359875188, file_name=02_usfhahjf.txt, file_relativePath=02_usfhahjf.txt, timestamp=1570728288605} and payload: input_dir/02_usfhahjf.txt
2019-10-10 17:24:48.609 INFO 46024 --- [ main] c.s.i.siexample.SiExampleApplication : Started SiExampleApplication in 0.743 seconds (JVM running for 1.232)
Desired output:
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/06_asdfasdf.txt, id=cf1a978b-c577-bb14-cf45-cf5b7ce8f2a7, file_name=06_asdfasdf.txt, file_relativePath=06_asdfasdf.txt, timestamp=1570728288606} and payload: input_dir/06_asdfasdf.txt
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/05_bsdfasdf.txt, id=c81dbcdc-6dd0-b549-4923-fe567ff6ca23, file_name=05_bsdfasdf.txt, file_relativePath=05_bsdfasdf.txt, timestamp=1570728288606} and payload: input_dir/05_bsdfasdf.txt
2019-10-10 17:24:48.607 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/02_usfhahjf.txt, id=3371143b-a097-a9ee-e303-d4d359875188, file_name=02_usfhahjf.txt, file_relativePath=02_usfhahjf.txt, timestamp=1570728288605} and payload: input_dir/02_usfhahjf.txt
2019-10-10 17:24:48.605 INFO 46024 --- [ask-scheduler-3] c.s.i.s.i.FileToConsoleIntegration : Handling message with headers: {file_originalFile=input_dir/01_zhasdfha.txt, id=5fcfb1cc-7187-86a8-dcf4-23e9b31b2376, file_name=01_zhasdfha.txt, file_relativePath=01_zhasdfha.txt, timestamp=1570728288603} and payload: input_dir/01_zhasdfha.txt
The difference between the desired output and current output is that the order is messed. How can I fix that?
Just because you have set the queue sizes to 5, doesn't mean the framework will wait for all 5 before the downstream poller pulls them. If there is a poller waiting for a message (the default is to wait up to 1 second on each poll), it will be received immediately. You could try setting the poller's receive timeout to 0 but there will still be a (small) race condition where messages can be fetched earlier than you expected.
It would be better to use an aggregator followed by a transformer to sort the List<> (or a custom output processor on the aggregator) and then a splitter.

Spring Boot not able to detect the values that I have key in

I have problem regarding inserting data from angular to spring boot by rest API using mongodb atlas as the database. I have create another variable called numbers to test it out. But it turns out that the values was able to capture on angular but not in spring boot. Below are my codes:
Angular code:
<div class="todo-content">
<h1 class="page-title">My Todos</h1>
<div class="todo-create">
<form #todoForm="ngForm" (ngSubmit) = "createTodo(todoForm)" novalidate>
<input type="text" id="title" class="form-control" placeholder="Type a todo and press enter..."
required
name="title" [(ngModel)]="newTodo.title"
#title="ngModel" >
<input type="text" id="numbers" class="form-control" placeholder="Type a todo and press enter..."
required
name="numbers" [(ngModel)]="newTodo.numbers"
#numbers="ngModel" >
<div *ngIf="title.errors && title.dirty"
class="alert alert-danger">
<div [hidden]="!title.errors.required">
Title is required.
</div>
</div>
<td><button class="btn btn-danger" (ngSubmit) = "createTodo(todoForm)"> submit User</button></td>
</form>
</div>
<ul class="todo-list">
<li *ngFor="let todo of todos" [class.completed]= "todo.completed === true" >
<div class="todo-row" *ngIf="!editing || editingTodo.id != todo.id">
<a class="todo-completed" (click)="toggleCompleted(todo)">
<i class="material-icons toggle-completed-checkbox"></i>
</a>
<span class="todo-title">
{{todo.title}}
</span>
<span class="todo-actions">
<a (click)="editTodo(todo)">
<i class="material-icons edit">edit</i>
</a>
<a (click)="deleteTodo(todo.id)">
<i class="material-icons delete">clear</i>
</a>
</span>
</div>
<div class="todo-edit" *ngIf="editing && editingTodo.id === todo.id">
<input class="form-control" type="text"
[(ngModel)]="editingTodo.title" required>
<span class="edit-actions">
<a (click)="updateTodo(editingTodo)">
<i class="material-icons">done</i>
</a>
<a (click)="clearEditing()">
<i class="material-icons">clear</i>
</a>
</span>
</div>
</li>
</ul>
<div class="no-todos" *ngIf="todos && todos.length == 0">
<p>No Todos Found!</p>
</div>
todo-list.component.ts
import { Component, Input, OnInit } from '#angular/core';
import { TodoService } from './todo.service';
import { Todo } from './todo';
import {NgForm} from '#angular/forms';
#Component({
selector: 'todo-list',
templateUrl: './todo-list.component.html'
})
export class TodoListComponent implements OnInit {
todos: Todo[];
newTodo: Todo = new Todo();
editing: boolean = false;
editingTodo: Todo = new Todo();
constructor(
private todoService: TodoService,
) {}
ngOnInit(): void {
this.getTodos();
}
getTodos(): void {
this.todoService.getTodos()
.then(todos => this.todos = todos );
}
createTodo(todoForm: NgForm): void {
console.log(this.newTodo.numbers);
console.log(todoForm);
this.todoService.createTodo(this.newTodo)
.then(createTodo => {
todoForm.reset();
this.newTodo = new Todo();
this.todos.unshift(createTodo)
});
}
deleteTodo(id: string): void {
this.todoService.deleteTodo(id)
.then(() => {
this.todos = this.todos.filter(todo => todo.id != id);
});
}
updateTodo(todoData: Todo): void {
console.log(todoData);
this.todoService.updateTodo(todoData)
.then(updatedTodo => {
let existingTodo = this.todos.find(todo => todo.id === updatedTodo.id);
Object.assign(existingTodo, updatedTodo);
this.clearEditing();
});
}
toggleCompleted(todoData: Todo): void {
todoData.completed = !todoData.completed;
this.todoService.updateTodo(todoData)
.then(updatedTodo => {
let existingTodo = this.todos.find(todo => todo.id === updatedTodo.id);
Object.assign(existingTodo, updatedTodo);
});
}
editTodo(todoData: Todo): void {
this.editing = true;
Object.assign(this.editingTodo, todoData);
}
clearEditing(): void {
this.editingTodo = new Todo();
this.editing = false;
}
}
todo.service.ts
import { Injectable } from '#angular/core';
import { Todo } from './todo';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TodoService {
private baseUrl = 'http://localhost:8080';
constructor(private http: Http) { }
getTodos(): Promise<Todo[]> {
return this.http.get(this.baseUrl + '/api/todos/')
.toPromise()
.then(response => response.json() as Todo[])
.catch(this.handleError);
}
createTodo(todoData: Todo): Promise<Todo> {
console.log("inside service");
console.log(todoData);
console.log(todoData.numbers);
return this.http.post(this.baseUrl + '/api/todos/', todoData, "a")
.toPromise().then(response => response.json() as Todo)
.catch(this.handleError);
}
updateTodo(todoData: Todo): Promise<Todo> {
return this.http.put(this.baseUrl + '/api/todos/' + todoData.id, todoData)
.toPromise()
.then(response => response.json() as Todo)
.catch(this.handleError);
}
deleteTodo(id: string): Promise<any> {
return this.http.delete(this.baseUrl + '/api/todos/' + id)
.toPromise()
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('Some error occured', error);
return Promise.reject(error.message || error);
}
}
todo.ts
export class Todo {
id: string;
title: string;
numbers: string;
completed: boolean;
createdAt: Date;
}
Spring Boot:
TodoController
package com.example.todoapp.controllers;
import javax.validation.Valid;
import com.example.todoapp.models.Todo;
import com.example.todoapp.repositories.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api")
#CrossOrigin("*")
public class TodoController {
#Autowired
TodoRepository todoRepository;
#GetMapping("/todos")
public List<Todo> getAllTodos() {
Sort sortByCreatedAtDesc = new Sort(Sort.Direction.DESC, "createdAt");
return todoRepository.findAll(sortByCreatedAtDesc);
}
#PostMapping("/todos")
public Todo createTodo(#Valid #RequestBody Todo todo, String numbers) {
System.out.println(todo.getNumber());
System.out.println(todo.getTitle());
System.out.println(numbers+ "numbers");
todo.setCompleted(false);
return todoRepository.save(todo);
}
#PostMapping("/contact")
public Todo createContact(#Valid #RequestBody Todo todo) {
todo.setCompleted(false);
return todoRepository.save(todo);
}
#GetMapping(value="/todos/{id}")
public ResponseEntity<Todo> getTodoById(#PathVariable("id") String id) {
return todoRepository.findById(id)
.map(todo -> ResponseEntity.ok().body(todo))
.orElse(ResponseEntity.notFound().build());
}
#PutMapping(value="/todos/{id}")
public ResponseEntity<Todo> updateTodo(#PathVariable("id") String id,
#Valid #RequestBody Todo todo) {
return todoRepository.findById(id)
.map(todoData -> {
todoData.setTitle(todo.getTitle());
todoData.setCompleted(todo.getCompleted());
Todo updatedTodo = todoRepository.save(todoData);
return ResponseEntity.ok().body(updatedTodo);
}).orElse(ResponseEntity.notFound().build());
}
#DeleteMapping(value="/todos/{id}")
public ResponseEntity<?> deleteTodo(#PathVariable("id") String id) {
return todoRepository.findById(id)
.map(todo -> {
todoRepository.deleteById(id);
return ResponseEntity.ok().build();
}).orElse(ResponseEntity.notFound().build());
}
}
TodoRepository
package com.example.todoapp.repositories;
import com.example.todoapp.models.Todo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
}
Todo
package com.example.todoapp.models;
import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="todos")
#JsonIgnoreProperties(value = {"createdAt"}, allowGetters = true)
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=100)
#Indexed(unique=true)
private String title;
#Size(max=100)
#Indexed(unique=false)
private String numbers;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title, String numbers) {
this.title = title;
this.numbers= numbers;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getNumber() {
return numbers;
}
public void setNumber(String number) {
this.numbers = number;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s',numbers='%s', completed='%s']",
id, title,numbers, completed);
}
}
Error from angular:
fff
todo-list.component.ts:32 NgForm {_submitted: true, ngSubmit: EventEmitter, form: FormGroup}
todo.service.ts:20 inside service
todo.service.ts:21 Todo {a: true, title: "My Web Application went blank on private mode", numbers: "fff"}
todo.service.ts:22 fff
Error From spring boot:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2018-11-10 16:13:21.940 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : Starting TodoappApplication on NCS-180417AV05 with PID 9436 (E:\Project\portfolio_website\templates\spring-boot-mongodb-angular-todo-app-master\spring-boot-backendv2\target\classes started by royyzh in E:\Project\portfolio_website\templates\spring-boot-mongodb-angular-todo-app-master\spring-boot-backendv2)
2018-11-10 16:13:21.944 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : No active profile set, falling back to default profiles: default
2018-11-10 16:13:21.992 INFO 9436 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#327b636c: startup date [Sat Nov 10 16:13:21 SGT 2018]; root of context hierarchy
2018-11-10 16:13:23.367 INFO 9436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-11-10 16:13:23.393 INFO 9436 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-10 16:13:23.393 INFO 9436 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-11-10 16:13:23.399 INFO 9436 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_181\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:/Program Files/Java/jre1.8.0_181/bin/server;C:/Program Files/Java/jre1.8.0_181/bin;C:/Program Files/Java/jre1.8.0_181/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\TortoiseSVN\bin;C:\Program Files\PuTTY\;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Git\cmd;C:\apache-maven-3.5.4\bin;C:\curl;C:\Program Files\nodejs\;D:\eclipes java ee\mongodb-win32-x86_64-2008plus-ssl-4.0.3\bin;C:\Users\royyzh\AppData\Roaming\npm;C:\Users\royyzh\AppData\Local\Programs\EmEditor;D:\sts-bundle\sts-3.9.5.RELEASE;;.]
2018-11-10 16:13:23.692 INFO 9436 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-10 16:13:23.693 INFO 9436 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1705 ms
2018-11-10 16:13:23.792 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-10 16:13:23.797 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-10 16:13:24.698 INFO 9436 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='RoyYipProjectCluster-shard-0'}
2018-11-10 16:13:24.698 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:24.746 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:24.747 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:25.123 INFO 9436 --- [ main] org.mongodb.driver.cluster : No server chosen by com.mongodb.Mongo$4#2e52fb3e from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
2018-11-10 16:13:25.138 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:4829}] to royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.149 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=9102165, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621241304334}
2018-11-10 16:13:25.158 INFO 9436 --- [ main] org.mongodb.driver.cluster : No server chosen by WritableServerSelector from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=9102165, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621241304334}]}. Waiting for 30000 ms before timing out
2018-11-10 16:13:25.201 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:4482}] to royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.204 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:4726}] to royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.209 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=7415729, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621301859146}
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5801588, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000005, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621302845567}
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max election id to 7fffffff0000000000000005 from replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max set version to 1 from replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Discovered replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.296 INFO 9436 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:4, serverValue:4726}] to royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.698 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#327b636c: startup date [Sat Nov 10 16:13:21 SGT 2018]; root of context hierarchy
2018-11-10 16:13:25.763 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/contact],methods=[POST]}" onto public com.example.todoapp.models.Todo com.example.todoapp.controllers.TodoController.createContact(com.example.todoapp.models.Todo)
2018-11-10 16:13:25.765 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.getTodoById(java.lang.String)
2018-11-10 16:13:25.766 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos],methods=[POST]}" onto public com.example.todoapp.models.Todo com.example.todoapp.controllers.TodoController.createTodo(com.example.todoapp.models.Todo,java.lang.String)
2018-11-10 16:13:25.767 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos],methods=[GET]}" onto public java.util.List<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.getAllTodos()
2018-11-10 16:13:25.767 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[PUT]}" onto public org.springframework.http.ResponseEntity<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.updateTodo(java.lang.String,com.example.todoapp.models.Todo)
2018-11-10 16:13:25.768 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<?> com.example.todoapp.controllers.TodoController.deleteTodo(java.lang.String)
2018-11-10 16:13:25.771 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-11-10 16:13:25.771 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-10 16:13:25.793 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.793 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.840 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.995 INFO 9436 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-10 16:13:26.060 INFO 9436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-10 16:13:26.064 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : Started TodoappApplication in 4.443 seconds (JVM running for 6.802)
2018-11-10 16:13:32.981 INFO 9436 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-11-10 16:13:32.981 INFO 9436 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-11-10 16:13:33.000 INFO 9436 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms
null
My Web Application went blank on private mode
nullnumbers
null
My Web Application went blank on private mode
nullnumbers
What should I do to make it work? Which part of my code needs to be changed and why?
There are a few mistakes. Here are the fixes you need to make.
this.http.post(this.baseUrl + '/api/todos/', todoData, "a")
What is the "a" doing in the POST call. You can remove that in createTodo method declared in todo.service.ts
In Todo.java the variable is declared as numbers and the setter is declared as
public void setNumber(String number) {
Change this to
public void setNumbers(String numbers) {
this.numbers = numbers;
}
Now you can update createTodo method in TodoController.java to the following
#PostMapping("/todos")
public Todo createTodo(#Valid #RequestBody Todo todo) {

How to consume APIs with RESTTemplate in Spring

Apologizes in advance for such a stupid question but I'm attempting to create consume a Rest API from a site RESTcountries.eu that generates the following data:
[{"name":"Estonia","topLevelDomain":[".ee"],"alpha2Code":"EE","alpha3Code":"EST","callingCodes":["372"],"capital":"Tallinn","altSpellings":["EE","Eesti","Republic of Estonia","Eesti Vabariik"],"region":"Europe","subregion":"Northern Europe","population":1315944,"latlng":[59.0,26.0],"demonym":"Estonian","area":45227.0,"gini":36.0,"timezones":["UTC+02:00"],"borders":["LVA","RUS"],"nativeName":"Eesti","numericCode":"233","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"et","iso639_2":"est","name":"Estonian","nativeName":"eesti"}],"translations":{"de":"Estland","es":"Estonia","fr":"Estonie","ja":"エストニア","it":"Estonia","br":"Estônia","pt":"Estónia"},"flag":"https://restcountries.eu/data/est.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}]}]
I seem to get an error everytime I attempt to run the program. Thanks in advance for any help.
I have the classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class BaseCountries {
private String name;
private List<String> topLevelDomain;
private String alpha2Code;
private String alpha3Code;
private List<String> callingCodes;
private String capital;
private List<String> altSpellings;
private String relevance;
private String region;
private String subregion;
private Integer population;
private List<Double> latlng;
private String demonym;
private Double area;
private Double gini;
private List<String> timezones;
private List<String> borders;
private String nativeName;
private String numericCode;
//Getters and Setters
}
}
and this as my Main:
#SpringBootApplication
#ComponentScan("com.ronone.service")
public class WorldStatsApplication {
private static final Logger log = LoggerFactory.getLogger(WorldStatsApplication.class);
public static void main(String[] args) {
String uri = "https://restcountries.eu/rest/v2/capital/{capital}";
SpringApplication.run(WorldStatsApplication.class, args);
RestTemplate restTemplate = new RestTemplate();
BaseCountries country = restTemplate.getForObject(uri, BaseCountries.class, "London");
System.out.println("Country Name: " + country.getCapital());
}
}
Print Trace:
2017-06-17 22:21:58.336 INFO 1062 --- [ restartedMain] c.r.WorldStats.WorldStatsApplication : Starting WorldStatsApplication on Ronalds-MacBook-Pro.local with PID 1062 (started by ronaldpitt in /Users/ronaldpitt/Desktop/Java Apps/WorldStats)
2017-06-17 22:21:58.338 INFO 1062 --- [ restartedMain] c.r.WorldStats.WorldStatsApplication : No active profile set, falling back to default profiles: default
2017-06-17 22:21:58.413 INFO 1062 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4984bfe5: startup date [Sat Jun 17 22:21:58 EDT 2017]; root of context hierarchy
2017-06-17 22:21:59.432 INFO 1062 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2017-06-17 22:22:00.833 INFO 1062 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-17 22:22:00.855 INFO 1062 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-06-17 22:22:00.856 INFO 1062 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-06-17 22:22:00.982 INFO 1062 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-06-17 22:22:00.983 INFO 1062 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2576 ms
2017-06-17 22:22:01.207 INFO 1062 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-17 22:22:01.213 INFO 1062 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-17 22:22:01.214 INFO 1062 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-17 22:22:01.214 INFO 1062 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-17 22:22:01.214 INFO 1062 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-17 22:22:02.125 INFO 1062 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4984bfe5: startup date [Sat Jun 17 22:21:58 EDT 2017]; root of context hierarchy
2017-06-17 22:22:02.243 INFO 1062 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-06-17 22:22:02.245 INFO 1062 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-06-17 22:22:02.306 INFO 1062 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-17 22:22:02.306 INFO 1062 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-17 22:22:02.329 INFO 1062 --- [ restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : Detected #ExceptionHandler methods in repositoryRestExceptionHandler
2017-06-17 22:22:02.436 INFO 1062 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-17 22:22:02.587 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4984bfe5: startup date [Sat Jun 17 22:21:58 EDT 2017]; root of context hierarchy
2017-06-17 22:22:02.603 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/ || ],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositoryController.optionsForRepositories()
2017-06-17 22:22:02.604 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/ || ],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.RepositoryLinksResource> org.springframework.data.rest.webmvc.RepositoryController.listRepositories()
2017-06-17 22:22:02.604 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/ || ],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryController.headForRepositories()
2017-06-17 22:22:02.608 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
2017-06-17 22:22:02.608 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}/{propertyId}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
2017-06-17 22:22:02.609 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String) throws java.lang.Exception
2017-06-17 22:22:02.609 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}],methods=[GET],produces=[application/x-spring-data-compact+json || text/uri-list]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReferenceCompact(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
2017-06-17 22:22:02.610 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}],methods=[PATCH || PUT || POST],consumes=[application/json || application/x-spring-data-compact+json || text/uri-list],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.createPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.http.HttpMethod,org.springframework.hateoas.Resources<java.lang.Object>,java.io.Serializable,java.lang.String) throws java.lang.Exception
2017-06-17 22:22:02.610 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}/{property}/{propertyId}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReferenceId(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,java.lang.String) throws java.lang.Exception
2017-06-17 22:22:02.616 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.617 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.headForSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.617 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.data.rest.webmvc.RepositorySearchesResource org.springframework.data.rest.webmvc.RepositorySearchController.listSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.618 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search/{search}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.util.MultiValueMap<java.lang.String, java.lang.Object>,java.lang.String,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders)
2017-06-17 22:22:02.619 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search/{search}],methods=[GET],produces=[application/x-spring-data-compact+json]}" onto public org.springframework.hateoas.ResourceSupport org.springframework.data.rest.webmvc.RepositorySearchController.executeSearchCompact(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.http.HttpHeaders,org.springframework.util.MultiValueMap<java.lang.String, java.lang.Object>,java.lang.String,java.lang.String,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler)
2017-06-17 22:22:02.620 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search/{search}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearch(org.springframework.data.rest.webmvc.RootResourceInformation,java.lang.String)
2017-06-17 22:22:02.620 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/search/{search}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.data.rest.webmvc.RepositorySearchController.headForSearch(org.springframework.data.rest.webmvc.RootResourceInformation,java.lang.String)
2017-06-17 22:22:02.623 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.624 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.headCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.625 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.625 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}],methods=[GET],produces=[application/x-spring-data-compact+json || text/uri-list]}" onto public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResourceCompact(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.626 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}],methods=[POST],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.626 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForItemResource(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.626 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.headForItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.627 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.Resource<?>> org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.628 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[PUT],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.628 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[PATCH],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.patchItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException,org.springframework.data.rest.webmvc.ResourceNotFoundException
2017-06-17 22:22:02.629 INFO 1062 --- [ restartedMain] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped "{[/{repository}/{id}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.deleteItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.support.ETag) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
2017-06-17 22:22:02.633 INFO 1062 --- [ restartedMain] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped "{[/profile],methods=[GET]}" onto org.springframework.http.HttpEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.ProfileController.listAllFormsOfMetadata()
2017-06-17 22:22:02.634 INFO 1062 --- [ restartedMain] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped "{[/profile],methods=[OPTIONS]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.ProfileController.profileOptions()
2017-06-17 22:22:02.635 INFO 1062 --- [ restartedMain] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped "{[/profile/{repository}],methods=[OPTIONS],produces=[application/alps+json]}" onto org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.alps.AlpsController.alpsOptions()
2017-06-17 22:22:02.635 INFO 1062 --- [ restartedMain] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped "{[/profile/{repository}],methods=[GET],produces=[application/alps+json || */*]}" onto org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.RootResourceInformation> org.springframework.data.rest.webmvc.alps.AlpsController.descriptor(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.636 INFO 1062 --- [ restartedMain] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped "{[/profile/{repository}],methods=[GET],produces=[application/schema+json]}" onto public org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.json.JsonSchema> org.springframework.data.rest.webmvc.RepositorySchemaController.schema(org.springframework.data.rest.webmvc.RootResourceInformation)
2017-06-17 22:22:02.779 INFO 1062 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-06-17 22:22:02.895 INFO 1062 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-06-17 22:22:02.992 INFO 1062 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-17 22:22:03.002 INFO 1062 --- [ restartedMain] c.r.WorldStats.WorldStatsApplication : Started WorldStatsApplication in 15.161 seconds (JVM running for 16.137)
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of com.ronone.WorldStats.models.BaseCountries out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.ronone.WorldStats.models.BaseCountries out of START_ARRAY token
at [Source: java.io.PushbackInputStream#775df1ae; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:244)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:229)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:96)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:655)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
at com.ronone.WorldStats.WorldStatsApplication.main(WorldStatsApplication.java:25)
... 5 more
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.ronone.WorldStats.models.BaseCountries out of START_ARRAY token
at [Source: java.io.PushbackInputStream#775df1ae; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1371)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:174)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:150)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:241)
... 11 more
2017-06-17 22:23:23.932 INFO 1062 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-06-17 22:23:23.933 INFO 1062 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-06-17 22:23:23.990 INFO 1062 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 56 ms
Your json to pojo mapping is incorrect. It should be mapped to an array of BaseCountries rather being mapped to class alone.
You can try this BaseCountries[] countries = restTemplate.getForObject(uri, BaseCountries[].class, "London");
Hope this helps!

Categories