Skip to content

Commit

Permalink
feat: Add findByTitle, findByFirstName, and findByLink methods to Pos…
Browse files Browse the repository at this point in the history
…tRepository
  • Loading branch information
baserrato committed Aug 28, 2024
1 parent 2be3407 commit 01c17aa
Show file tree
Hide file tree
Showing 6 changed files with 146 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.liatrio.dojo.devopsknowledgeshareapi;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Slf4j
public class InfoController {

@GetMapping("/info")
public String getInfo() {
log.info("Received a GET request for /info");
return "Welcome to the API version 1.0";
}
}
10 changes: 10 additions & 0 deletions src/main/java/com/liatrio/dojo/devopsknowledgeshareapi/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ public class Post {
private @NonNull String datePosted;
private @NonNull String imageUrl;
private @NonNull Date dateAsDate;
private String dateUpdated;

public void setDateUpdated(Date dateAsDate) {
DateFormat dateFormat = new SimpleDateFormat(dateFormat());
this.dateUpdated = dateFormat.format(dateAsDate);
}

public String getDateUpdated() {
return dateUpdated;
}

public Post() {
this.dateAsDate = Calendar.getInstance().getTime();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.Collectors;

import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Slf4j
public class PostController {
private PostRepository repository;

private String deploymentType = System.getenv("DEPLOYMENT_TYPE") != null ? System.getenv("DEPLOYMENT_TYPE") : "blue";
String deploymentType = System.getenv("DEPLOYMENT_TYPE") != null ? System.getenv("DEPLOYMENT_TYPE") : "blue";

public PostController(PostRepository repository) {
this.repository = repository;
Expand All @@ -25,6 +30,24 @@ public Collection<Post> posts() {
return repository.findAll().stream().collect(Collectors.toList());
}

@GetMapping("/posts/title/{title}")
public List<Post> getPostsByTitle(@PathVariable("title") String title) {
log.info("{}: received a GET request for posts with title {}", deploymentType, title);

Check failure

Code scanning / CodeQL

Log Injection High

This log entry depends on a
user-provided value
.
return repository.findByTitle(title);
}

@GetMapping("/posts/firstname/{firstName}")
public List<Post> getPostsByFirstName(@PathVariable("firstName") String firstName) {
log.info("{}: received a GET request for posts with first name {}", deploymentType, firstName);

Check failure

Code scanning / CodeQL

Log Injection High

This log entry depends on a
user-provided value
.
return repository.findByFirstName(firstName);
}

@GetMapping("/posts/link/{link}")
public List<Post> getPostsByLink(@PathVariable("link") String link) {
log.info("{}: received a GET request for posts with link {}", deploymentType, link);

Check failure

Code scanning / CodeQL

Log Injection High

This log entry depends on a
user-provided value
.
return repository.findByLink(link);
}

@PostMapping("/posts")
public Post post(@RequestBody Post post, HttpServletResponse resp) {
log.info("{}: recieved a POST request", deploymentType);
Expand All @@ -36,4 +59,34 @@ public void deletePost(@PathVariable("id") String id) {
log.info("{}: recieved a DELETE request", deploymentType);
repository.deleteById(Long.parseLong(id));
}

@PutMapping("/posts/{id}")
public Post updatePost(@PathVariable("id") Long id, @RequestBody Post updatedPost) {
log.info("{}: received a PUT request", deploymentType);
return repository.findById(id).map(post -> {
post.setFirstName(updatedPost.getFirstName());
post.setTitle(updatedPost.getTitle());
try {
post.setLink(updatedPost.getLink());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Convert String to Date
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Adjust the pattern as needed
Date datePosted = formatter.parse(updatedPost.getDatePosted());
post.setDatePosted(datePosted);
} catch (ParseException e) {
log.error("Date parsing error: ", e);
// Handle the error appropriately, e.g., throw an exception or set a default date
}
post.setImageUrl(updatedPost.getImageUrl());
post.setDateAsDate(updatedPost.getDateAsDate());
return repository.save(post);
}).orElseGet(() -> {
updatedPost.setId(id);
return repository.save(updatedPost);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;

import java.util.List;

@RepositoryRestResource
@Repository
interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByTitle(String title);
List<Post> findByFirstName(String firstName);
List<Post> findByLink(String link);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.liatrio.dojo.devopsknowledgeshareapi;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class InfoControllerTest {

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Test
void testInfoEndpoint() {
String url = "http://localhost:" + port + "/info";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("Welcome to the API version 1.0");
assertThat(response.getBody()).doesNotContain("error");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.junit.jupiter.api.Assertions.assertNotEquals;

import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -106,4 +111,26 @@ public void getImageUrlTest() throws Exception {
String test = hc.getImageUrl();
assertEquals(imageUrl, test);
}
}

@Test
public void setDateUpdatedTest() throws Exception {
Post hc = new Post();
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2022-01-01");
hc.setDateUpdated(date);
String test = hc.getDateUpdated();
DateFormat dateFormat = new SimpleDateFormat(hc.dateFormat());
String expected = dateFormat.format(date);
assertEquals(expected, test);
}

@Test
public void getDateUpdatedTest() throws Exception {
Post hc = new Post();
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2022-01-01");
hc.setDateUpdated(date);
String test = hc.getDateUpdated();
DateFormat dateFormat = new SimpleDateFormat(hc.dateFormat());
String expected = dateFormat.format(date);
assertEquals(expected, test);
}
}

0 comments on commit 01c17aa

Please sign in to comment.