Skip to content
Snippets Groups Projects
Commit fa97e03c authored by Beth Davies's avatar Beth Davies
Browse files

Merge branch 'release/Sprint-3' into...

Merge branch 'release/Sprint-3' into 142-as-a-user-i-want-to-be-able-to-add-comments-to-the-post-in-my-feed-so-that-i-can-have-my-2
parents 6e8ae26e 4a2b305e
No related branches found
No related tags found
No related merge requests found
Showing
with 652 additions and 160 deletions
package polish_community_group_11.polish_community.feed.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import polish_community_group_11.polish_community.feed.repository.FeedRepository;
import polish_community_group_11.polish_community.feed.services.FeedService;
import java.util.List;
@RestController
@RequestMapping("/api/feed")
public class FeedApisController {
private final FeedRepository feedRepository;
private final FeedService feedService;
public FeedApisController(FeedRepository feedRepository, FeedService feedService) {
this.feedService = feedService;
this.feedRepository = feedRepository;
}
// getting all posts
@GetMapping
public List<FeedImpl> getAllPosts() {
return feedRepository.getAllPosts();
}
//getting them by id
@GetMapping("/{postId}")
public ResponseEntity<FeedImpl> getPostById(@PathVariable int postId) {
try {
FeedImpl post = feedRepository.getPostById(postId);
return ResponseEntity.ok(post);
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
// creating a new post
@PostMapping("/add")
public ResponseEntity<?> addNewPost(@RequestBody FeedImpl feed) {
try {
feedService.addNewFeedPost(feed);
return ResponseEntity.ok().body("Post created successfully");
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating post: " + e.getMessage());
}
}
// updating the post
@PutMapping("/{postId}")
public ResponseEntity<Void> updatePost(@PathVariable int postId, @RequestBody FeedImpl feed) {
try {
feedRepository.updatePost(postId, feed);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
// deleting a post
@DeleteMapping("/{postId}")
public ResponseEntity<Void> deletePost(@PathVariable int postId) {
try {
feedRepository.deletePost(postId);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
// liking a post
@PostMapping("/{postId}/like")
public ResponseEntity<Void> likePost(@PathVariable int postId, @RequestParam int userId) {
try {
feedRepository.likePost(postId, userId);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// removing a like from post
@DeleteMapping("/{postId}/like")
public ResponseEntity<Void> unlikePost(@PathVariable int postId, @RequestParam int userId) {
try {
feedRepository.unlikePost(postId, userId);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
// getting list of likes from a post
@GetMapping("/{postId}/hasLiked")
public ResponseEntity<Boolean> hasUserLikedPost(@PathVariable int postId, @RequestParam int userId) {
try {
boolean hasLiked = feedRepository.hasUserLikedPost(postId, userId);
return ResponseEntity.ok(hasLiked);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
}
\ No newline at end of file
......@@ -11,24 +11,19 @@ import polish_community_group_11.polish_community.feed.services.FeedRepositoryIm
public class FeedController {
private FeedRepositoryImpl feedRepository;
private CommentService commentService;
@Autowired
public FeedController(FeedRepositoryImpl feedRepository, CommentService commentService){
this.feedRepository = feedRepository;
this.commentService = commentService;
}
// public FeedController(FeedRepositoryImpl feedRepository){
// this.feedRepository = feedRepository;
// }
@GetMapping("/feed")
public ModelAndView getFeed(){
public ModelAndView getFeedPage() {
ModelAndView modelAndView = new ModelAndView("feed/feed");
modelAndView.addObject("posts" , feedRepository.getAllPosts());
// Fetch comments for each post and add to model
modelAndView.addObject("commentService", commentService);
return modelAndView;
}
}
package polish_community_group_11.polish_community.feed.models;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
public interface Feed {
public String getPostImageUrl();
String getPostImageUrl();
void setPostImageUrl(String postImageUrl);
public void setPostImageUrl(String postImageUrl);
String getPostTitle();
void setPostTitle(String postTitle);
public String getPost_title();
String getPostDescription();
void setPostDescription(String postDescription);
public void setPost_title(String post_title);
LocalDate getPostTime();
void setPostTime(LocalDate postTime);
public String getPost_description();
int getUserId();
void setUserId(int userId);
public void setPost_description(String post_description);
String getAuthorName();
void setAuthorName(String authorName);
public String getPost_author();
String getAuthorOrganization();
void setAuthorOrganization(String organization);
public void setPost_author(String post_author);
List<String> getTags();
void setTags(List<String> tags);
public LocalDate getPost_time();
public void setPost_time(LocalDate post_time);
int getLikesCount();
void setLikesCount(int likesCount);
}
\ No newline at end of file
......@@ -2,21 +2,23 @@ package polish_community_group_11.polish_community.feed.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FeedImpl implements Feed {
private int postId;
private String postImageUrl;
private String post_title;
private String post_description;
private String post_author;
private LocalDate post_time;
private int user_id;
private String postTitle;
private String postDescription;
private LocalDate postTime;
private int userId;
private String authorName;
private String authorOrganization;
private List<String> tags;
private int likesCount;
}
\ No newline at end of file
package polish_community_group_11.polish_community.feed.repository;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import java.util.List;
public interface FeedRepository {
List<FeedImpl> getAllPosts();
FeedImpl getPostById(int postId);
void addNewFeedPost(FeedImpl feed);
void updatePost(int postId, FeedImpl feed);
void deletePost(int postId);
void likePost(int postId, int userId);
void unlikePost(int postId, int userId);
boolean hasUserLikedPost(int postId, int userId);
}
package polish_community_group_11.polish_community.feed.repository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import java.util.List;
@Repository
public class FeedRepositoryImpl implements FeedRepository {
private final JdbcTemplate jdbcTemplate;
private final RowMapper<FeedImpl> feedMapper;
public FeedRepositoryImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.feedMapper = (rs, rowNum) -> {
FeedImpl feed = new FeedImpl();
feed.setPostImageUrl(rs.getString("post_image_url"));
feed.setPostTitle(rs.getString("post_title"));
feed.setPostDescription(rs.getString("post_description"));
feed.setPostTime(rs.getDate("post_time").toLocalDate());
feed.setUserId(rs.getInt("user_id"));
feed.setAuthorName(rs.getString("fullname"));
feed.setAuthorOrganization(rs.getString("organization"));
feed.setTags(getTagsForPost(rs.getInt("post_id")));
feed.setLikesCount(getLikesCount(rs.getInt("post_id")));
return feed;
};
}
// getting all posts
@Override
public List<FeedImpl> getAllPosts() {
String sql = "SELECT f.*, u.fullname, u.organization " +
"FROM feed f " +
"LEFT JOIN users u ON f.user_id = u.id " +
"ORDER BY f.post_time DESC";
return jdbcTemplate.query(sql, feedMapper);
}
// getting a post by id
@Override
public FeedImpl getPostById(int postId) {
String sql = "SELECT f.*, u.fullname, u.organization " +
"FROM feed f " +
"LEFT JOIN users u ON f.user_id = u.id " +
"WHERE f.post_id = ?";
return jdbcTemplate.queryForObject(sql, feedMapper, postId);
}
// adding a new post
@Override
public void addNewFeedPost(FeedImpl feed) {
String sql = "INSERT INTO feed (post_image_url, post_title, post_description, post_time, user_id) " +
"VALUES (?, ?, ?, ?, ?)";
jdbcTemplate.update(sql,
feed.getPostImageUrl() != null ? feed.getPostImageUrl() : "",
feed.getPostTitle(),
feed.getPostDescription(),
java.sql.Date.valueOf(feed.getPostTime()),
feed.getUserId()
);
int postId = getGeneratedPostId();
List<String> tags = feed.getTags();
if (tags != null && !tags.isEmpty()) {
insertTagsForPost(postId, tags);
}
}
// update a post that is editing
@Override
public void updatePost(int postId, FeedImpl feed) {
String sql = "UPDATE feed SET post_image_url = ?, post_title = ?, post_description = ?, " +
"post_author = ?, post_time = ?, author_title = ? WHERE post_id = ?";
jdbcTemplate.update(sql,
feed.getPostImageUrl(),
feed.getPostTitle(),
feed.getPostDescription(),
java.sql.Date.valueOf(feed.getPostTime()),
postId
);
// update the tags
jdbcTemplate.update("DELETE FROM feed_tags WHERE post_id = ?", postId);
insertTagsForPost(postId, feed.getTags());
}
// deleting a post
@Override
public void deletePost(int postId) {
// delete associated likes, tags then the post
jdbcTemplate.update("DELETE FROM post_likes WHERE post_id = ?", postId);
jdbcTemplate.update("DELETE FROM feed_tags WHERE post_id = ?", postId);
jdbcTemplate.update("DELETE FROM feed WHERE post_id = ?", postId);
}
// liking a post
@Override
public void likePost(int postId, int userId) {
String sql = "INSERT INTO post_likes (post_id, user_id) VALUES (?, ?)";
jdbcTemplate.update(sql, postId, userId);
}
// removing like
@Override
public void unlikePost(int postId, int userId) {
String sql = "DELETE FROM post_likes WHERE post_id = ? AND user_id = ?";
jdbcTemplate.update(sql, postId, userId);
}
// checking if user had liked or not
@Override
public boolean hasUserLikedPost(int postId, int userId) {
String sql = "SELECT COUNT(*) FROM post_likes WHERE post_id = ? AND user_id = ?";
int count = jdbcTemplate.queryForObject(sql, Integer.class, postId, userId);
return count > 0;
}
// getting number of likes on post
private int getLikesCount(int postId) {
String sql = "SELECT COUNT(*) FROM post_likes WHERE post_id = ?";
return jdbcTemplate.queryForObject(sql, Integer.class, postId);
}
// getting tags associated with post
private List<String> getTagsForPost(int postId) {
String sql = "SELECT t.tag_name FROM tags t " +
"INNER JOIN feed_tags ft ON t.tag_id = ft.tag_id " +
"WHERE ft.post_id = ?";
return jdbcTemplate.query(sql, (rs, rowNum) -> rs.getString("tag_name"), postId);
}
// getting id of the recently created post
private int getGeneratedPostId() {
return jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Integer.class);
}
private void insertTagsForPost(int postId, List<String> tags) {
for (String tag : tags) {
// check for empty tags
if (tag == null || tag.trim().isEmpty()) {
continue;
}
String cleanTag = tag.trim().toLowerCase();
int tagId = insertTagAndGetId(cleanTag);
// link to post
try {
jdbcTemplate.update(
"INSERT INTO feed_tags (post_id, tag_id) VALUES (?, ?)",
postId, tagId
);
} catch (Exception e) {
// handle duplicate tag associations silently
if (!e.getMessage().contains("duplicate")) {
throw e;
}
}
}
}
private int insertTagAndGetId(String tag) {
try {
String checkSql = "SELECT tag_id FROM tags WHERE tag_name = ?";
Integer tagId = jdbcTemplate.queryForObject(checkSql, new Object[]{tag}, Integer.class);
return tagId != null ? tagId : createNewTag(tag);
} catch (Exception e) {
return createNewTag(tag);
}
}
private int createNewTag(String tag) {
jdbcTemplate.update("INSERT INTO tags (tag_name) VALUES (?)", tag);
return jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Integer.class);
}
}
\ No newline at end of file
package polish_community_group_11.polish_community.feed.services;
import org.springframework.stereotype.Service;
import polish_community_group_11.polish_community.feed.models.Feed;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Service
public class FeedRepositoryImpl implements FeedRepository {
private final List<Feed> feeds;
public FeedRepositoryImpl() {
feeds = Arrays.asList(
new FeedImpl("assets/post-image.jpg",
"Pentagon unlikely to use all of the billions Congress authorized it to spend on Ukraine weapons before Biden leaves office, officials say",
"The Pentagon is unlikely to use all of the billions of dollars authorized by Congress to arm Ukraine before President Joe Biden leaves office, according to two US officials and three defense officials",
"John Doe",
LocalDate.now(),
1),
new FeedImpl("assets/post-image2.webp",
"Business owners, churches take legal action against Harvey mayor, alleging improper fees",
"Some business owners and churches in south suburban Harvey are taking legal action against the city, alleging that they're being unfairly targeted with improper fees to help raise revenue.",
"Jane Smith",
LocalDate.now(),
2),
new FeedImpl("Customize Toolbar...",
"Post Title 3 ",
"A quick look at some interesting insights and updates.",
"Mark Lee",
LocalDate.now(),
3)
);
}
@Override
public List<Feed> getAllPosts() {
return feeds;
}
@Override
public Feed getFeedByTitle(String postTitle) {
return feeds.stream().filter(feed -> feed.getPost_title().equalsIgnoreCase(postTitle)).findFirst().orElse(null);
}
// public List<Feed> getAllPosts() {
// return Arrays.asList(
// new FeedImpl("assets/post-image.jpg",
// "Pentagon unlikely to use all of the billions Congress authorized it to spend on Ukraine weapons before Biden leaves office, officials say",
// "The Pentagon is unlikely to use all of the billions of dollars authorized by Congress to arm Ukraine before President Joe Biden leaves office, according to two US officials and three defense officials",
// "John Doe",
// LocalDate.now(),
// 1),
// new FeedImpl("assets/post-image2.webp",
// "Business owners, churches take legal action against Harvey mayor, alleging improper fees",
// "Some business owners and churches in south suburban Harvey are taking legal action against the city, alleging that they're being unfairly targeted with improper fees to help raise revenue.",
// "Jane Smith",
// LocalDate.now(),
// 2),
// new FeedImpl("Customize Toolbar...",
// "Post Title 3 ",
// "A quick look at some interesting insights and updates.",
// "Mark Lee",
// LocalDate.now(),
// 3)
// );
// }
}
package polish_community_group_11.polish_community.feed.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import polish_community_group_11.polish_community.feed.models.Feed;
import polish_community_group_11.polish_community.feed.models.FeedImpl;
import polish_community_group_11.polish_community.feed.repository.FeedRepository;
import polish_community_group_11.polish_community.register.models.User;
import polish_community_group_11.polish_community.register.services.UserService;
import java.time.LocalDate;
import java.util.List;
@Service
public class FeedService {
private final FeedRepository feedRepository;
private final UserService userService;
private static final Logger log = LoggerFactory.getLogger(FeedService.class);
@Autowired
private FeedRepository feedRepository;
public FeedService(FeedRepository feedRepository, UserService userService) {
this.feedRepository = feedRepository;
this.userService = userService;
}
public void addNewFeedPost(FeedImpl feed) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
log.error("No authentication found");
throw new SecurityException("No authentication found");
}
public List<Feed> getAllPosts() {
return feedRepository.getAllPosts();
String userEmail = authentication.getName();
log.info("Adding new post for user: {}", userEmail);
User user = userService.findByEmail(userEmail);
if (user == null) {
log.error("No user found for email: {}", userEmail);
throw new SecurityException("No authenticated user found");
}
public Feed getFeedByTitle(String postTitle) {
return feedRepository.getFeedByTitle(postTitle);
feed.setUserId(user.getId());
feed.setPostTime(LocalDate.now());
try {
feedRepository.addNewFeedPost(feed);
} catch (Exception e) {
log.error("Error adding new post: ", e);
throw e;
}
}
// @Autowired
// private polish_community_group_11.polish_community.feed.services.FeedRepository feedRepository;
//
// public List<Feed> getAllPosts() {
// return feedRepository.getAllPosts();
// }
//
// public Feed getFeedByTitle(String postTitle) {
// return feedRepository.getFeedByTitle(postTitle);
// }
}
\ No newline at end of file
package polish_community_group_11.polish_community.information.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.services.InformationService;
import java.sql.SQLException;
import java.util.List;
......@@ -22,4 +21,9 @@ public class InformationApiController {
public List<DBInfo> getAllInformation(@PathVariable int category_id){
return infoService.getAllItemsByCategoryId(category_id);
}
@DeleteMapping("api/info/delete")
public int deleteInformation(@RequestParam List<Integer> deleteIdList) throws SQLException {
return infoService.deleteInfoByList(deleteIdList);
}
}
......@@ -4,25 +4,20 @@ import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import polish_community_group_11.polish_community.information.common.Utility;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.DBInfoImpl;
import polish_community_group_11.polish_community.information.models.ViewModel.DBInfoForm;
import polish_community_group_11.polish_community.information.services.InformationService;
import java.lang.invoke.MethodHandles;
import java.sql.SQLException;
import java.util.List;
@Controller
public class InformationController {
......@@ -56,25 +51,54 @@ public class InformationController {
@GetMapping("info/add/{categoryId}")
public ModelAndView addInformation(@PathVariable int categoryId){
ModelAndView modelAndView=new ModelAndView("information/AddInformation");
DBInfo newInfo = new DBInfoImpl();
ModelAndView modelAndView=new ModelAndView("information/addInformation");
DBInfoForm newInfo = new DBInfoForm();
newInfo.setCategoryId(categoryId);
modelAndView.addObject("newInfo",newInfo);
modelAndView.addObject("formAction", "/info/add");
return modelAndView;
}
@PostMapping("/info/add")
public ModelAndView addInformation(@Valid @ModelAttribute("newInfo") DBInfoImpl newInfo,
BindingResult bindingResult, Model model)
{
ModelAndView modelAndView = new ModelAndView("information/AddInformation");
public ModelAndView addInformation(@Valid @ModelAttribute("newInfo") DBInfoForm newInfo,
BindingResult bindingResult, Model model) throws SQLException {
ModelAndView modelAndView = new ModelAndView("information/addInformation");
if(bindingResult.hasErrors()){
modelAndView.addObject(model.asMap());
modelAndView.addObject("formAction", "/info/add");
}
else{
DBInfo addInfo = infoService.processDbInfo(newInfo);
DBInfo addInfo = infoService.processDbInfoForm(newInfo);
infoService.addNewInfo(addInfo);
modelAndView = new ModelAndView("redirect:../categories");
modelAndView = new ModelAndView(
String.format("redirect:../categories/%d", addInfo.getCategoryId()));
}
return modelAndView;
}
@GetMapping("/info/edit/{info_id}")
public ModelAndView editInformation(@PathVariable int info_id) throws SQLException {
ModelAndView modelAndView = new ModelAndView("information/addInformation");
DBInfo selectedInfo = infoService.getInfomrationItemById(info_id);
DBInfoForm newInfo = infoService.processDbInfoFormForEdit(selectedInfo);
modelAndView.addObject("newInfo", newInfo);
modelAndView.addObject("formAction", "/info/edit");
return modelAndView;
}
@PostMapping("/info/edit")
public ModelAndView editInformation(@Valid @ModelAttribute("newInfo") DBInfoForm newInfo,
BindingResult bindingResult, Model model) throws SQLException {
ModelAndView modelAndView = new ModelAndView("information/addInformation");
if(bindingResult.hasErrors()){
modelAndView.addObject(model.asMap());
modelAndView.addObject("formAction", "/info/edit");
}
else{
DBInfo updatedInfo = infoService.processDbInfoForm(newInfo);
infoService.editInfo(updatedInfo);
modelAndView = new ModelAndView(
String.format("redirect:../categories/%d", updatedInfo.getCategoryId()));
}
return modelAndView;
}
......
......@@ -3,14 +3,17 @@ package polish_community_group_11.polish_community.information.dao;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.DBInfoImpl;
import java.sql.SQLException;
import java.util.List;
/**
* This Information Repository interface acts as a layer to hide the main implementations of the
information repository methods and make only the methods available.
It defines methods to retrieve specific data
items and lists of database information from the data source.*/
items and lists of database information from the data source.
**/
public interface InformationRepository {
public DBInfo getInfomrationById(int id)
......@@ -18,5 +21,7 @@ public interface InformationRepository {
public List<DBInfo> getDbInfoListByCategory(int category_id);
List<DBInfo> findDbInfo(String userInput);
void addNewInfo(DBInfo newInfo);
void addNewInfo(DBInfo newInfo) throws SQLException;
int deleteInfoList(List<Integer> deleteIdList) throws SQLException;
int editInfo(DBInfo updatedInfo) throws SQLException;
}
......@@ -4,16 +4,16 @@ import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.DBInfoImpl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
/**
Implementation of the InformationRepository interface.
......@@ -97,21 +97,59 @@ public class InformationRepositoryImpl implements InformationRepository {
return jdbc.query(sql, ps -> ps.setString(1, "%" + userInput.toLowerCase() + "%"), infoItemMapper);
}
public void addNewInfo(DBInfo newInfo){
// Inserts new database of information record to the information table
public void addNewInfo(DBInfo newInfo) throws SQLException {
String dbInsertSql =
"insert into information " +
"(category_id, info_title, created_by, created_date, " +
"updated_date, tag_id, short_info, info_article)" +
" values (?,?,?,?,?,?,?,?)";
try {
jdbc.update(dbInsertSql,
newInfo.getCategoryId(),
newInfo.getInfoTitle(),
newInfo.getCreatedBy(),
newInfo.getCreatedDate(),
newInfo.getUpdatedDate(),
newInfo.getTagId(),
"Nitish Marnuri", //Mocking the user for now
LocalDate.now(),
LocalDate.now(),
1, // Mocking the tag id for now
newInfo.getShortDescription(),
newInfo.getInfoDescription()
);
} catch (DataAccessException e) {
throw new SQLException("Failed to insert new information record", e);
}
}
// Deletes a list of records from information table with list of Information Ids
public int deleteInfoList(List<Integer> deleteIdList) throws SQLException {
// Prepare query for deletion
String deleteSql = "delete from information where info_id in (" +
String.join(",", deleteIdList.stream().map(info_id -> "?").toArray(String[]::new)) + ")";
Object[] deleteParams = deleteIdList.toArray();
try {
return jdbc.update(deleteSql, deleteParams);
} catch (DataAccessException e) {
throw new SQLException("Failed to delete information records", e);
}
}
// Updates selected record with new updated information
public int editInfo(DBInfo updatedInfo) throws SQLException {
String updateSql = "update information " +
"set info_title=?, short_info=?, info_article=? " +
"where info_id=?";
try {
return jdbc.update(updateSql,
updatedInfo.getInfoTitle(),
updatedInfo.getShortDescription(),
updatedInfo.getInfoDescription(),
updatedInfo.getInformationId()
);
} catch (DataAccessException e) {
throw new SQLException("Failed to update information record", e);
}
}
}
......@@ -20,7 +20,6 @@ import java.time.LocalDate;
public class DBInfoImpl extends InformationImpl implements DBInfo {
private int categoryId; // Id to map the information with Category table as a foreign key.
private int tagId; // Id to map the information with tag table as a foreign key.
@NotEmpty(message = "Please enter a short description")
private String shortDescription;
public DBInfoImpl(int categoryId, int tagId, int informationId, String infoTitle,
......
......@@ -17,11 +17,9 @@ import java.time.LocalDate;
@NoArgsConstructor
public abstract class InformationImpl implements Information {
private int informationId;
@NotEmpty(message = "Please enter a title for the new information heading")
private String infoTitle;
private String createdBy;
private LocalDate createdDate;
private LocalDate updatedDate;
@NotEmpty(message = "Please add the detailed content information for the new information.")
private String infoDescription;
}
package polish_community_group_11.polish_community.information.models.ViewModel;
import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
/*
This is a view model class DB Info form to take form data and perform validations.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DBInfoForm {
private int informationId;
private int categoryId;
private int tagId;
// Add validations for not empty fields
@NotEmpty(message = "Please enter a title for the new information heading")
private String infoTitle;
@NotEmpty(message = "Please enter a short description")
private String shortDescription;
@NotEmpty(message = "Please add the detailed content information for the new information.")
private String infoDescription;
private String createdBy;
private LocalDate createdDate;
private LocalDate updatedDate;
}
......@@ -4,6 +4,7 @@ import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.SearchResult;
import polish_community_group_11.polish_community.information.models.ViewModel.DBInfoForm;
import java.sql.SQLException;
import java.util.List;
......@@ -21,6 +22,9 @@ public interface InformationService {
List<DBInfo> getAllItemsByCategoryId(int category_id);
List<SearchResult> searchInfo(String userInput);
DBInfo processDbInfo(DBInfo dbinfo);
void addNewInfo(DBInfo newInfo);
DBInfo processDbInfoForm(DBInfoForm dbInfoForm);
void addNewInfo(DBInfo newInfo) throws SQLException;
int deleteInfoByList(List<Integer> deleteIdList) throws SQLException;
int editInfo(DBInfo updatedInfo) throws SQLException;
DBInfoForm processDbInfoFormForEdit(DBInfo selectedInfo);
}
......@@ -5,7 +5,9 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.stereotype.Service;
import polish_community_group_11.polish_community.information.dao.InformationRepository;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.DBInfoImpl;
import polish_community_group_11.polish_community.information.models.SearchResult;
import polish_community_group_11.polish_community.information.models.ViewModel.DBInfoForm;
import java.sql.SQLException;
import java.time.LocalDate;
......@@ -46,15 +48,47 @@ public class InformationServiceImpl implements InformationService{
.toList();
}
public void addNewInfo(DBInfo newInfo){
public void addNewInfo(DBInfo newInfo) throws SQLException {
informationRepository.addNewInfo(newInfo);
}
public DBInfo processDbInfo(DBInfo dbinfo) {
dbinfo.setTagId(1);
dbinfo.setCreatedBy("Nitish");
dbinfo.setCreatedDate(LocalDate.now());
dbinfo.setUpdatedDate(LocalDate.now());
return dbinfo;
public int deleteInfoByList(List<Integer> deleteIdList) throws SQLException {
return informationRepository.deleteInfoList(deleteIdList);
}
public int editInfo(DBInfo updatedInfo) throws SQLException {
return informationRepository.editInfo(updatedInfo);
}
public DBInfo processDbInfoForm(DBInfoForm dbInfoForm) {
if (dbInfoForm == null) {
throw new IllegalArgumentException("dbInfoForm cannot be null");
}
DBInfo newInfo = new DBInfoImpl();
newInfo.setCategoryId(dbInfoForm.getCategoryId());
newInfo.setInfoTitle(dbInfoForm.getInfoTitle());
newInfo.setShortDescription(dbInfoForm.getShortDescription());
newInfo.setInfoDescription(dbInfoForm.getInfoDescription());
newInfo.setInformationId(dbInfoForm.getInformationId());
newInfo.setCreatedBy(dbInfoForm.getCreatedBy());
newInfo.setCreatedDate(dbInfoForm.getCreatedDate());
newInfo.setTagId(dbInfoForm.getTagId());
return newInfo;
}
public DBInfoForm processDbInfoFormForEdit(DBInfo selectedInfo) {
if (selectedInfo == null) {
throw new IllegalArgumentException("dbInfoForm cannot be null");
}
DBInfoForm selectedInfoForm = new DBInfoForm();
selectedInfoForm.setCategoryId(selectedInfo.getCategoryId());
selectedInfoForm.setInfoTitle(selectedInfo.getInfoTitle());
selectedInfoForm.setInformationId(selectedInfo.getInformationId());
selectedInfoForm.setShortDescription(selectedInfo.getShortDescription());
selectedInfoForm.setInfoDescription(selectedInfo.getInfoDescription());
selectedInfoForm.setCreatedBy(selectedInfo.getCreatedBy());
selectedInfoForm.setCreatedDate(selectedInfo.getCreatedDate());
selectedInfoForm.setTagId(selectedInfo.getTagId());
return selectedInfoForm;
}
}
package polish_community_group_11.polish_community.news.controllers;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.information.models.DBInfoImpl;
import polish_community_group_11.polish_community.news.models.News;
import polish_community_group_11.polish_community.news.models.NewsImpl;
import polish_community_group_11.polish_community.news.services.NewsService;
import java.sql.SQLException;
......@@ -21,6 +28,22 @@ public class NewsController {
public ModelAndView getNews() throws SQLException {
ModelAndView modelAndView = new ModelAndView("news/newsList");
modelAndView.addObject("newsList",newsService.getAllNews());
modelAndView.addObject("news" , new NewsImpl());
return modelAndView;
}
@PostMapping("/news/add")
public ModelAndView addInformation(@Valid @ModelAttribute("news") NewsImpl news,
BindingResult bindingResult, Model model) throws SQLException {
ModelAndView modelAndView = new ModelAndView("news/addNews");
if(bindingResult.hasErrors()){
modelAndView.addObject(model.asMap());
}
else{
News newsToAdd = news;
newsService.addNews(newsToAdd);
modelAndView = new ModelAndView("redirect:/news");
}
return modelAndView;
}
}
package polish_community_group_11.polish_community.news.dao;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.news.models.News;
import java.sql.SQLException;
......@@ -8,7 +9,11 @@ import java.util.List;
public interface NewsRepository {
public List<News> getAllNews() throws SQLException;
void addNews(News news) throws SQLException;
News getNewsById(int id) throws SQLException;
void updateNews(News news) throws SQLException;
void deleteNews(int id) throws SQLException;
}
......@@ -6,11 +6,13 @@ import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.information.models.DBInfo;
import polish_community_group_11.polish_community.news.models.News;
import polish_community_group_11.polish_community.news.models.NewsImpl;
import java.sql.SQLException;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.util.List;
@Repository // Marks the class as a repository in the Spring context, responsible for data access logic
......@@ -81,6 +83,32 @@ public class NewsRepositoryImpl implements NewsRepository {
}
}
public void addNews(News news) throws SQLException{
String dbInsertSql =
"insert into news " +
"(news_title, news_summary, news_source, " +
"news_link, news_image_url, user_id, news_upload_date)" +
" values (?,?,?,?,?,?,?)";
try {
int x = jdbc.update(dbInsertSql,
news.getNews_title(),
news.getNews_summary(),
news.getNews_source(),
news.getNews_link(),
news.getNews_image_url(),
1,
LocalDate.now()
);
}catch (DataAccessException e) {
throw new SQLException("Failed to insert new information record", e);
}
}
@Override
public News getNewsById(int id) throws SQLException {
String sql = "SELECT * FROM news WHERE news_id = ?";
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment