Source code for Lightrun articles

This commit is contained in:
Graham Cox
2022-05-17 16:07:21 +01:00
parent 06a6b0b3a7
commit 67b8a66173
54 changed files with 1460 additions and 0 deletions

33
lightrun/tasks-service/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>tasks-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tasks-service</name>
<description>Tasks Service for LightRun Article</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-artemis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-jms-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,23 @@
package com.baeldung.tasksservice;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jms.artemis.ArtemisConfigurationCustomizer;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ArtemisConfig implements ArtemisConfigurationCustomizer {
@Value("${spring.artemis.host}")
private String hostname;
@Value("${spring.artemis.port}")
private int port;
@Override
public void customize(org.apache.activemq.artemis.core.config.Configuration configuration) {
try {
configuration.addAcceptorConfiguration("remote", "tcp://" + hostname + ":" + port);
} catch (Exception e) {
throw new RuntimeException("Failed to configure Artemis listener", e);
}
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.tasksservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TasksServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TasksServiceApplication.class, args);
}
}

View File

@@ -0,0 +1,15 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.http;
public record CreateTaskRequest(String title, String createdBy) {
}

View File

@@ -0,0 +1,17 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.http;
import java.util.Optional;
public record PatchTaskRequest(Optional<String> status, Optional<String> assignedTo) {
}

View File

@@ -0,0 +1,22 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.http;
import java.time.Instant;
public record TaskResponse(String id,
String title,
Instant created,
String createdBy,
String assignedTo,
String status) {
}

View File

@@ -0,0 +1,86 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.http;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import com.baeldung.tasksservice.adapters.repository.TaskRecord;
import com.baeldung.tasksservice.service.TasksService;
import com.baeldung.tasksservice.service.UnknownTaskException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
class TasksController {
@Autowired
private TasksService tasksService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public TaskResponse createTask(@RequestBody CreateTaskRequest body) {
var task = tasksService.createTask(body.title(), body.createdBy());
return buildResponse(task);
}
@GetMapping
public List<TaskResponse> searchTasks(@RequestParam("status") Optional<String> status,
@RequestParam("createdBy") Optional<String> createdBy) {
var tasks = tasksService.search(status, createdBy);
return tasks.stream()
.map(this::buildResponse)
.collect(Collectors.toList());
}
@GetMapping("/{id}")
public TaskResponse getTask(@PathVariable("id") String id) {
var task = tasksService.getTaskById(id);
return buildResponse(task);
}
@DeleteMapping("/{id}")
public void deleteTask(@PathVariable("id") String id) {
tasksService.deleteTaskById(id);
}
@PatchMapping("/{id}")
public TaskResponse patchTask(@PathVariable("id") String id,
@RequestBody PatchTaskRequest body) {
var task = tasksService.updateTask(id, body.status(), body.assignedTo());
return buildResponse(task);
}
private TaskResponse buildResponse(final TaskRecord task) {
return new TaskResponse(task.getId(), task.getTitle(), task.getCreated(), task.getCreatedBy(),
task.getAssignedTo(), task.getStatus());
}
@ExceptionHandler(UnknownTaskException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleUnknownTask() {
}
}

View File

@@ -0,0 +1,5 @@
{
"local-tasks": {
"host": "localhost:8082"
}
}

View File

@@ -0,0 +1,35 @@
GET http://{{host}}/createdemoapplication1 HTTP/1.1
###
GET http://{{host}}/unknown HTTP/1.1
###
GET http://{{host}}?status=PENDING
###
GET http://{{host}}?createdBy=baeldung
###
GET http://{{host}}?createdBy=baeldung&status=COMPLETE
###
DELETE http://{{host}}/createdemoapplication1 HTTP/1.1
###
DELETE http://{{host}}/unknown HTTP/1.1
###
POST http://{{host}} HTTP/1.1
Content-Type: application/json
{
"title": "My Task",
"createdBy": "graham"
}
###
PATCH http://{{host}}/createdemoapplication1 HTTP/1.1
Content-Type: application/json
{
"status": "COMPLETE"
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.tasksservice.adapters.jms;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import com.baeldung.tasksservice.service.DeletedUserService;
@Service
public class JmsConsumer {
@Autowired
private DeletedUserService deletedUserService;
@JmsListener(destination = "deleted_user")
public void receive(String user) {
deletedUserService.handleDeletedUser(user);
}
}

View File

@@ -0,0 +1,80 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.repository;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "tasks")
public class TaskRecord {
@Id
@Column(name = "task_id")
private String id;
private String title;
@Column(name = "created_at")
private Instant created;
@Column(name = "created_by")
private String createdBy;
@Column(name = "assigned_to")
private String assignedTo;
private String status;
public TaskRecord(final String id, final String title, final Instant created, final String createdBy,
final String assignedTo, final String status) {
this.id = id;
this.title = title;
this.created = created;
this.createdBy = createdBy;
this.assignedTo = assignedTo;
this.status = status;
}
private TaskRecord() {
// Needed for JPA
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public Instant getCreated() {
return created;
}
public String getCreatedBy() {
return createdBy;
}
public String getAssignedTo() {
return assignedTo;
}
public String getStatus() {
return status;
}
public void setAssignedTo(final String assignedTo) {
this.assignedTo = assignedTo;
}
public void setStatus(final String status) {
this.status = status;
}
}

View File

@@ -0,0 +1,28 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.adapters.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TasksRepository extends JpaRepository<TaskRecord, String> {
List<TaskRecord> findByStatus(String status);
List<TaskRecord> findByCreatedBy(String createdBy);
List<TaskRecord> findByStatusAndCreatedBy(String status, String createdBy);
List<TaskRecord> findByAssignedTo(String assignedTo);
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.tasksservice.service;
import javax.transaction.Transactional;
import com.baeldung.tasksservice.adapters.repository.TaskRecord;
import com.baeldung.tasksservice.adapters.repository.TasksRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DeletedUserService {
@Autowired
private TasksRepository tasksRepository;
@Transactional
public void handleDeletedUser(String user) {
var ownedByUser = tasksRepository.findByCreatedBy(user);
tasksRepository.deleteAll(ownedByUser);
var assignedToUser = tasksRepository.findByAssignedTo(user);
for (TaskRecord record : assignedToUser) {
record.setAssignedTo(null);
record.setStatus("PENDING");
}
}
}

View File

@@ -0,0 +1,72 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.service;
import javax.transaction.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import com.baeldung.tasksservice.adapters.repository.TaskRecord;
import com.baeldung.tasksservice.adapters.repository.TasksRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TasksService {
@Autowired
private TasksRepository tasksRepository;
public TaskRecord getTaskById(String id) {
return tasksRepository.findById(id).orElseThrow(() -> new UnknownTaskException(id));
}
@Transactional
public void deleteTaskById(String id) {
var task = tasksRepository.findById(id).orElseThrow(() -> new UnknownTaskException(id));
tasksRepository.delete(task);
}
public List<TaskRecord> search(Optional<String> createdBy, Optional<String> status) {
if (createdBy.isPresent() && status.isPresent()) {
return tasksRepository.findByStatusAndCreatedBy(status.get(), createdBy.get());
} else if (createdBy.isPresent()) {
return tasksRepository.findByCreatedBy(createdBy.get());
} else if (status.isPresent()) {
return tasksRepository.findByStatus(status.get());
} else {
return tasksRepository.findAll();
}
}
@Transactional
public TaskRecord updateTask(String id, Optional<String> newStatus, Optional<String> newAssignedTo) {
var task = tasksRepository.findById(id).orElseThrow(() -> new UnknownTaskException(id));
newStatus.ifPresent(task::setStatus);
newAssignedTo.ifPresent(task::setAssignedTo);
return task;
}
public TaskRecord createTask(String title, String createdBy) {
var task = new TaskRecord(UUID.randomUUID().toString(),
title,
Instant.now(),
createdBy,
null,
"PENDING");
tasksRepository.save(task);
return task;
}
}

View File

@@ -0,0 +1,24 @@
/****************************************************************************************************************
*
* Copyright (c) 2022 OCLC, Inc. All Rights Reserved.
*
* OCLC proprietary information: the enclosed materials contain
* proprietary information of OCLC, Inc. and shall not be disclosed in whole or in
* any part to any third party or used by any person for any purpose, without written
* consent of OCLC, Inc. Duplication of any portion of these materials shall include this notice.
*
******************************************************************************************************************/
package com.baeldung.tasksservice.service;
public class UnknownTaskException extends RuntimeException {
private final String id;
public UnknownTaskException(final String id) {
this.id = id;
}
public String getId() {
return id;
}
}

View File

@@ -0,0 +1,13 @@
server.port=8082
spring.artemis.mode=EMBEDDED
spring.artemis.host=localhost
spring.artemis.port=61616
spring.artemis.embedded.enabled=true
spring.jms.template.default-destination=my-queue-1
logging.level.org.apache.activemq.audit.base=WARN
logging.level.org.apache.activemq.audit.message=WARN

View File

@@ -0,0 +1,13 @@
CREATE TABLE tasks (
task_id VARCHAR(36) PRIMARY KEY,
title VARCHAR(100) NOT NULL,
created_at DATETIME NOT NULL,
created_by VARCHAR(36) NOT NULL,
assigned_to VARCHAR(36) NULL,
status VARCHAR(20) NOT NULL
);
INSERT INTO tasks(task_id, title, created_at, created_by, assigned_to, status) VALUES
('createdemoapplication1', 'Create demo applications - Tasks', '2022-05-05 12:34:56', 'baeldung', 'coxg', 'IN_PROGRESS'),
('createdemoapplication2', 'Create demo applications - Users', '2022-05-05 12:34:56', 'baeldung', NULL, 'PENDING'),
('createdemoapplication3', 'Create demo applications - API', '2022-05-05 12:34:56', 'baeldung', NULL, 'PENDING');