Web App Project, need assistance - eclipse

Can someone please help, im in my first year of college and im stuck on my web development project. On my blog web page I have a list of posts which i need to arrange chronolgically (new post first). We just started arraylists in my programming class but we have not yet covered how to sort them
Were using the PLAY framework for the project consisting of models, controllers, views and routes. I have a Post Class in the models folder and a Blog Class in controllers shown below
package models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import play.db.jpa.Model;
#Entity
public class Post extends Model
{
public String title;
#Lob
public String content;
#OneToMany
public List<Comment> comments = new ArrayList<Comment>();
public String comment;
public Post(String title, String content)
{
this.title = title;
this.content = content;
}
public String toString()
{
return title;
}
}
package controllers;
import java.util.List;
import models.Message;
import models.Post;
import models.User;
import play.Logger;
import play.mvc.Controller;
public class Blog extends Controller
{
public static void index()
{
User user = Accounts.getLoggedInUser();
render(user);
}
public static void newPost(String title, String content)
{
User user = Accounts.getLoggedInUser();
Post post = new Post (title, content);
post.save();
user.posts.add(post);
user.save();
Logger.info ("title:" + title + " content:" + content);
index();
}
public static void deletePost(Long postid)
{
User user = Accounts.getLoggedInUser();
Post post = Post.findById(postid);
user.posts.remove(post);
user.save();
post.delete();
index();
}
}
and this is the html code that displays the published posts
<section class="ui stacked segment">
<h4 class="ui inverted blue block header">Display Posts</h4>
#{list items:user.posts, as:'post'}
<h5 class="ui inverted green block header"></h5>
<i class="external url icon">${post.title}
#{/list}
</section>
Im totally lost in terms of the java part and have crashed the project numerous times trying to make it work, any help would be greatly appreciated

Related

Request method 'POST' not supported, but the method for creating objects works

I create a CRUD application using SpringBoot. I use PostgreSQL as a database. My application also uses SpringSecurity. The methods of displaying and creating objects work perfectly. But for some reason, updating and deleting the same objects gives an error:
2022-11-01 08:51:14.602 WARN 12149 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
I think the problem is in the html code. I use Thymeleaf.
**My Student Controller:
**
package ru.connor.FirstSecurityApp.controllers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.connor.FirstSecurityApp.model.Student;
import ru.connor.FirstSecurityApp.services.StudentService;
import javax.validation.Valid;
import java.util.Optional;
#Controller
#RequestMapping("/students")
#RequiredArgsConstructor
public class StudentController {
private final StudentService studentService;
#GetMapping()
public String showAllClasses(Model model) {
model.addAttribute("students", studentService.showAllStudent());
return "main/AllClasses";
}
#GetMapping("/{id}")
public String showById(#PathVariable("id") int id, Model model){
Optional<Student> student = Optional.ofNullable(studentService.showStudentById(id));
if (student.isEmpty()){
return "main/students/errorPage";
}else model.addAttribute("student", student);
return "main/students/index";
}
#GetMapping("/add")
public String addStudent(#ModelAttribute("student") Student student) {
return "main/students/new";
}
#PostMapping()
public String create(#ModelAttribute("student") #Valid Student student,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "main/students/new";
studentService.addStudent(student);
return "redirect:/students";
}
#GetMapping("/{id}/edit")
public String edit(Model model, #PathVariable("id") int id) {
model.addAttribute("student", studentService.showStudentById(id));
return "main/students/edit";
}
#PatchMapping("/{id}")
public String update(#ModelAttribute("student") #Valid Student student, BindingResult bindingResult, #PathVariable("id") int id) {
if (bindingResult.hasErrors()){
return "main/students/edit";}
studentService.update(id, student);
return "redirect:/students";
}
#DeleteMapping("/{id}")
public String delete(#PathVariable("id") int id){
Optional<Student> student = Optional.ofNullable(studentService.showStudentById(id));
if (student.isPresent()){
studentService.delete(id);
return "redirect:/students";
}
return "main/students/index";
}
}
Student Service:
package ru.connor.FirstSecurityApp.services;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.connor.FirstSecurityApp.model.Student;
import ru.connor.FirstSecurityApp.repository.StudentsRepository;
import java.util.List;
import java.util.Optional;
#Service
#RequiredArgsConstructor
#SuppressWarnings("unused")
#Transactional(readOnly = true)
public class StudentService {
private final StudentsRepository studentsRepository;
public List<Student> showAllStudent(){
return studentsRepository.findAll();
}
public Student showStudentById(int id){
Optional<Student> foundPerson = studentsRepository.findById(id);
return foundPerson.orElse(null);
}
#Transactional
public void addStudent(Student student){
studentsRepository.save(student);
}
#Transactional
public void update(int id, Student person){
person.setId(id);
studentsRepository.save(person);
}
#Transactional
public boolean delete(int id){
if (studentsRepository.findById(id).isPresent()){
studentsRepository.deleteById(id);
return true;
}
return false;
}
}
**HTML view where the delete form is specified:
**
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Student</title>
</head>
<body>
<h1 th:text="${student.get().getFullStudentName()}"></h1>
<hr>
<form method="post" th:action="#{/students/{id}(id=${student.get().getId()})}">
<input type="submit" value="Delete">
</form>
</body>
</html>
As you have mentioned #PatchMapping for updates then you need the HTTP PATCH method instead of POST. The same goes for delete you have used #DeleteMapping, so you need to use the HTTP DELETE method instead of POST.
Create -> POST
Read -> GET
Update -> PUT/PATCH
Delete -> DELETE
With form submit I don't think PATCH/PUT/DELETE will work so in that case you need to change #PatchMapping/#DeleteMapping to #PostMapping and update the URL so it will be unique for update/delete.
PUT/PATCH/DELETE will work with REST API only.

how avoid to access to other data users. Spring boot + MongoDB

I'm developing a web application with Spring Boot and MongoDB. I'm following the MVC model.
I have a view which shows a list of stored data, but the app ignores the logged user and shows every objects.
https://i.stack.imgur.com/zl7TC.png
Here, the first row was added by another user, but it's showed anyway.
How could I get only the object allowed to the authenticated user?.
The only way I can see is checking the user Id after each query and get only the object of the given user. I think that there should be a better way to do this.
The code is the following:
Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "trackings")
public class Tracking extends Entity implements Serializable {
private static final long serialVersionUID = -1249902722123443448L;
#Indexed(unique = true, direction = IndexDirection.DESCENDING)
private String trackingName;
private String SoftwareName;
#DBRef
private Set<Alarm> alarms;
public String getTrackingName() {
return trackingName;
}
public void setTrackingName(String trackingName) {
this.trackingName = trackingName;
}
public String getSoftwareName() {
return SoftwareName;
}
public void setSoftwareName(String softwareName) {
SoftwareName = softwareName;
}
public Collection<Alarm> getAlarms() {
return alarms;
}
public void setAlarms(Set<Alarm> alarms) {
this.alarms = alarms;
}
}
Repository
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import us.etsii.fvt.domains.Tracking;
#Repository
public interface TrackingRepository extends MongoRepository<Tracking, String>{
Tracking findByTrackingName(String name);
}
Controller
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import us.etsii.fvt.domains.Alarm;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.domains.User;
import us.etsii.fvt.services.TrackingService;
import us.etsii.fvt.services.UserService;
#Controller
public class TrackingController {
#Autowired
private UserService userService;
#Autowired
private TrackingService trackingService;
#RequestMapping(value = { "/tracking" }, method = RequestMethod.GET)
public ModelAndView tracking() {
ModelAndView modelAndView = new ModelAndView();
// AƱadimos el usuario al modelo
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("currentUser", user);
modelAndView.addObject("fullName", user.getFullname());
// AƱadimos la lista de trackings al modelo
List<Tracking> trackings = trackingService.findAll();
modelAndView.addObject("trackings", trackings);
// Devolvemos el modelo
modelAndView.setViewName("tracking");
return modelAndView;
}
...
}
Service
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.repositories.TrackingRepository;
#Service
public class TrackingService {
#Autowired
private TrackingRepository trackingRepository;
public Tracking findTrackingByName(String name) {
return trackingRepository.findByTrackingName(name);
}
public void saveTracking(Tracking tracking) {
trackingRepository.save(tracking);
}
public List<Tracking> findAll() {
return trackingRepository.findAll();
}
public Tracking findById(String id) {
Optional<Tracking> t = trackingRepository.findById(id);
if(!t.isPresent()) {
return null;
}
return t.get();
}
public void remove(String id) {
trackingRepository.deleteById(id);
}
}
There are ambiguous points in your question but assuming you have an User Entity:
You should get the logged in user from Spring Security
You should include a relation of User Entity to Tracking Entity (include User ID information in Tracking records)
Then you should query the mongo db Tracking Entity with the given user id.
You can use standard query by field functionality of Spring Repository.

ManyToMany Relation with Play Framework 1.2.5 JPA

I have 2 Models Article.java and Tags.java. An Article can have many Tags, and a Tags can be belonged to many Article. I am really in trouble to make this relation using JPA and Play Framework 1.2.5. Below are my codes (without setter-getter), and actually it works even throwing exception but I can not get the Tags (getTagname()) of an Article
Article article = Article.findById((long)id);
List<Tags> tags = article.getTags();
for (Tags tags2 : tags) {
System.out.println(tags2.getTagname());
}
Here is my models, Article.java
#Entity
public class Article extends Model{
#Required
public String title;
#Required
public String link;
#Required
#Lob
public String description;
public Date date;
#ManyToMany(cascade=CascadeType.ALL)
public List<Tags> tags = new ArrayList<Tags>();
}
Tags.java
#Entity
public class Tags extends Model {
#Required
public String tagname;
#ManyToMany(mappedBy="tags")
public List<Article> tagsInArticle = new ArrayList<Article>();
}
I am doing something like your code provided above (and use Play 1.2.5), and it seems there is are problems found with the code you provided. The following are my step:
First, I create 2 models Article.java
package models;
import play.data.validation.Required;
import play.db.jpa.Model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "article")
public class Article extends Model {
#Required
public String title;
#ManyToMany(cascade = CascadeType.ALL)
public List<Tag> tags = new ArrayList<Tag>();
}
and Tag.java
package models;
import play.data.validation.Required;
import play.db.jpa.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "tag")
public class Tag extends Model {
#Required
#Column(name = "tag_name")
public String tagName;
#ManyToMany(mappedBy = "tags")
public List<Article> articles = new ArrayList<Article>();
}
Then, on the database, I manually added several record for testing purpose:
article (id;title) > 1;"java example" and 6;"article1"
tag (id;tag_name) > 4;"java" and 5;"playframework"
article_tag (articles_id;tags_id) > 6;4 and 6;5 and 1;4
So then, I testing it with the controller action :
public static void test() {
Article article = Article.findById(6L); // find "article1"
Tag tag_java = Tag.findById(4L); // find java tag
render(article, tag_java);
}
and view below:
#{extends 'main.html' /}
<h3>Article Title : ${article?.title}</h3>
Tags:<br>
<ol>
#{list article?.tags, as:'tag'}
<li>${tag.tagName}</li>
#{/list}
</ol>
All article tagged <b>java</b> :
<ul>
#{list tag_java?.articles, as:'java_article'}
<li>${java_article.title}</li>
#{/list}
</ul>
and lastly, the result is what to be expected :
UPDATE
This #ManyToOne relation is bi-directional. Providing with single data article, we can have all tag on that article, and also all of these tag can have all article data corresponding to each tag. The controller codes are similar, but without passing Tag object directly and the views look like following:
#{extends 'main.html' /}
<h3>Article Title : ${article?.title}</h3>
Tags:<br>
<ol>
#{list article?.tags, as:'tag'}
<li>${tag.tagName}</li>
#{/list}
</ol>
#{list article?.tags, as:'tag'}
Related article [tagged with ${tag.tagName}]:<br>
<ol>
#{list tag?.articles, as:'article'}
<li>${article.title}</li>
#{/list}
</ol>
#{/list}

new to play! Having trouble with: Please annotate your JPA model with #javax.persistence.Entity annotation

new to play and just trying to follow the video on: http://www.playframework.org/
I'm coming so far that i want to create the list of tasks after creating the Task-class. I when i reload i get this error:
"UsupportedOperationException occured : Please annotate your JPA model with #javax.persistence.Entity annotation."
I'm using Eclipse. Also note that i have changed tasks to be persons in:
My Person model/class-defination in Person.java
package models;
import play.*;
import play.db.jpa.*;
import javax.persistence.*;
import java.util.*;
public class Person extends Model{
public String title;
public boolean done;
public Person(String title){
this.title = title;
}
}
And application.java:
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index() {
List persons = Person.find("order by id desc").fetch();
render(persons);
}
}
The error is connected with this line:
List persons = Person.find("order by id desc").fetch();
Add #Entity to the top of the model class.
And let's be clear, use the Javax Entity annotation and not Hibernate's! As suggested in the official documentation!
As mentioned before add #Entity before your Model class.
Within your example the Person class would look like that:
package models;
import play.*;
import play.db.jpa.*;
import javax.persistence.*;
import java.util.*;
#Entity
public class Person extends Model{
public String title;
public boolean done;
public Person(String title){
this.title = title;
}
}

GWT-Objectify : basic

I've been through a few documentations, but am not able to communicate to the datastore yet...can anyone give me a sample project/code of objectify used in GWT web app(I use eclipse)...just a simple 'put' and 'get' action using RPC should do...or, atleast tell me how its done
Easiest way to understand how to make objectify work is to repeat all steps described in this article from David's Chandler blog. Whole blog is a pretty much must read if you interested in GWT, GAE(Java), gwt-presenter, gin\guice,etc. There you will find working example, but anyway here i'll show a slighly advanced example.
In package shared define your entity/model:
import javax.persistence.Embedded;
import javax.persistence.Id;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Unindexed;
#Entity
public class MyEntry implements IsSerializable {
// Objectify auto-generates Long IDs just like JDO / JPA
#Id private Long id;
#Unindexed private String text = "";
#Embedded private Time start;
// empty constructor for serialization
public MyEntry () {
}
public MyEntry (Time start, String text) {
super();
this.text = tText;
this.start = start;
}
/*constructors,getters,setters...*/
}
Time class (also shared package) contains just one field msecs:
#Entity
public class Time implements IsSerializable, Comparable<Time> {
protected int msecs = -1;
//rest of code like in MyEntry
}
Copy class ObjectifyDao from link above to your server.dao package. And then make DAO class specifically for MyEntry -- MyEntryDAO:
package com.myapp.server.dao;
import java.util.logging.Logger;
import com.googlecode.objectify.ObjectifyService;
import com.myapp.shared.MyEntryDao;
public class MyEntryDao extends ObjectifyDao<MyEntry>
{
private static final Logger LOG = Logger.getLogger(MyEntryDao.class.getName());
static
{
ObjectifyService.register(MyEntry.class);
}
public MyEntryDao()
{
super(MyEntry.class);
}
}
Finally we can make requests to database(server package):
public class FinallyDownloadingEntriesServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/plain");
//more code...
resp.setHeader("Content-Disposition", "attachment; filename=\""+"MyFileName"+".txt\";");
try {
MyEntryDao = new MyEntryDao();
/*query to get all MyEntries from datastore sorted by start Time*/
ArrayList<MyEntry> entries = (ArrayList<MyEntry>) dao.ofy().query(MyEntry.class).order("start.msecs").list();
PrintWriter out = resp.getWriter();
int i = 0;
for (MyEntry entry : entries) {
++i;
out.println(i);
out.println(entry.getStart() + entry.getText());
out.println();
}
} finally {
//catching exceptions
}
}