From b7e1b19b42097d559f21bb867fbe9b192061d36e Mon Sep 17 00:00:00 2001 From: nawal-ahmad Date: Sat, 23 Oct 2021 21:24:11 +0300 Subject: [PATCH 01/10] signup-login-profile --- build.gradle | 8 +- .../com/example/init/controllers/User.java | 65 ++++++++ .../example/init/models/ApplicationUser.java | 144 ++++++++++++++++++ .../ApplicationUserRepository.java | 10 ++ .../init/security/UserDetailsServiceImpl.java | 25 +++ .../init/security/WebSecurityConfig.java | 32 ++++ src/main/resources/application.properties | 23 ++- src/main/resources/templates/login.html | 29 ++++ src/main/resources/templates/profile.html | 18 +++ src/main/resources/templates/signup.html | 45 ++++++ 10 files changed, 389 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/example/init/controllers/User.java create mode 100644 src/main/java/com/example/init/models/ApplicationUser.java create mode 100644 src/main/java/com/example/init/repositories/ApplicationUserRepository.java create mode 100644 src/main/java/com/example/init/security/UserDetailsServiceImpl.java create mode 100644 src/main/java/com/example/init/security/WebSecurityConfig.java create mode 100644 src/main/resources/templates/login.html create mode 100644 src/main/resources/templates/profile.html create mode 100644 src/main/resources/templates/signup.html diff --git a/build.gradle b/build.gradle index 71840fc..8a1b3cf 100644 --- a/build.gradle +++ b/build.gradle @@ -13,16 +13,16 @@ repositories { } dependencies { - // implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - // implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-websocket' - // implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-test' - // testImplementation 'org.springframework.security:spring-security-test' + testImplementation 'org.springframework.security:spring-security-test' } test { diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java new file mode 100644 index 0000000..413b164 --- /dev/null +++ b/src/main/java/com/example/init/controllers/User.java @@ -0,0 +1,65 @@ +package com.example.init.controllers; + +import antlr.BaseAST; +import com.example.init.models.ApplicationUser; +import com.example.init.repositories.ApplicationUserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.servlet.view.RedirectView; + +import java.security.Principal; +import java.util.ArrayList; + +@Controller +public class User { + + @Autowired + BCryptPasswordEncoder bCryptPasswordEncoder; + + @Autowired + ApplicationUserRepository applicationUserRepository; + + @GetMapping("/signup") + public String getSignUpPage() { + return "signup"; + } + + @GetMapping("/login") + public String getSignInPage() { + return "login"; + } + + @PostMapping("/signup") + public RedirectView attemptSignUp(@ModelAttribute ApplicationUser user) { + ApplicationUser newUser = new ApplicationUser(user.getEmail(),user.getUsername(), + bCryptPasswordEncoder.encode(user.getPassword()), + user.getFirstName(), user.getLastName(), user.getDateOfBirth(), user.getBio()); + applicationUserRepository.save(newUser); + Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); + SecurityContextHolder.getContext().setAuthentication(authentication); + return new RedirectView("/login"); + } + + @PostMapping("/login") + public RedirectView loginResponse(@ModelAttribute ApplicationUser user, Model model) { + model.addAttribute("username", applicationUserRepository.findByUsername(user.getUsername())); + return new RedirectView("profile"); + } + + @GetMapping("/profile") + public String getUserProfile(Principal principal, Model model) { + ApplicationUser user = applicationUserRepository.findByUsername(principal.getName()); + model.addAttribute("username", principal.getName()); + model.addAttribute("userProfile", user); + return "profile"; + } + +} diff --git a/src/main/java/com/example/init/models/ApplicationUser.java b/src/main/java/com/example/init/models/ApplicationUser.java new file mode 100644 index 0000000..7f4ca18 --- /dev/null +++ b/src/main/java/com/example/init/models/ApplicationUser.java @@ -0,0 +1,144 @@ +package com.example.init.models; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import javax.persistence.*; +import java.util.Collection; + +@Entity +public class ApplicationUser implements UserDetails { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + @Column(unique = true) + private String email; + + @Column(unique = true) + private String username; + + private String password; + private String firstName; + private String lastName; + private String dateOfBirth; + private String bio; + + public ApplicationUser() { + } + + public ApplicationUser(Long id, String email, String username, String password, String firstName, String lastName, String dateOfBirth, String bio) { + this.id = id; + this.email = email; + this.username = username; + this.password = password; + this.firstName = firstName; + this.lastName = lastName; + this.dateOfBirth = dateOfBirth; + this.bio = bio; + } + + public ApplicationUser(String email, String username, String password, String firstName, String lastName, String dateOfBirth, String bio) { + this.email = email; + this.username = username; + this.password = password; + this.firstName = firstName; + this.lastName = lastName; + this.dateOfBirth = dateOfBirth; + this.bio = bio; + } + + + @Override + public Collection getAuthorities() { + return null; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public boolean isAccountNonExpired() { + return false; + } + + @Override + public boolean isAccountNonLocked() { + return false; + } + + @Override + public boolean isCredentialsNonExpired() { + return false; + } + + @Override + public boolean isEnabled() { + return false; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setUsername(String username) { + this.username = username; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getBio() { + return bio; + } + + public void setBio(String bio) { + this.bio = bio; + } + +} diff --git a/src/main/java/com/example/init/repositories/ApplicationUserRepository.java b/src/main/java/com/example/init/repositories/ApplicationUserRepository.java new file mode 100644 index 0000000..b2dba6f --- /dev/null +++ b/src/main/java/com/example/init/repositories/ApplicationUserRepository.java @@ -0,0 +1,10 @@ +package com.example.init.repositories; + +import com.example.init.models.ApplicationUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ApplicationUserRepository extends JpaRepository { + public ApplicationUser findByUsername(String username); +} diff --git a/src/main/java/com/example/init/security/UserDetailsServiceImpl.java b/src/main/java/com/example/init/security/UserDetailsServiceImpl.java new file mode 100644 index 0000000..c6b5e57 --- /dev/null +++ b/src/main/java/com/example/init/security/UserDetailsServiceImpl.java @@ -0,0 +1,25 @@ +package com.example.init.security; + +import com.example.init.models.ApplicationUser; +import com.example.init.repositories.ApplicationUserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + @Autowired + ApplicationUserRepository applicationUserRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + ApplicationUser applicationUser = applicationUserRepository.findByUsername(username); + if (applicationUser == null) { + throw new UsernameNotFoundException((username + " not found!")); + } + return applicationUser; + } +} diff --git a/src/main/java/com/example/init/security/WebSecurityConfig.java b/src/main/java/com/example/init/security/WebSecurityConfig.java new file mode 100644 index 0000000..d29a49e --- /dev/null +++ b/src/main/java/com/example/init/security/WebSecurityConfig.java @@ -0,0 +1,32 @@ +package com.example.init.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + UserDetailsServiceImpl userDetailsService; + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().disable().csrf().disable().authorizeRequests().antMatchers( "/login", "/signup","/").permitAll().antMatchers("/adminpanel").hasAuthority("ROLE_ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").loginProcessingUrl("/perform_login").defaultSuccessUrl("/", true).failureUrl("/error").and().logout().logoutUrl("/perform_logout"); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index f03a366..30c62a3 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,18 @@ +spring.datasource.hikari.connectionTimeout=20000 +spring.datasource.hikari.maximumPoolSize=5 spring.sql.init.platform=postgres -spring.datasource.url=jdbc:postgresql://localhost:5432/coders -spring.datasource.username=abdelqader -spring.datasource.password=0000 -spring.jpa.database=postgresql -spring.jpa.generate-ddl=true -spring.jpa.hibernate.ddl-auto=update + +spring.datasource.url=jdbc:postgresql://localhost:5433/init +spring.datasource.username=postgres +spring.datasource.password=1234 + +spring.jpa.hibernate.ddl-auto=create-drop +spring.datasource.initialization-mode=always + +spring.jpa.show-sql=true +spring.jpa.generate-ddl=false +spring.jpa.open-in-view=false +spring.jpa.properties.hibernate.show_sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.type=trace +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html new file mode 100644 index 0000000..2ee5460 --- /dev/null +++ b/src/main/resources/templates/login.html @@ -0,0 +1,29 @@ + + + + + login + + + +
+ +
+ Invalid username and password. +
+
+ You have been logged out. +
+ +
+ + +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html new file mode 100644 index 0000000..18157f4 --- /dev/null +++ b/src/main/resources/templates/profile.html @@ -0,0 +1,18 @@ + + + + + user ptofile + + + +
+ ProfilePicture +
+
+

+

+

+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/signup.html b/src/main/resources/templates/signup.html new file mode 100644 index 0000000..29ce50c --- /dev/null +++ b/src/main/resources/templates/signup.html @@ -0,0 +1,45 @@ + + + + + signup + + + +
+ Sign up +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+ + \ No newline at end of file From 9820bf9dfbb69154027eda9f4561dedae29ca382 Mon Sep 17 00:00:00 2001 From: nawal-ahmad Date: Sun, 24 Oct 2021 10:06:10 +0300 Subject: [PATCH 02/10] signup-signin-profile --- .../com/example/init/controllers/User.java | 6 +++++ .../ApplicationUserRepository.java | 1 + .../init/security/WebSecurityConfig.java | 22 ++++++++++++++++++- src/main/resources/templates/login.html | 2 +- src/main/resources/templates/profile.html | 1 + 5 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index 413b164..c870e2e 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -7,6 +7,8 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -17,6 +19,7 @@ import java.security.Principal; import java.util.ArrayList; +import java.util.Optional; @Controller public class User { @@ -51,9 +54,12 @@ public RedirectView attemptSignUp(@ModelAttribute ApplicationUser user) { @PostMapping("/login") public RedirectView loginResponse(@ModelAttribute ApplicationUser user, Model model) { model.addAttribute("username", applicationUserRepository.findByUsername(user.getUsername())); + model.addAttribute("email", applicationUserRepository.findByEmail(user.getEmail())); +// if (user.isEmpty()) user = applicationUserRepository.findByUsername(email); return new RedirectView("profile"); } + @GetMapping("/profile") public String getUserProfile(Principal principal, Model model) { ApplicationUser user = applicationUserRepository.findByUsername(principal.getName()); diff --git a/src/main/java/com/example/init/repositories/ApplicationUserRepository.java b/src/main/java/com/example/init/repositories/ApplicationUserRepository.java index b2dba6f..bba47bc 100644 --- a/src/main/java/com/example/init/repositories/ApplicationUserRepository.java +++ b/src/main/java/com/example/init/repositories/ApplicationUserRepository.java @@ -7,4 +7,5 @@ @Repository public interface ApplicationUserRepository extends JpaRepository { public ApplicationUser findByUsername(String username); + public ApplicationUser findByEmail(String email); } diff --git a/src/main/java/com/example/init/security/WebSecurityConfig.java b/src/main/java/com/example/init/security/WebSecurityConfig.java index d29a49e..f72fb63 100644 --- a/src/main/java/com/example/init/security/WebSecurityConfig.java +++ b/src/main/java/com/example/init/security/WebSecurityConfig.java @@ -27,6 +27,26 @@ protected void configure(AuthenticationManagerBuilder auth) throws Exception { @Override protected void configure(HttpSecurity http) throws Exception { - http.cors().disable().csrf().disable().authorizeRequests().antMatchers( "/login", "/signup","/").permitAll().antMatchers("/adminpanel").hasAuthority("ROLE_ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").loginProcessingUrl("/perform_login").defaultSuccessUrl("/", true).failureUrl("/error").and().logout().logoutUrl("/perform_logout"); + http + .cors() + .disable(). + csrf() + .disable() + .authorizeRequests() + .antMatchers( "/login", "/signup","/") + .permitAll().antMatchers("/adminpanel") + .hasAuthority("ROLE_ADMIN") + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login") + .usernameParameter("email") + .permitAll() + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/", true) + .failureUrl("/error") + .and() + .logout() + .logoutUrl("/perform_logout"); } } diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html index 2ee5460..1fbc38b 100644 --- a/src/main/resources/templates/login.html +++ b/src/main/resources/templates/login.html @@ -16,7 +16,7 @@
- +
diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html index 18157f4..d701c06 100644 --- a/src/main/resources/templates/profile.html +++ b/src/main/resources/templates/profile.html @@ -10,6 +10,7 @@ ProfilePicture
+

From 680942d0f7673904edca84bb0817fa2038aee1c8 Mon Sep 17 00:00:00 2001 From: nawal-ahmad Date: Sun, 24 Oct 2021 12:24:54 +0300 Subject: [PATCH 03/10] post --- .../com/example/init/controllers/User.java | 19 ++++-- .../example/init/models/ApplicationUser.java | 61 ++++++++--------- .../java/com/example/init/models/Post.java | 67 +++++++++++++++++++ .../init/repositories/PostRepository.java | 9 +++ src/main/resources/templates/profile.html | 31 ++++++++- 5 files changed, 149 insertions(+), 38 deletions(-) create mode 100644 src/main/java/com/example/init/models/Post.java create mode 100644 src/main/java/com/example/init/repositories/PostRepository.java diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index c870e2e..28058d2 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -2,7 +2,9 @@ import antlr.BaseAST; import com.example.init.models.ApplicationUser; +import com.example.init.models.Post; import com.example.init.repositories.ApplicationUserRepository; +import com.example.init.repositories.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -16,10 +18,8 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.view.RedirectView; - import java.security.Principal; import java.util.ArrayList; -import java.util.Optional; @Controller public class User { @@ -30,6 +30,9 @@ public class User { @Autowired ApplicationUserRepository applicationUserRepository; + @Autowired + PostRepository postRepository; + @GetMapping("/signup") public String getSignUpPage() { return "signup"; @@ -42,9 +45,8 @@ public String getSignInPage() { @PostMapping("/signup") public RedirectView attemptSignUp(@ModelAttribute ApplicationUser user) { - ApplicationUser newUser = new ApplicationUser(user.getEmail(),user.getUsername(), - bCryptPasswordEncoder.encode(user.getPassword()), - user.getFirstName(), user.getLastName(), user.getDateOfBirth(), user.getBio()); + ApplicationUser newUser = new ApplicationUser(user.getEmail(),bCryptPasswordEncoder.encode(user.getUsername()),user.getPassword(), + user.getFirstName(),user.getLastName(),user.getDateOfBirth(),user.getBio()); applicationUserRepository.save(newUser); Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); SecurityContextHolder.getContext().setAuthentication(authentication); @@ -68,4 +70,11 @@ public String getUserProfile(Principal principal, Model model) { return "profile"; } + @PostMapping("/addPost") + public RedirectView addPost(Principal principle, String body) { + ApplicationUser newUser = applicationUserRepository.findByUsername(principle.getName()); + Post post = new Post(newUser, body); + postRepository.save(post); + return new RedirectView("/profile"); + } } diff --git a/src/main/java/com/example/init/models/ApplicationUser.java b/src/main/java/com/example/init/models/ApplicationUser.java index 7f4ca18..6b7d7c9 100644 --- a/src/main/java/com/example/init/models/ApplicationUser.java +++ b/src/main/java/com/example/init/models/ApplicationUser.java @@ -2,9 +2,9 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; - import javax.persistence.*; import java.util.Collection; +import java.util.List; @Entity public class ApplicationUser implements UserDetails { @@ -18,29 +18,20 @@ public class ApplicationUser implements UserDetails { @Column(unique = true) private String username; - private String password; private String firstName; private String lastName; private String dateOfBirth; private String bio; - public ApplicationUser() { - } + @OneToMany (mappedBy = "applicationUser", fetch = FetchType.EAGER) + private List posts; - public ApplicationUser(Long id, String email, String username, String password, String firstName, String lastName, String dateOfBirth, String bio) { - this.id = id; - this.email = email; - this.username = username; - this.password = password; - this.firstName = firstName; - this.lastName = lastName; - this.dateOfBirth = dateOfBirth; - this.bio = bio; + public ApplicationUser() { } public ApplicationUser(String email, String username, String password, String firstName, String lastName, String dateOfBirth, String bio) { - this.email = email; + this.id = id; this.username = username; this.password = password; this.firstName = firstName; @@ -49,22 +40,6 @@ public ApplicationUser(String email, String username, String password, String fi this.bio = bio; } - - @Override - public Collection getAuthorities() { - return null; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public String getUsername() { - return username; - } - @Override public boolean isAccountNonExpired() { return false; @@ -85,6 +60,15 @@ public boolean isEnabled() { return false; } + public void setUsername(String username) { + this.username = username; + } + + @Override + public Collection getAuthorities() { + return null; + } + public Long getId() { return id; } @@ -101,8 +85,14 @@ public void setEmail(String email) { this.email = email; } - public void setUsername(String username) { - this.username = username; + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; } public void setPassword(String password) { @@ -141,4 +131,11 @@ public void setBio(String bio) { this.bio = bio; } + public List getPosts() { + return posts; + } + + public void setPosts(List posts) { + this.posts = posts; + } } diff --git a/src/main/java/com/example/init/models/Post.java b/src/main/java/com/example/init/models/Post.java new file mode 100644 index 0000000..1be4400 --- /dev/null +++ b/src/main/java/com/example/init/models/Post.java @@ -0,0 +1,67 @@ +package com.example.init.models; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.hibernate.annotations.CreationTimestamp; +import org.springframework.format.annotation.DateTimeFormat; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Entity +public class Post { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + @ManyToOne() + @JoinColumn(name = "application_user_id") + private ApplicationUser applicationUser; + + private String body; + + @CreationTimestamp + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + @JsonFormat(pattern = "yyyy-MM-dd||HH:mm:ss") + private LocalDateTime createdAt; + + public Post() { + } + + public Post(ApplicationUser applicationUser, String body ) { + this.applicationUser = applicationUser; + this.body = body; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public ApplicationUser getApplicationUser() { + return applicationUser; + } + + public void setApplicationUser(ApplicationUser applicationUser) { + this.applicationUser = applicationUser; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + } +} diff --git a/src/main/java/com/example/init/repositories/PostRepository.java b/src/main/java/com/example/init/repositories/PostRepository.java new file mode 100644 index 0000000..a2d4053 --- /dev/null +++ b/src/main/java/com/example/init/repositories/PostRepository.java @@ -0,0 +1,9 @@ +package com.example.init.repositories; + +import com.example.init.models.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PostRepository extends JpaRepository { +} diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html index d701c06..006e555 100644 --- a/src/main/resources/templates/profile.html +++ b/src/main/resources/templates/profile.html @@ -2,7 +2,7 @@ - user ptofile + user profile @@ -15,5 +15,34 @@
+ +
+
+ +
+
+
+ + +
+ +
+
+
+ +
+
+ +Posts + +
+
+
+

+

+
+
+
+ \ No newline at end of file From 97234e24c76608272da9806d2d9ef8e6c651fe74 Mon Sep 17 00:00:00 2001 From: nawal-ahmad Date: Sun, 24 Oct 2021 13:24:20 +0300 Subject: [PATCH 04/10] add post --- src/main/java/com/example/init/controllers/User.java | 2 +- src/main/java/com/example/init/models/ApplicationUser.java | 2 +- src/main/java/com/example/init/models/Post.java | 6 ++++-- src/main/resources/application.properties | 2 +- src/main/resources/templates/profile.html | 2 +- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index 28058d2..954e07c 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -45,7 +45,7 @@ public String getSignInPage() { @PostMapping("/signup") public RedirectView attemptSignUp(@ModelAttribute ApplicationUser user) { - ApplicationUser newUser = new ApplicationUser(user.getEmail(),bCryptPasswordEncoder.encode(user.getUsername()),user.getPassword(), + ApplicationUser newUser = new ApplicationUser(user.getEmail(),user.getUsername(),bCryptPasswordEncoder.encode(user.getPassword()), user.getFirstName(),user.getLastName(),user.getDateOfBirth(),user.getBio()); applicationUserRepository.save(newUser); Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); diff --git a/src/main/java/com/example/init/models/ApplicationUser.java b/src/main/java/com/example/init/models/ApplicationUser.java index 6b7d7c9..c8d5581 100644 --- a/src/main/java/com/example/init/models/ApplicationUser.java +++ b/src/main/java/com/example/init/models/ApplicationUser.java @@ -31,7 +31,7 @@ public ApplicationUser() { } public ApplicationUser(String email, String username, String password, String firstName, String lastName, String dateOfBirth, String bio) { - this.id = id; + this.email=email; this.username = username; this.password = password; this.firstName = firstName; diff --git a/src/main/java/com/example/init/models/Post.java b/src/main/java/com/example/init/models/Post.java index 1be4400..ec2fd70 100644 --- a/src/main/java/com/example/init/models/Post.java +++ b/src/main/java/com/example/init/models/Post.java @@ -14,7 +14,8 @@ public class Post { @Column(name = "id", nullable = false) private Long id; - @ManyToOne() + + @ManyToOne @JoinColumn(name = "application_user_id") private ApplicationUser applicationUser; @@ -22,7 +23,7 @@ public class Post { @CreationTimestamp @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - @JsonFormat(pattern = "yyyy-MM-dd||HH:mm:ss") +// @JsonFormat(pattern = "yyyy-MM-dd||HH:mm:ss") private LocalDateTime createdAt; public Post() { @@ -64,4 +65,5 @@ public LocalDateTime getCreatedAt() { public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } + } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 30c62a3..61bd96f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.datasource.url=jdbc:postgresql://localhost:5433/init spring.datasource.username=postgres spring.datasource.password=1234 -spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.ddl-auto=create spring.datasource.initialization-mode=always spring.jpa.show-sql=true diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html index 006e555..8e0f5f7 100644 --- a/src/main/resources/templates/profile.html +++ b/src/main/resources/templates/profile.html @@ -9,7 +9,7 @@
ProfilePicture
-
+

From 505504577c2ee5a99c9c69f4b8c982d1fa6b1640 Mon Sep 17 00:00:00 2001 From: abdelqader-alomari Date: Sun, 24 Oct 2021 15:23:30 +0300 Subject: [PATCH 05/10] back to main --- api.json | 98 +++++++++++++++++++ recentquotes.json | 1 + .../com/example/init/controllers/Home.java | 6 ++ src/main/resources/templates/home.html | 8 ++ 4 files changed, 113 insertions(+) create mode 100644 api.json create mode 100644 recentquotes.json diff --git a/api.json b/api.json new file mode 100644 index 0000000..fa9b858 --- /dev/null +++ b/api.json @@ -0,0 +1,98 @@ +[ + { + "id": 849, + "question": "How to remove the docker container with container id mentioned in the command.", + "description": null, + "answers": { + "answer_a": "$ docker rm -rf 9b6343d3b5a0", + "answer_b": "$ docker -rm rf 9b6343d3b5a0", + "answer_c": "$ docker rm 9b6343d3b5a0", + "answer_d": null, + "answer_e": null, + "answer_f": null + }, + "multiple_correct_answers": "false", + "correct_answers": { + "answer_a_correct": "false", + "answer_b_correct": "false", + "answer_c_correct": "true", + "answer_d_correct": "false", + "answer_e_correct": "false", + "answer_f_correct": "false" + }, + "correct_answer": "answer_a", + "explanation": null, + "tip": null, + "tags": [ + { + "name": "Docker" + } + ], + "category": "Docker", + "difficulty": "Easy" + }, + { + "id": 26, + "question": "What is a daemon?", + "description": null, + "answers": { + "answer_a": "It is a generic name for e-mail servers on Linux. The most famous one is mailer-daemon", + "answer_b": "It is a program that keeps running on the background after it is called, answering to requests done by users and other programs.", + "answer_c": "It is an antivirus for Linux.", + "answer_d": "It is the generic name for any Linux server.", + "answer_e": null, + "answer_f": null + }, + "multiple_correct_answers": "false", + "correct_answers": { + "answer_a_correct": "false", + "answer_b_correct": "true", + "answer_c_correct": "false", + "answer_d_correct": "false", + "answer_e_correct": "false", + "answer_f_correct": "false" + }, + "correct_answer": "answer_b", + "explanation": null, + "tip": null, + "tags": [ + { + "name": "Linux" + } + ], + "category": "Linux", + "difficulty": "Medium" + }, + { + "id": 627, + "question": "How can we set infinite execution time for a PHP script?", + "description": null, + "answers": { + "answer_a": "Add set_time_limit() at the beginning of a script", + "answer_b": "Add set_time_limit(infinity) at the beginning of a script", + "answer_c": "Add set_time_limit(0) at the beginning of a script", + "answer_d": null, + "answer_e": null, + "answer_f": null + }, + "multiple_correct_answers": "false", + "correct_answers": { + "answer_a_correct": "false", + "answer_b_correct": "false", + "answer_c_correct": "true", + "answer_d_correct": "false", + "answer_e_correct": "false", + "answer_f_correct": "false" + }, + "correct_answer": "answer_a", + "explanation": null, + "tip": null, + "tags": [ + { + "name": "PHP" + } + ], + "category": "Code", + "difficulty": "Medium" + } + ] \ No newline at end of file diff --git a/recentquotes.json b/recentquotes.json new file mode 100644 index 0000000..fa6c1bc --- /dev/null +++ b/recentquotes.json @@ -0,0 +1 @@ +{"quoteText":"A lot of people give up just before theyre about to make it. You know you never know when that next obstacle is going to be the last one. ", "quoteAuthor":"Chuck Norris", "senderName":"", "senderLink":"", "quoteLink":"http://forismatic.com/en/2bc6cf0fd5/"} \ No newline at end of file diff --git a/src/main/java/com/example/init/controllers/Home.java b/src/main/java/com/example/init/controllers/Home.java index 6adc840..b34f5e3 100644 --- a/src/main/java/com/example/init/controllers/Home.java +++ b/src/main/java/com/example/init/controllers/Home.java @@ -10,4 +10,10 @@ public class Home { public String home() { return "home"; } + + @GetMapping("/index") + public String index() { + return "index"; + } + } diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html index 033f5e1..6b510d5 100644 --- a/src/main/resources/templates/home.html +++ b/src/main/resources/templates/home.html @@ -8,5 +8,13 @@

Hello World

+ From 0c065c9264263b1ba84af46ee43edb690ccadd2c Mon Sep 17 00:00:00 2001 From: abdelqader-alomari Date: Sun, 24 Oct 2021 15:31:49 +0300 Subject: [PATCH 06/10] any --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 71840fc..b66f0b1 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ repositories { } dependencies { - // implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web' @@ -23,6 +23,8 @@ dependencies { runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-test' // testImplementation 'org.springframework.security:spring-security-test' + implementation 'com.google.code.gson:gson:2.8.8' + } test { From 560a7bfca61f9b17b21cdc05de8b24c17ec7dd34 Mon Sep 17 00:00:00 2001 From: mohnalkhateeb Date: Sun, 24 Oct 2021 16:38:03 +0300 Subject: [PATCH 07/10] api_get --- build.gradle | 1 + .../com/example/init/InitApplication.java | 1 + .../init/controllers/CodeController.java | 8 ++ .../init/controllers/CourseController.java | 56 +++++++++ .../init/controllers/QuizController.java | 41 +++++++ .../com/example/init/controllers/User.java | 4 - .../example/init/models/ApplicationUser.java | 4 + .../java/com/example/init/models/Code.java | 56 +++++++++ .../java/com/example/init/models/Courses.java | 108 ++++++++++++++++ .../java/com/example/init/models/Quiz.java | 53 ++++++++ .../init/repositories/CodeRepositories.java | 10 ++ .../init/repositories/CourseRepository.java | 9 ++ .../init/security/WebSecurityConfig.java | 2 +- src/main/resources/application.properties | 6 +- src/main/resources/json.json | 115 ++++++++++++++++++ src/main/resources/templates/courses.html | 26 ++++ src/main/resources/templates/quiz.html | 32 +++++ 17 files changed, 524 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/example/init/controllers/CodeController.java create mode 100644 src/main/java/com/example/init/controllers/CourseController.java create mode 100644 src/main/java/com/example/init/controllers/QuizController.java create mode 100644 src/main/java/com/example/init/models/Code.java create mode 100644 src/main/java/com/example/init/models/Courses.java create mode 100644 src/main/java/com/example/init/models/Quiz.java create mode 100644 src/main/java/com/example/init/repositories/CodeRepositories.java create mode 100644 src/main/java/com/example/init/repositories/CourseRepository.java create mode 100644 src/main/resources/json.json create mode 100644 src/main/resources/templates/courses.html create mode 100644 src/main/resources/templates/quiz.html diff --git a/build.gradle b/build.gradle index 8a1b3cf..8d03cce 100644 --- a/build.gradle +++ b/build.gradle @@ -23,6 +23,7 @@ dependencies { runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' + implementation 'com.google.code.gson:gson:2.8.8' } test { diff --git a/src/main/java/com/example/init/InitApplication.java b/src/main/java/com/example/init/InitApplication.java index 365f755..400e74e 100644 --- a/src/main/java/com/example/init/InitApplication.java +++ b/src/main/java/com/example/init/InitApplication.java @@ -8,6 +8,7 @@ public class InitApplication { public static void main(String[] args) { SpringApplication.run(InitApplication.class, args); + } } diff --git a/src/main/java/com/example/init/controllers/CodeController.java b/src/main/java/com/example/init/controllers/CodeController.java new file mode 100644 index 0000000..009f082 --- /dev/null +++ b/src/main/java/com/example/init/controllers/CodeController.java @@ -0,0 +1,8 @@ +package com.example.init.controllers; + +import org.springframework.stereotype.Controller; + +@Controller +public class CodeController { + +} diff --git a/src/main/java/com/example/init/controllers/CourseController.java b/src/main/java/com/example/init/controllers/CourseController.java new file mode 100644 index 0000000..95c0f73 --- /dev/null +++ b/src/main/java/com/example/init/controllers/CourseController.java @@ -0,0 +1,56 @@ +package com.example.init.controllers; + +import com.example.init.models.Courses; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; + +@Controller +public class CourseController { + + +// @Autowired +// CourseRepository courseRepository; + + + @GetMapping("/courses") + public String getCourses(Model model) throws Exception { + + Gson gson = new Gson(); + + JsonReader reader = new JsonReader(new FileReader("C:\\Users\\STUDENT\\java401\\SSD-Projects\\init\\src\\main\\resources\\json.json")); +// ArrayList courses= readJsonFile(courseFile); + Type jsonCasting = new TypeToken>() { + }.getType(); + List jsonList = gson.fromJson(reader, jsonCasting); +// Courses courses = new Courses(); +// courses.setTitle("hello from "); + model.addAttribute("courses" ,jsonList); +// courseRepository.save(courses); + return "courses"; + } + + + + + + + +// System.out.println("-------------------------------hello-----------------------------------------------------------------------"); +//// System.out.println(Courses.readJsonFile(courseFile)); +// System.out.println("--------------------------------after hello ----------------------------------------------------------------------"); +// System.out.println(jsonList.toString()); + + +} diff --git a/src/main/java/com/example/init/controllers/QuizController.java b/src/main/java/com/example/init/controllers/QuizController.java new file mode 100644 index 0000000..794de6b --- /dev/null +++ b/src/main/java/com/example/init/controllers/QuizController.java @@ -0,0 +1,41 @@ +package com.example.init.controllers; + +import com.example.init.models.Quiz; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +@Controller +public class QuizController { + + + + + @GetMapping("/quiz") + public String getQuiz(Model model) throws IOException { + Gson gson = new Gson(); + String urlApi = "https://quizapi.io/api/v1/questions?apiKey=phkL2Z69NDCrImLlfnLoElQkoF3StoJlQrAeKvkf&limit=10&css"; + HttpURLConnection connection = (HttpURLConnection) new URL(urlApi).openConnection(); + InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream()); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String data = bufferedReader.readLine(); + Type jsonCasting = new TypeToken>(){}.getType(); + List jsonList = gson.fromJson(data,jsonCasting); + model.addAttribute("quiz",jsonList); +// model.addAttribute("answers",jsonList); + bufferedReader.close(); + return "quiz"; + } +} diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index c870e2e..c128450 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -1,14 +1,11 @@ package com.example.init.controllers; -import antlr.BaseAST; import com.example.init.models.ApplicationUser; import com.example.init.repositories.ApplicationUserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -19,7 +16,6 @@ import java.security.Principal; import java.util.ArrayList; -import java.util.Optional; @Controller public class User { diff --git a/src/main/java/com/example/init/models/ApplicationUser.java b/src/main/java/com/example/init/models/ApplicationUser.java index 7f4ca18..a26537a 100644 --- a/src/main/java/com/example/init/models/ApplicationUser.java +++ b/src/main/java/com/example/init/models/ApplicationUser.java @@ -4,7 +4,9 @@ import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; @Entity public class ApplicationUser implements UserDetails { @@ -25,6 +27,8 @@ public class ApplicationUser implements UserDetails { private String dateOfBirth; private String bio; + @OneToMany(mappedBy = "author" , fetch = FetchType.EAGER) + private List codes ; public ApplicationUser() { } diff --git a/src/main/java/com/example/init/models/Code.java b/src/main/java/com/example/init/models/Code.java new file mode 100644 index 0000000..8d9a88e --- /dev/null +++ b/src/main/java/com/example/init/models/Code.java @@ -0,0 +1,56 @@ +package com.example.init.models; + +import javax.persistence.*; + +@Entity +public class Code { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + private String title; + private String body; + + @ManyToOne + @JoinColumn(name = "author_id") + private ApplicationUser author; + + public ApplicationUser getAuthor() { + return author; + } + + public Code(Long id, String title, String body, ApplicationUser author) { + this.id = id; + this.title = title; + this.body = body; + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public void setAuthor(ApplicationUser author) { + this.author = author; + } +} diff --git a/src/main/java/com/example/init/models/Courses.java b/src/main/java/com/example/init/models/Courses.java new file mode 100644 index 0000000..367c694 --- /dev/null +++ b/src/main/java/com/example/init/models/Courses.java @@ -0,0 +1,108 @@ +package com.example.init.models; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; + +//import javax.persistence.*; +import javax.persistence.*; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +// +@Entity +public class Courses { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; +// public int course_id; + public String title; + public String course_level; + public String description; + public String image; + + public Courses() throws Exception { + + } + + + public Courses(String title, String course_level, String description, String image) throws Exception { + this.title = title; + this.course_level = course_level; + this.description = description; + this.image = image; + + } + + + + // this is reader json file -------------------------- + public static ArrayList readJsonFile(FileReader jsonFile) { + // create Gson instance + Gson gson = new Gson(); + + // create a reader + BufferedReader reader = new BufferedReader(jsonFile); + + // convert JSON array to list of users + ArrayList courses = gson.fromJson(reader,new TypeToken>() {}.getType()); + + + System.out.println(courses); + return courses; + } + +// ------------------------------------ this is the End + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getCourse_level() { + return course_level; + } + + public void setCourse_level(String course_level) { + this.course_level = course_level; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getImage() { + return image; + } + + public void setImage(String image) { + this.image = image; + } + + + + + @Override + public String toString() { + return "Courses{" + + "title='" + title + '\'' + + ", description='" + description + '\'' + + ", image='" + image + '\'' + + '}'; + } +} diff --git a/src/main/java/com/example/init/models/Quiz.java b/src/main/java/com/example/init/models/Quiz.java new file mode 100644 index 0000000..bf4692f --- /dev/null +++ b/src/main/java/com/example/init/models/Quiz.java @@ -0,0 +1,53 @@ +package com.example.init.models; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import javax.persistence.*; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +@Entity +public class Quiz { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + public String question; +// public String answers; + + public Quiz(String question) { + this.question = question; +// this.answers = answers; + } + + public Long getId() { + return id; + } + +// public String url = "https://quizapi.io/api/v1/questions?apiKey=phkL2Z69NDCrImLlfnLoElQkoF3StoJlQrAeKvkf&limit=5&css"; + + public Quiz() { + } + +// public String getAnswers() { +// return answers; +// } + +// public void setAnswers(String answers) { +// this.answers = answers; +// } + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + +} diff --git a/src/main/java/com/example/init/repositories/CodeRepositories.java b/src/main/java/com/example/init/repositories/CodeRepositories.java new file mode 100644 index 0000000..0ca8a04 --- /dev/null +++ b/src/main/java/com/example/init/repositories/CodeRepositories.java @@ -0,0 +1,10 @@ +package com.example.init.repositories; + +import com.example.init.models.Code; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CodeRepositories extends JpaRepository { + +} diff --git a/src/main/java/com/example/init/repositories/CourseRepository.java b/src/main/java/com/example/init/repositories/CourseRepository.java new file mode 100644 index 0000000..338f5b1 --- /dev/null +++ b/src/main/java/com/example/init/repositories/CourseRepository.java @@ -0,0 +1,9 @@ +package com.example.init.repositories; + +import com.example.init.models.Courses; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CourseRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/init/security/WebSecurityConfig.java b/src/main/java/com/example/init/security/WebSecurityConfig.java index f72fb63..3b7cd93 100644 --- a/src/main/java/com/example/init/security/WebSecurityConfig.java +++ b/src/main/java/com/example/init/security/WebSecurityConfig.java @@ -33,7 +33,7 @@ protected void configure(HttpSecurity http) throws Exception { csrf() .disable() .authorizeRequests() - .antMatchers( "/login", "/signup","/") + .antMatchers( "/login", "/signup","/","/quiz") .permitAll().antMatchers("/adminpanel") .hasAuthority("ROLE_ADMIN") .anyRequest().authenticated() diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 30c62a3..ae3973a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,11 +2,11 @@ spring.datasource.hikari.connectionTimeout=20000 spring.datasource.hikari.maximumPoolSize=5 spring.sql.init.platform=postgres -spring.datasource.url=jdbc:postgresql://localhost:5433/init -spring.datasource.username=postgres +spring.datasource.url=jdbc:postgresql://localhost:5432/init +spring.datasource.username=mohammad spring.datasource.password=1234 -spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.ddl-auto=update spring.datasource.initialization-mode=always spring.jpa.show-sql=true diff --git a/src/main/resources/json.json b/src/main/resources/json.json new file mode 100644 index 0000000..e1857cd --- /dev/null +++ b/src/main/resources/json.json @@ -0,0 +1,115 @@ +[ + { + "id": 1, + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Interactive Technology Studio", + "course_level": "Graduate/Professional Only (200+)", + "description": "Technologies, languages, and skills required for creating prototypes to communicate interactive technology concepts. Topics include HTTP, CSS, CSS scripting, AJAX, Design Patterns, Javascript, Javascript libraries such as jQuery, SQL, MVC, and cloud architectures.", + "image":"https://united-pop.com/website/var/tmp/image-thumbnails/0/3214/thumb__diplomaCourseDetail/interactive_audio_designer~-~480w.jpeg"}, + { + "id": 2, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Programming in Java as a Second Language", + "course_level": "Lower Division (1-99)", + + "description": "An introduction to the lexical, syntactic, semantic, and pragmatic characteristics of the Java language for experienced programmers. Emphasis on object-oriented programming, using standard libraries, and programming with automatic garbage collection.", + "image":"https://miro.medium.com/max/750/1*HuoU7i1AIvkUSApmIx8XQw.png"}, + { + "id": 3, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Computer Game Development", + "course_level": "Graduate/Professional Only (200+)", + + "description": "Introduction to the principles of interactive 2D and 3D computer game development. Concepts in computer graphics, algorithms, software engineering, art and graphics, music and sound, story analysis, and artificial intelligence are presented and are the basis for student work.", +"image":"https://images.ctfassets.net/3s5io6mnxfqz/32WnMVURX2H9rRiNA1qbsg/a93ccb573ad78895d20bccbfdeece606/AdobeStock_345938875.jpeg?fm=jpg&w=900&fl=progressive"}, + { + "id": 4, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Artificial Intelligence in Biology and Medicine", + "course_level": "Upper Division (100-199)", + + "description": "Introduction to computational methods in molecular biology, aimed at those interested in learning about this interdisciplinary area. Covers computational approaches to understanding and predicting the structure, function, interactions, and evolution of DNA, RNA, proteins, and related molecules and processes.", + "image" : "https://tedxashokau.com/wp-content/uploads/2020/10/Artificial-Intelligence.jpg" + }, + { + "id": 5, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Digital Image Processing", + "course_level": "Upper Division (100-199)", + + "description": "Introduction to the fundamental concepts of digital signal and image processing as applicable in areas such as multimedia, graphics, AI, data mining, databases, vision, or video games. Topics include image representation, space- and frequency-domain transformations, filters, segmentation, and compression.", + "image" : "https://online.stanford.edu/sites/default/files/styles/figure_default/public/2018-03/ee_digitalimageprocessing_ee368.jpg?itok=S2vGmtU4" + }, + { + "id": 6, + + "school": "School of Physical Sciences", + "title": "Advanced Data Acquisition and Analysis", + "course_level": "Graduate/Professional Only (200+)", + + "description": "Introduces students to a variety of practical laboratory techniques, including lock-in, boxcar, coincidence counting, noise filtering, PID control, properties of common transducers, computer interfacing to instruments, vacuum technology, laboratory safety, basic mechanical design, and shop skills. Materials fee.", + "image" : "https://learn.g2.com/hubfs/what-is-advanced-analytics.jpg" + }, + { + "id": 7, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Artificial Intelligence Frontiers: Technical, Ethical, and Societal", + "course_level": "Upper Division (100-199)", + + "description": "Explores the frontiers of artificial intelligence and related technologies with a focus on the underlying ethical, legal, and societal challenges and opportunities they create. Encourages critical thinking about these issues.", + "image" : "https://www.insurancejournal.com/app/uploads/2016/01/ethics-580x580.jpg" + }, + { + "id": 8, + + "school": "The Henry Samueli School of Engineering", + "title": "Biomedical Big Data", + "course_level": "Graduate/Professional Only (200+)", + + "description": "Analysis and visualization of large biomedical datasets. Topics covered include cloud computing, learning Structured Query Language (SQL), database normalization and joins, using Google’s BigQuery, using the statistical analysis package R, machine learning algorithms, application of machine learning for classification problems.", + "image" : "https://prod-discovery.edx-cdn.org/media/course/image/63f8ec13-8c6b-4c70-b380-3f95e56a21f6-d8de3c31749c.small.jpg" + }, + { + "id": 9, + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Network Security", + "course_level": "Graduate/Professional Only (200+)", + + "description": "Introduction to network security, including network threats and attacks, as well as defenses against such attacks. Topics include network infrastructure security, mobile and Wi-Fi security, spam, phishing, firewalls, anonymity, secure email, secure and private cloud computing, and web security.", + "image" : "https://images.anytask.com/resources/user/07b908f2cd365eec/task/1604585232973_secure.png"}, + { + "id":10 , + + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Realistic Image Synthesis", + "course_level": "Graduate/Professional Only (200+)", + + "description": "Provides an in-depth overview on a core sub-field of computer graphics. Graduate students who take this course are better prepared for conducting research on the related topics in computer graphics, vision, and scientific computing.", + "image" : "https://pbs.twimg.com/media/DVZtj_GUQAAv6mp.jpg" + }, + { + "id": 11, + + "school": "The Henry Samueli School of Engineering", + "title": "Introduction to Programming", + "course_level": "Lower Division (1-99)", + "description": "An introduction to computers and programming. Python programming syntax/style, types. Numbers and sequences. Control flow. I/O and errors/exceptions. Function calling, parameter passing, formal arguments, return values. Variable scoping. Programming laboratory.", + "image" : "https://www.tuni.fi/sites/default/files/styles/base_landscape_lg/public/media/image/jop_pow_koodaus.png?itok=MbIrLPrF" + }, + { + "id": 12, + "school": "Donald Bren School of Information and Computer Sciences", + "title": "Project in Databases and Web Applications", + "course_level": "Upper Division (100-199)", + + "description": "Introduces students to advanced database technologies and Web applications. Topics include database connectivity (ODBC/JDBC), extending databases using stored procedures, database administration, Web servers, Web programming languages (Java servlets, XML, Ajax, and mobile platforms).", + "image" : "https://www.midaswebtech.com/wp-content/themes/midas_it/images/web-development.gif" + } + +] \ No newline at end of file diff --git a/src/main/resources/templates/courses.html b/src/main/resources/templates/courses.html new file mode 100644 index 0000000..8f6dba7 --- /dev/null +++ b/src/main/resources/templates/courses.html @@ -0,0 +1,26 @@ + + + + + Courses Page + + + + + + + + + +
+ +
+ +
+ + image +
+ + + + \ No newline at end of file diff --git a/src/main/resources/templates/quiz.html b/src/main/resources/templates/quiz.html new file mode 100644 index 0000000..5e39f28 --- /dev/null +++ b/src/main/resources/templates/quiz.html @@ -0,0 +1,32 @@ + + + + + Quiz Page + + + + + + + + + +
+ + + + + + + + + + + +
+ + + + + \ No newline at end of file From c6f72ff664382e2ad479fec893781c251b6ce80d Mon Sep 17 00:00:00 2001 From: abdelqader-alomari Date: Sun, 24 Oct 2021 23:42:30 +0300 Subject: [PATCH 08/10] add controller and profile for each user by id, all users, follow and feed initially done --- .../com/example/init/controllers/User.java | 14 ++++++- .../java/com/example/init/models/Coders.java | 12 +++--- .../init/repositories/CodersRepository.java | 2 +- src/main/resources/application.properties | 2 +- src/main/resources/templates/feed.html | 40 ++++-------------- src/main/resources/templates/home.html | 8 ---- src/main/resources/templates/user.html | 42 +++++++++++++++++++ src/main/resources/templates/users.html | 11 ++++- 8 files changed, 80 insertions(+), 51 deletions(-) create mode 100644 src/main/resources/templates/user.html diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index 17088ca..e42018b 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; @@ -77,6 +78,15 @@ public RedirectView addPost(Principal principle, String body) { return new RedirectView("/profile"); } + @GetMapping("/user") + public String profile(@RequestParam long id, Model model, Principal principal) { + Coders user = codersRepository.findById(id).get(); + model.addAttribute("username", user.getUsername()); + model.addAttribute("userProfile", user); + model.addAttribute("logged", ((UsernamePasswordAuthenticationToken) principal).getPrincipal()); + return "user"; + } + @GetMapping("/users") public String getUsers(Model model, Principal principal) { List users = codersRepository.findAll(); @@ -87,7 +97,7 @@ public String getUsers(Model model, Principal principal) { } @PostMapping("/follow") - public RedirectView followUser(Coders user, @RequestParam Long id) { + public RedirectView followUser(@AuthenticationPrincipal Coders user, @RequestParam Long id) { Coders feed = codersRepository.findByUsername(user.getUsername()); Coders follow = codersRepository.findById(id).get(); feed.getFollowers().add(follow); @@ -96,7 +106,7 @@ public RedirectView followUser(Coders user, @RequestParam Long id) { } @GetMapping("/feed") - public String getUsersInfo(Coders user, Model model) { + public String getUsersInfo(@AuthenticationPrincipal Coders user, Model model) { Coders feed = codersRepository.findByUsername(user.getUsername()); List following = feed.getFollowers(); model.addAttribute("followers", following); diff --git a/src/main/java/com/example/init/models/Coders.java b/src/main/java/com/example/init/models/Coders.java index 075ee70..467c8b1 100644 --- a/src/main/java/com/example/init/models/Coders.java +++ b/src/main/java/com/example/init/models/Coders.java @@ -29,10 +29,10 @@ public class Coders implements UserDetails { @OneToMany(mappedBy = "applicationUser", fetch = FetchType.EAGER) private List posts; - @ManyToMany(cascade = { CascadeType.ALL }) + @ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER) @JoinTable(name = "follower_follower", joinColumns = @JoinColumn(name = "from_id"), inverseJoinColumns = @JoinColumn(name = "to_id")) List followers = new ArrayList<>(); - @ManyToMany(mappedBy = "followers") + @ManyToMany(mappedBy = "followers", fetch = FetchType.EAGER) List following = new ArrayList<>(); public Coders() { @@ -51,22 +51,22 @@ public Coders(String email, String username, String password, String firstName, @Override public boolean isAccountNonExpired() { - return false; + return true; } @Override public boolean isAccountNonLocked() { - return false; + return true; } @Override public boolean isCredentialsNonExpired() { - return false; + return true; } @Override public boolean isEnabled() { - return false; + return true; } public void setUsername(String username) { diff --git a/src/main/java/com/example/init/repositories/CodersRepository.java b/src/main/java/com/example/init/repositories/CodersRepository.java index 6673df8..dde97d9 100644 --- a/src/main/java/com/example/init/repositories/CodersRepository.java +++ b/src/main/java/com/example/init/repositories/CodersRepository.java @@ -8,5 +8,5 @@ public interface CodersRepository extends JpaRepository { public Coders findByUsername(String username); - public Coders findUserById(Long id); + // public Coders findUserById(Long id); } \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 532a27b..06316f2 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,4 +4,4 @@ spring.datasource.username=abdelqader spring.datasource.password=0000 spring.jpa.database=postgresql spring.jpa.generate-ddl=true -spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file +spring.jpa.hibernate.ddl-auto=update \ No newline at end of file diff --git a/src/main/resources/templates/feed.html b/src/main/resources/templates/feed.html index 636fe49..95ea331 100644 --- a/src/main/resources/templates/feed.html +++ b/src/main/resources/templates/feed.html @@ -6,48 +6,26 @@ > - Feed page
- -

Feed

+

Feed Posts

- Card image cap
Username:
-

- Profile

-
Posts:
-
    -
  • -
+

+

+
Posts:
+
    +
  • +
diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html index 6b510d5..033f5e1 100644 --- a/src/main/resources/templates/home.html +++ b/src/main/resources/templates/home.html @@ -8,13 +8,5 @@

Hello World

- diff --git a/src/main/resources/templates/user.html b/src/main/resources/templates/user.html new file mode 100644 index 0000000..eb882c8 --- /dev/null +++ b/src/main/resources/templates/user.html @@ -0,0 +1,42 @@ + + + + + user profile + + + +
+ ProfilePicture +
+ +

+

+

+

+
+ +
+
+ + Posts + +
+
+
+

+

+
+
+
+ + diff --git a/src/main/resources/templates/users.html b/src/main/resources/templates/users.html index e811660..1c28abc 100644 --- a/src/main/resources/templates/users.html +++ b/src/main/resources/templates/users.html @@ -31,8 +31,15 @@

People You May Know

  • -
    - + + +
    From 119efcbf9c40d72236e2291cd702c7d9a3b14484 Mon Sep 17 00:00:00 2001 From: Jamal Eldeen Wari Date: Sun, 24 Oct 2021 23:55:42 +0300 Subject: [PATCH 09/10] adding some stuff to github --- build.gradle | 1 + .../init/controllers/QuizController.java | 71 ++++++++++++++++--- .../java/com/example/init/models/Quiz.java | 27 ++++++- .../java/com/example/init/models/QuizDTO.java | 70 ++++++++++++++++++ src/main/resources/application.properties | 6 +- src/main/resources/templates/quiz.html | 23 +++--- 6 files changed, 176 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/example/init/models/QuizDTO.java diff --git a/build.gradle b/build.gradle index 8d03cce..0e73eff 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,7 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' implementation 'com.google.code.gson:gson:2.8.8' + implementation 'com.googlecode.json-simple:json-simple:1.1.1' } test { diff --git a/src/main/java/com/example/init/controllers/QuizController.java b/src/main/java/com/example/init/controllers/QuizController.java index 794de6b..b161504 100644 --- a/src/main/java/com/example/init/controllers/QuizController.java +++ b/src/main/java/com/example/init/controllers/QuizController.java @@ -1,21 +1,24 @@ package com.example.init.controllers; import com.example.init.models.Quiz; +import com.example.init.models.QuizDTO; import com.google.gson.Gson; +import com.google.gson.JsonElement; +import org.json.simple.JSONObject; +import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; +import java.io.*; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; -import java.util.ArrayList; -import java.util.List; +import java.util.*; @Controller public class QuizController { @@ -24,18 +27,70 @@ public class QuizController { @GetMapping("/quiz") - public String getQuiz(Model model) throws IOException { + public String getQuiz(Model model) throws IOException, ParseException { Gson gson = new Gson(); String urlApi = "https://quizapi.io/api/v1/questions?apiKey=phkL2Z69NDCrImLlfnLoElQkoF3StoJlQrAeKvkf&limit=10&css"; HttpURLConnection connection = (HttpURLConnection) new URL(urlApi).openConnection(); InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); +// String data = bufferedReader.readLine(); String data = bufferedReader.readLine(); Type jsonCasting = new TypeToken>(){}.getType(); List jsonList = gson.fromJson(data,jsonCasting); + List fromJson = gson.fromJson(data,jsonCasting); + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("answers" , data); + model.addAttribute("answers" , jsonObject); + +// List jsonMap = Arrays.asList(gson.fromJson(data,Quiz[].class)); + + +// JSONParser jsonParser = new JSONParser(); +// Object ob = jsonParser.parse(data); +// JSONObject jsonObject = (JSONObject) ob{0}; +// String answers = (String) jsonObject.get("answers"); +// +// +// List jsonAnswers = Arrays.asList(gson.fromJson(answers,QuizDTO[].class)); + model.addAttribute("quiz",jsonList); -// model.addAttribute("answers",jsonList); + System.out.println(jsonList.toString()); + QuizDTO quizDTO = new QuizDTO(); +// System.out.println(data+" "+ jsonMap); +// List jsonMap = Arrays.asList(gson.fromJson(data,QuizDTO[].class)); +// JSONObject jsonObject = new JSONObject(); +// +// Map ans = new LinkedHashMap(6); +// ans.put("answer_a",quizDTO.getAnswer_a()); +// ans.put("answer_b",quizDTO.getAnswer_b()); +// ans.put("answer_c",quizDTO.getAnswer_c()); +// ans.put("answer_d",quizDTO.getAnswer_d()); +// ans.put("answer_e",quizDTO.getAnswer_e()); +// ans.put("answer_f",quizDTO.getAnswer_f()); +// jsonObject.toJSONString(jsonList) +// jsonObject.put("answers",ans); +// model.addAttribute("answers",jsonAnswers); bufferedReader.close(); return "quiz"; } +// @GetMapping("/quizAns") +// public String fetchAns(Model model){ +// QuizDTO quizDTO = new QuizDTO(); +// JsonObject jsonObject = new JsonObject(); +// Map ans = new LinkedHashMap(6); +// ans.put("answer_a",quizDTO.getAnswer_a()); +// ans.put("answer_b",quizDTO.getAnswer_b()); +// ans.put("answer_c",quizDTO.getAnswer_c()); +// ans.put("answer_d",quizDTO.getAnswer_d()); +// ans.put("answer_e",quizDTO.getAnswer_e()); +// ans.put("answer_f",quizDTO.getAnswer_f()); +// jsonObject.add("answers", (JsonElement) ans); +// model.addAttribute("answers",jsonObject); +// return "quiz"; +// +// } + + } diff --git a/src/main/java/com/example/init/models/Quiz.java b/src/main/java/com/example/init/models/Quiz.java index bf4692f..8fc2954 100644 --- a/src/main/java/com/example/init/models/Quiz.java +++ b/src/main/java/com/example/init/models/Quiz.java @@ -8,7 +8,9 @@ import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; @Entity public class Quiz { @@ -17,14 +19,37 @@ public class Quiz { @Column(name = "id", nullable = false) private Long id; +// public String answers; public String question; // public String answers; + public String answer_a; + public String answer_b; + public String answer_c; + public String answer_d; + public String answer_e; + public String answer_f; + +// public String getAnswers() { +// return answers; +// } +// +// public void setAnswers(String answers) { +// this.answers = answers; +// } - public Quiz(String question) { + public Quiz(String question, String answer_a, String answer_b, String answer_c, String answer_d, String answer_e, String answer_f) { this.question = question; // this.answers = answers; + this.answer_a = answer_a; + this.answer_b = answer_b; + this.answer_c = answer_c; + this.answer_d = answer_d; + this.answer_e = answer_e; + this.answer_f = answer_f; } + + public Long getId() { return id; } diff --git a/src/main/java/com/example/init/models/QuizDTO.java b/src/main/java/com/example/init/models/QuizDTO.java new file mode 100644 index 0000000..041cbcb --- /dev/null +++ b/src/main/java/com/example/init/models/QuizDTO.java @@ -0,0 +1,70 @@ +package com.example.init.models; + +public class QuizDTO { + private String answer_a; + private String answer_b; + private String answer_c; + private String answer_d; + private String answer_e; + private String answer_f; + + public QuizDTO() { + } + + public QuizDTO(String answer_a, String answer_b, String answer_c, String answer_d, String answer_e, String answer_f) { + this.answer_a = answer_a; + this.answer_b = answer_b; + this.answer_c = answer_c; + this.answer_d = answer_d; + this.answer_e = answer_e; + this.answer_f = answer_f; + } + + public String getAnswer_a() { + return answer_a; + } + + public void setAnswer_a(String answer_a) { + this.answer_a = answer_a; + } + + public String getAnswer_b() { + return answer_b; + } + + public void setAnswer_b(String answer_b) { + this.answer_b = answer_b; + } + + public String getAnswer_c() { + return answer_c; + } + + public void setAnswer_c(String answer_c) { + this.answer_c = answer_c; + } + + public String getAnswer_d() { + return answer_d; + } + + public void setAnswer_d(String answer_d) { + this.answer_d = answer_d; + } + + public String getAnswer_e() { + return answer_e; + } + + public void setAnswer_e(String answer_e) { + this.answer_e = answer_e; + } + + public String getAnswer_f() { + return answer_f; + } + + public void setAnswer_f(String answer_f) { + this.answer_f = answer_f; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ae3973a..67434da 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -2,9 +2,9 @@ spring.datasource.hikari.connectionTimeout=20000 spring.datasource.hikari.maximumPoolSize=5 spring.sql.init.platform=postgres -spring.datasource.url=jdbc:postgresql://localhost:5432/init -spring.datasource.username=mohammad -spring.datasource.password=1234 +spring.datasource.url=jdbc:postgresql://localhost:5432/coders +spring.datasource.username=postgres +spring.datasource.password=12345 spring.jpa.hibernate.ddl-auto=update spring.datasource.initialization-mode=always diff --git a/src/main/resources/templates/quiz.html b/src/main/resources/templates/quiz.html index 5e39f28..5a67438 100644 --- a/src/main/resources/templates/quiz.html +++ b/src/main/resources/templates/quiz.html @@ -12,18 +12,21 @@ + +
    - - - - - - - - + + + + + + + + + - - + +
    From 98be21c201f3245cdb4b6caea60a71b6ff574e20 Mon Sep 17 00:00:00 2001 From: nawal-ahmad Date: Tue, 26 Oct 2021 01:24:44 +0300 Subject: [PATCH 10/10] new branch working properly with edit, delete and a basic navbar --- .../com/example/init/InitApplication.java | 2 - .../com/example/init/controllers/User.java | 34 +++++++++++++++++ src/main/resources/application.properties | 6 +-- src/main/resources/templates/header.html | 38 +++++++++++++++++++ src/main/resources/templates/profile.html | 5 ++- src/main/resources/templates/updateForm.html | 19 ++++++++++ 6 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 src/main/resources/templates/header.html create mode 100644 src/main/resources/templates/updateForm.html diff --git a/src/main/java/com/example/init/InitApplication.java b/src/main/java/com/example/init/InitApplication.java index 400e74e..06ed241 100644 --- a/src/main/java/com/example/init/InitApplication.java +++ b/src/main/java/com/example/init/InitApplication.java @@ -8,7 +8,5 @@ public class InitApplication { public static void main(String[] args) { SpringApplication.run(InitApplication.class, args); - } - } diff --git a/src/main/java/com/example/init/controllers/User.java b/src/main/java/com/example/init/controllers/User.java index 80f4938..aa1c7c4 100644 --- a/src/main/java/com/example/init/controllers/User.java +++ b/src/main/java/com/example/init/controllers/User.java @@ -15,6 +15,7 @@ import org.springframework.ui.Model; 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.RequestParam; import org.springframework.web.servlet.view.RedirectView; @@ -23,6 +24,9 @@ import java.util.ArrayList; import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.transaction.Transactional; + @Controller public class User { @@ -78,6 +82,36 @@ public RedirectView addPost(Principal principle, String body) { return new RedirectView("/profile"); } + + @Transactional + @GetMapping("/delete/{id}") + public RedirectView deleteUserPost(@PathVariable String id, HttpServletRequest request, Principal principal, Model model) { + Post post = contentRepository.findById(Long.parseLong(id)).orElseThrow(); + String username = (String) request.getSession().getAttribute("username"); + Coders user = codersRepository.findByUsername(principal.getName()); + model.addAttribute("username", principal.getName()); + model.addAttribute("userProfile", user); + contentRepository.delete(post); + return new RedirectView("/profile"); + } + + + @GetMapping("/edit/{id}") + public String showUpdateForm(@PathVariable("id") long id, Model model) { + Post post = contentRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); + model.addAttribute("post", post); + return "updateForm"; + } + + @PostMapping("/update/{id}") + public RedirectView updateUser(@PathVariable("id") long id, Post post) { + Post updatedPost = contentRepository.findById(id).orElseThrow(); + updatedPost.setBody(post.getBody()); + contentRepository.save(updatedPost); + return new RedirectView("/profile"); + } + @GetMapping("/user") public String profile(@RequestParam long id, Model model, Principal principal) { Coders user = codersRepository.findById(id).get(); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index f03a366..6a4905d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,7 @@ spring.sql.init.platform=postgres -spring.datasource.url=jdbc:postgresql://localhost:5432/coders -spring.datasource.username=abdelqader -spring.datasource.password=0000 +spring.datasource.url=jdbc:postgresql://localhost:5433/init +spring.datasource.username=postgres +spring.datasource.password=1234 spring.jpa.database=postgresql spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update diff --git a/src/main/resources/templates/header.html b/src/main/resources/templates/header.html new file mode 100644 index 0000000..7649d56 --- /dev/null +++ b/src/main/resources/templates/header.html @@ -0,0 +1,38 @@ + + + + + Title + + +
    + +
    + + diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html index 48d79a4..20cfc3f 100644 --- a/src/main/resources/templates/profile.html +++ b/src/main/resources/templates/profile.html @@ -39,7 +39,10 @@

    -

    +

    + Delete + Edit +
    diff --git a/src/main/resources/templates/updateForm.html b/src/main/resources/templates/updateForm.html new file mode 100644 index 0000000..d400ae7 --- /dev/null +++ b/src/main/resources/templates/updateForm.html @@ -0,0 +1,19 @@ + + + + + Update Form + + +
    + +
    + + + +
    + +