我想保存一条消息,当我运行curl请求时-
curl -H "Content-Type: application/json" -X POST -d "{\"time\": \"2019-12-27T09:50:02.000+0000\", \"unread\": true, \"message\": \"asd\", \"from\": \"John\"}" localhost:8080/api/save
我在cmd中出错
{“时间戳”:“ 2020-01-05T04:36:33.192 + 0000”,“状态”:500,“错误”:“内部服务器错误”,“消息”:“无可用消息”,“跟踪” “:” java.lang.NullPointerException \ r \ n \ tat org.vaadin.marcus.spring.service.impl.MessageServiceImpl.add(MessageServiceImpl.java:45)\ r \ n \ tat org.vaadin.marcus.spring。 service.impl.MessageServiceImpl $$ FastClassBySpringCGLIB $$ 2d73a7c.invoke()\ r \ n \ tat
我的代码
@Service
@Transactional
public class MessageServiceImpl implements MessageService {
private final MessageRepository repository;
private final PageRequest lastRequest;
private List<Long> chekedMessages = new ArrayList<>();
@Autowired
public MessageServiceImpl(MessageRepository repository) {
this.repository = repository;
lastRequest = new PageRequest(0, 10, Sort.Direction.DESC, "id");
}
@Override
public MessageStatus add(@RequestBody Message message) {
MessageStatus status = null;
try {
repository.save(message);
status.setMessage("Message Saved");
}
catch (Exception e) {
status.setMessage("Message not saved - " + e);
}
return status;
}
@Override
public List<Message> getAllMessages() {
return repository.findAll();
}
@Override
public List<Message> getLast() {
List<Message> result = repository.findAll(lastRequest).getContent();
return result.stream()
.sorted(Comparator.comparingLong(Message::getId))
.collect(Collectors.toList());
}
@Override
public List<Message> getUnreadById(long id) {
return repository.getUnreadById(id);
}
@Override
public String getUnreadMessages() {
List<Message> out = new ArrayList<>();
List<Message> unchekedMessages = repository.findAll();
for (Message message: unchekedMessages) {
if (!chekedMessages.contains(message.getId())) {
chekedMessages.add(message.getId());
out.add(message);
}
}
return new Gson().toJson(out);
}
@Override
public void updateMessage(long id, Message message) {
if (repository.findById(id).isPresent()) {
message.setId(id);
repository.save(message);
}
}
}
其他控制器
public class RestController {
@Autowired
TimerTask timerTask;
@Resource
private final MessageService messageService;
public RestController(MessageService messageService) {
this.messageService = messageService;
}
@PostMapping("/api/save")
public MessageStatus saveMessage(@RequestBody Message chatMessage) {
return messageService.add(chatMessage);
}
@GetMapping("/api/last")
public String getLasts() {
return new Gson().toJson(messageService.getLast());
}
@GetMapping("/api/unread")
public void getUnreadMessages() {
timerTask.run();
}
@GetMapping("/api/unread/{id}")
public List<Message> getUnreadById(@PathVariable ("id") long id) {
return messageService.getUnreadById(id);
}