#1 TEST THIS SHIT

已合併
AllisonZiegler 8 年之前 將 6 次代碼提交從 dallison合併至 master

+ 40
- 8
pom.xml 查看文件

34
             <artifactId>spring-boot-starter-web</artifactId>
34
             <artifactId>spring-boot-starter-web</artifactId>
35
         </dependency>
35
         </dependency>
36
 
36
 
37
-        <dependency>
38
-            <groupId>mysql</groupId>
39
-            <artifactId>mysql-connector-java</artifactId>
40
-            <scope>runtime</scope>
41
-        </dependency>
42
-
43
         <!--<dependency>-->
37
         <!--<dependency>-->
44
-            <!--<groupId>com.h2database</groupId>-->
45
-            <!--<artifactId>h2</artifactId>-->
38
+            <!--<groupId>mysql</groupId>-->
39
+            <!--<artifactId>mysql-connector-java</artifactId>-->
46
             <!--<scope>runtime</scope>-->
40
             <!--<scope>runtime</scope>-->
47
         <!--</dependency>-->
41
         <!--</dependency>-->
48
         <dependency>
42
         <dependency>
49
             <groupId>org.springframework.boot</groupId>
43
             <groupId>org.springframework.boot</groupId>
44
+            <artifactId>spring-boot-starter-websocket</artifactId>
45
+        </dependency>
46
+        <dependency>
47
+            <groupId>org.springframework.boot</groupId>
48
+            <artifactId>spring-boot-starter-data-rest</artifactId>
49
+        </dependency>
50
+        <dependency>
51
+            <groupId>com.h2database</groupId>
52
+            <artifactId>h2</artifactId>
53
+            <scope>runtime</scope>
54
+        </dependency>
55
+        <dependency>
56
+            <groupId>org.springframework.boot</groupId>
50
             <artifactId>spring-boot-starter-test</artifactId>
57
             <artifactId>spring-boot-starter-test</artifactId>
51
             <scope>test</scope>
58
             <scope>test</scope>
52
         </dependency>
59
         </dependency>
55
             <artifactId>spring-restdocs-mockmvc</artifactId>
62
             <artifactId>spring-restdocs-mockmvc</artifactId>
56
             <scope>test</scope>
63
             <scope>test</scope>
57
         </dependency>
64
         </dependency>
65
+
66
+        <dependency>
67
+            <groupId>org.webjars</groupId>
68
+            <artifactId>webjars-locator-core</artifactId>
69
+        </dependency>
70
+        <dependency>
71
+            <groupId>org.webjars</groupId>
72
+            <artifactId>sockjs-client</artifactId>
73
+            <version>1.0.2</version>
74
+        </dependency>
75
+        <dependency>
76
+            <groupId>org.webjars</groupId>
77
+            <artifactId>stomp-websocket</artifactId>
78
+            <version>2.3.3</version>
79
+        </dependency>
80
+        <dependency>
81
+            <groupId>org.webjars</groupId>
82
+            <artifactId>bootstrap</artifactId>
83
+            <version>3.3.7</version>
84
+        </dependency>
85
+        <dependency>
86
+            <groupId>org.webjars</groupId>
87
+            <artifactId>jquery</artifactId>
88
+            <version>3.1.0</version>
89
+        </dependency>
58
     </dependencies>
90
     </dependencies>
59
 
91
 
60
     <build>
92
     <build>

+ 26
- 0
src/main/java/com/ziplinegreen/vault/Config/WebSocketConfig.java 查看文件

1
+package com.ziplinegreen.vault.Config;
2
+
3
+
4
+import org.springframework.context.annotation.ComponentScan;
5
+import org.springframework.context.annotation.Configuration;
6
+import org.springframework.messaging.simp.config.MessageBrokerRegistry;
7
+import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
8
+import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
9
+import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
10
+
11
+@Configuration
12
+@EnableWebSocketMessageBroker
13
+@ComponentScan(basePackages = "com.ziplinegreen.vault")
14
+public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
15
+
16
+    @Override
17
+    public void configureMessageBroker(MessageBrokerRegistry config) {
18
+        config.enableSimpleBroker("/topic");
19
+        config.setApplicationDestinationPrefixes("/app"); //where the frontend sends things
20
+    }
21
+
22
+    @Override
23
+    public void registerStompEndpoints(StompEndpointRegistry registry) {
24
+        registry.addEndpoint("/vault-socket").withSockJS();
25
+    }
26
+}

+ 79
- 37
src/main/java/com/ziplinegreen/vault/Controller/PostController.java 查看文件

1
 package com.ziplinegreen.vault.Controller;
1
 package com.ziplinegreen.vault.Controller;
2
 
2
 
3
+import com.sun.deploy.net.HttpResponse;
3
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4
 import com.ziplinegreen.vault.Model.Post;
5
 import com.ziplinegreen.vault.Model.Post;
6
+import com.ziplinegreen.vault.Model.User;
5
 import com.ziplinegreen.vault.Repository.PostRepository;
7
 import com.ziplinegreen.vault.Repository.PostRepository;
6
 import com.ziplinegreen.vault.Repository.UserRepository;
8
 import com.ziplinegreen.vault.Repository.UserRepository;
9
+import com.ziplinegreen.vault.Service.PostService;
10
+import com.ziplinegreen.vault.Service.UserService;
7
 import org.springframework.beans.factory.annotation.Autowired;
11
 import org.springframework.beans.factory.annotation.Autowired;
8
 import org.springframework.data.domain.Page;
12
 import org.springframework.data.domain.Page;
9
 import org.springframework.data.domain.Pageable;
13
 import org.springframework.data.domain.Pageable;
14
+import org.springframework.http.HttpStatus;
10
 import org.springframework.http.ResponseEntity;
15
 import org.springframework.http.ResponseEntity;
16
+import org.springframework.messaging.handler.annotation.DestinationVariable;
17
+import org.springframework.messaging.handler.annotation.MessageMapping;
18
+import org.springframework.messaging.handler.annotation.SendTo;
19
+import org.springframework.stereotype.Controller;
11
 import org.springframework.web.bind.annotation.*;
20
 import org.springframework.web.bind.annotation.*;
12
 
21
 
13
 import javax.validation.Valid;
22
 import javax.validation.Valid;
23
+import java.util.Set;
14
 
24
 
15
-
25
+@Controller
16
 public class PostController {
26
 public class PostController {
17
 
27
 
18
     @Autowired
28
     @Autowired
19
-    private PostRepository postRepository;
29
+    private PostService postService;
30
+    @Autowired
31
+    private UserController userController;
20
 
32
 
21
     @Autowired
33
     @Autowired
22
-    private UserRepository userRepository;
34
+    private PostRepository repository;
23
 
35
 
24
-    @GetMapping("/users/{userId}/posts")
25
-    public Page<Post> getAllPostsByUserId(@PathVariable(value = "userId") Long userId,
26
-                                             Pageable pageable) {
27
-        return postRepository.findByUserId(userId, pageable);
36
+    @Autowired
37
+    public PostController(PostService postService) {
38
+        this.postService = postService;
28
     }
39
     }
29
 
40
 
30
-    @PostMapping("/users/{userId}/posts")
31
-    public Post createPost(@PathVariable (value = "userId") Long userId,
32
-                                 @Valid @RequestBody Post post) {
33
-        return userRepository.findById(userId).map(user -> {
34
-            post.setUser(user);
35
-            return postRepository.save(post);
36
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
41
+//    @PostMapping("/posts/{userId}")
42
+//    public ResponseEntity createPost(@PathVariable Long userId, @RequestBody Post post) {
43
+//        //userController.updatePosts(userId,post);
44
+//        return new ResponseEntity(userController.updatePosts(userId, post), HttpStatus.OK);
45
+//
46
+//    }
47
+
48
+    @MessageMapping("/posts/{userId}")
49
+    @SendTo("/topic/posts")
50
+    public Post createPost(@DestinationVariable("userId") Long userId, @RequestBody Post post) {
51
+    //public Post createPost(@RequestBody Post post) {
52
+        System.out.println(post.getMessage());
53
+        post.setUserName(userController.getUserById(userId).getBody().getUsername());
54
+        //return userController.updatePosts(userId,post);
55
+        return repository.save(post);
56
+        //return post;
57
+        //return new ResponseEntity(userController.updatePosts(userId, post), HttpStatus.OK);
58
+
37
     }
59
     }
38
 
60
 
39
-    @PutMapping("/users/{userId}/posts/{postId}")
40
-    public Post updateComment(@PathVariable (value = "userId") Long userId,
41
-                                 @PathVariable (value = "postId") Long postId,
42
-                                 @Valid @RequestBody Post postRequest) {
43
-        if(!userRepository.existsById(userId)) {
44
-            throw new ResourceNotFoundException("UserId " + userId + " not found");
45
-        }
46
-
47
-        return postRepository.findById(postId).map(post -> {
48
-            post.setMessage(postRequest.getMessage());
49
-            return postRepository.save(post);
50
-        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + "not found"));
61
+    @GetMapping("/posts/all")
62
+    public Iterable<Post> getAllPosts() {
63
+        return repository.findAll();
51
     }
64
     }
52
 
65
 
53
-    @DeleteMapping("/posts/{postId}/comments/{commentId}")
54
-    public ResponseEntity<?> deleteComment(@PathVariable (value = "userId") Long userId,
55
-                                           @PathVariable (value = "postId") Long postId) {
56
-        if(!userRepository.existsById(userId)) {
57
-            throw new ResourceNotFoundException("UserId " + userId + " not found");
58
-        }
59
-
60
-        return postRepository.findById(postId).map(post -> {
61
-            postRepository.delete(post);
62
-            return ResponseEntity.ok().build();
63
-        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
66
+
67
+
68
+    @GetMapping("/posts/{userId}")
69
+    //@SendTo("/topic/posts")
70
+    public ResponseEntity<Iterable<Post>> getAllPostsByUserId(@PathVariable Long userId) {
71
+        return postService.findByUserId(userId);
64
     }
72
     }
73
+
74
+//    @PutMapping("/users/{userId/posts")
75
+//    public ResponseEntity<Post> updatePost(@PathVariable Long userId, @RequestBody Post post){
76
+//        return postService.updatePost(userId, post);
77
+//    }
78
+
79
+
80
+
81
+//    @PutMapping("/users/{userId}/posts/{postId}")
82
+//    public Post updateComment(@PathVariable (value = "userId") Long userId,
83
+//                                 @PathVariable (value = "postId") Long postId,
84
+//                                 @Valid @RequestBody Post postRequest) {
85
+//        if(!userRepository.existsById(userId)) {
86
+//            throw new ResourceNotFoundException("UserId " + userId + " not found");
87
+//        }
88
+//
89
+//        return postRepository.findById(postId).map(post -> {
90
+//            post.setMessage(postRequest.getMessage());
91
+//            return postRepository.save(post);
92
+//        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + "not found"));
93
+//    }
94
+//
95
+//    @DeleteMapping("/posts/{postId}/comments/{commentId}")
96
+//    public ResponseEntity<?> deleteComment(@PathVariable (value = "userId") Long userId,
97
+//                                           @PathVariable (value = "postId") Long postId) {
98
+//        if(!userRepository.existsById(userId)) {
99
+//            throw new ResourceNotFoundException("UserId " + userId + " not found");
100
+//        }
101
+//
102
+//        return postRepository.findById(postId).map(post -> {
103
+//            postRepository.delete(post);
104
+//            return ResponseEntity.ok().build();
105
+//        }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
106
+//    }
65
 }
107
 }

+ 27
- 17
src/main/java/com/ziplinegreen/vault/Controller/UserController.java 查看文件

1
 package com.ziplinegreen.vault.Controller;
1
 package com.ziplinegreen.vault.Controller;
2
 
2
 
3
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
3
 import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
4
+import com.ziplinegreen.vault.Model.Post;
4
 import com.ziplinegreen.vault.Model.User;
5
 import com.ziplinegreen.vault.Model.User;
5
 import com.ziplinegreen.vault.Repository.UserRepository;
6
 import com.ziplinegreen.vault.Repository.UserRepository;
7
+import com.ziplinegreen.vault.Service.UserService;
6
 import org.springframework.beans.factory.annotation.Autowired;
8
 import org.springframework.beans.factory.annotation.Autowired;
7
 import org.springframework.data.domain.Page;
9
 import org.springframework.data.domain.Page;
8
 import org.springframework.data.domain.Pageable;
10
 import org.springframework.data.domain.Pageable;
11
+import org.springframework.http.HttpStatus;
9
 import org.springframework.http.ResponseEntity;
12
 import org.springframework.http.ResponseEntity;
10
 import org.springframework.web.bind.annotation.*;
13
 import org.springframework.web.bind.annotation.*;
11
 
14
 
12
 import javax.validation.Valid;
15
 import javax.validation.Valid;
16
+import java.util.List;
17
+import java.util.Set;
13
 
18
 
14
 @RestController
19
 @RestController
15
 public class UserController {
20
 public class UserController {
16
 
21
 
17
-    @Autowired
18
-    private UserRepository userRepository;
22
+    private UserService userService;
19
 
23
 
20
-    @GetMapping("/users")
21
-    public Page<User> getAllPosts(Pageable pageable) {
22
-        return userRepository.findAll(pageable);
24
+    @Autowired
25
+    public UserController(UserService userService) {
26
+        this.userService = userService;
23
     }
27
     }
24
 
28
 
25
     @PostMapping("/users")
29
     @PostMapping("/users")
26
-    public User createPost(@Valid @RequestBody User user) {
27
-        return userRepository.save(user);
30
+    public ResponseEntity<User> createUser(@RequestBody User user) {
31
+        return userService.createUser(user);
32
+    }
33
+
34
+    @GetMapping("/users/{userId}")
35
+    public ResponseEntity<User> getUserById(@PathVariable Long userId) {
36
+        return userService.findUserById(userId);
28
     }
37
     }
29
 
38
 
30
     @PutMapping("/users/{userId}")
39
     @PutMapping("/users/{userId}")
31
-    public User updatePost(@PathVariable Long userId, @Valid @RequestBody User userRequest) {
32
-        return userRepository.findById(userId).map(user -> {
33
-            user.setUsername(userRequest.getUsername());
34
-            return userRepository.save(user);
35
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
40
+    public ResponseEntity<User> updateUsername(@PathVariable Long userId, @Valid @RequestBody User userRequest) {
41
+        return new ResponseEntity<>(userService.updateUsername(userId,userRequest), HttpStatus.OK);
36
     }
42
     }
37
 
43
 
38
 
44
 
39
     @DeleteMapping("/users/{userId}")
45
     @DeleteMapping("/users/{userId}")
40
-    public ResponseEntity<?> deletePost(@PathVariable Long userId) {
41
-        return userRepository.findById(userId).map(user -> {
42
-            userRepository.delete(user);
43
-            return ResponseEntity.ok().build();
44
-        }).orElseThrow(() -> new ResourceNotFoundException("UserId " + userId + " not found"));
46
+    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
47
+        return userService.deleteUser(userId);
45
     }
48
     }
49
+
50
+    @PutMapping("/users/{userId}/updatepost")
51
+    public ResponseEntity<?> updatePosts(@PathVariable Long userId, @RequestBody Post post){
52
+        return userService.updatePosts(userId, post);
53
+    }
54
+
55
+
46
 }
56
 }

+ 18
- 13
src/main/java/com/ziplinegreen/vault/Model/Post.java 查看文件

13
 public class Post extends AuditModel{
13
 public class Post extends AuditModel{
14
 
14
 
15
     @Id
15
     @Id
16
-    @GeneratedValue
16
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
17
     private Long Id;
17
     private Long Id;
18
 
18
 
19
     @NotNull
19
     @NotNull
20
     @Lob
20
     @Lob
21
     private String message;
21
     private String message;
22
-
23
-    @ManyToOne(fetch = FetchType.LAZY, optional = false)
24
-    @JoinColumn(name = "user_id", nullable = false)
25
     @OnDelete(action = OnDeleteAction.CASCADE)
22
     @OnDelete(action = OnDeleteAction.CASCADE)
26
     @JsonIgnore
23
     @JsonIgnore
27
-    private User user;
24
+    private Long userId;
25
+    private String userName;
28
 
26
 
29
-    public Long getId() {
30
-        return Id;
27
+    public Post(){
28
+    }
29
+    public Post(@NotNull String message, Long userId, String userName) {
30
+        this.message = message;
31
+        this.userId = userId;
32
+        this.userName = userName;
31
     }
33
     }
32
 
34
 
33
-    public void setId(Long id) {
34
-        Id = id;
35
+    public Long getId() {
36
+        return Id;
35
     }
37
     }
36
 
38
 
37
     public String getMessage() {
39
     public String getMessage() {
42
         this.message = message;
44
         this.message = message;
43
     }
45
     }
44
 
46
 
45
-    public User getUser() {
46
-        return user;
47
+    public Long getUserId() {
48
+        return userId;
47
     }
49
     }
48
 
50
 
49
-    public void setUser(User user) {
50
-        this.user = user;
51
+    public String getUserName() { return userName; }
52
+
53
+    public void setUserName(String userName) {
54
+        this.userName = userName;
51
     }
55
     }
56
+
52
 }
57
 }

+ 52
- 6
src/main/java/com/ziplinegreen/vault/Model/User.java 查看文件

1
 package com.ziplinegreen.vault.Model;
1
 package com.ziplinegreen.vault.Model;
2
 
2
 
3
+import com.fasterxml.jackson.annotation.JsonIgnore;
4
+import org.hibernate.annotations.OnDelete;
5
+import org.hibernate.annotations.OnDeleteAction;
6
+
3
 import javax.persistence.*;
7
 import javax.persistence.*;
4
 import javax.validation.constraints.NotNull;
8
 import javax.validation.constraints.NotNull;
9
+import java.util.ArrayList;
10
+import java.util.List;
5
 
11
 
6
 @Entity
12
 @Entity
7
 @Table(name = "user")
13
 @Table(name = "user")
8
 public class User extends AuditModel{
14
 public class User extends AuditModel{
9
     @Id
15
     @Id
10
-    @GeneratedValue
16
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
11
     private Long id;
17
     private Long id;
12
-
13
-//    @NotNull
14
-    @Column(name ="USER_USERNAME")
18
+    @NotNull
15
     private String username;
19
     private String username;
20
+    private String email;
21
+    private String password;
22
+    @OneToMany(fetch = FetchType.LAZY,
23
+            cascade= {
24
+                CascadeType.PERSIST,
25
+                CascadeType.MERGE
26
+            })
27
+    @JoinTable(name = "user_posts",
28
+            joinColumns = {@JoinColumn(name = "user_id")})
29
+    private List<Post> posts = new ArrayList<>();
30
+
31
+    public List<Post> getPosts() {
32
+        if(posts.size()==0){
33
+            posts = new ArrayList<>();
34
+            return posts;
35
+        }
36
+        return posts;
37
+    }
38
+
39
+    public User(){}
40
+    public User(@NotNull String username, String email, String password) {
41
+        this.username = username;
42
+        this.email = email;
43
+        this.password = password;
44
+    }
45
+
46
+    public void setPosts(List<Post> posts) {
47
+        this.posts = posts;
48
+    }
16
 
49
 
17
     public Long getId() {
50
     public Long getId() {
18
         return id;
51
         return id;
19
     }
52
     }
20
 
53
 
21
-    public void setId(Long id) {
22
-        this.id = id;
54
+    public String getEmail() {
55
+        return email;
56
+    }
57
+
58
+    public void setEmail(String email) {
59
+        this.email = email;
60
+    }
61
+
62
+    public String getPassword() {
63
+        return password;
64
+    }
65
+
66
+    public void setPassword(String password) {
67
+        this.password = password;
23
     }
68
     }
24
 
69
 
25
     public String getUsername() {
70
     public String getUsername() {
29
     public void setUsername(String username) {
74
     public void setUsername(String username) {
30
         this.username = username;
75
         this.username = username;
31
     }
76
     }
77
+
32
 }
78
 }

+ 6
- 2
src/main/java/com/ziplinegreen/vault/Repository/PostRepository.java 查看文件

4
 import org.springframework.data.domain.Page;
4
 import org.springframework.data.domain.Page;
5
 import org.springframework.data.domain.Pageable;
5
 import org.springframework.data.domain.Pageable;
6
 import org.springframework.data.jpa.repository.JpaRepository;
6
 import org.springframework.data.jpa.repository.JpaRepository;
7
+import org.springframework.data.jpa.repository.Query;
8
+import org.springframework.data.repository.query.Param;
9
+import org.springframework.data.rest.core.annotation.RepositoryRestResource;
7
 import org.springframework.stereotype.Repository;
10
 import org.springframework.stereotype.Repository;
8
 
11
 
9
-@Repository
12
+@RepositoryRestResource
10
 public interface PostRepository extends JpaRepository<Post,Long> {
13
 public interface PostRepository extends JpaRepository<Post,Long> {
11
-    Page<Post> findByUserId(Long userId, Pageable pageable);
14
+    //@Query("select postcontent,timestamp from Post where user_id = :userId")
15
+    Iterable<Post> findByUserId(Long userId);
12
 }
16
 }

+ 2
- 1
src/main/java/com/ziplinegreen/vault/Repository/UserRepository.java 查看文件

2
 
2
 
3
 import com.ziplinegreen.vault.Model.User;
3
 import com.ziplinegreen.vault.Model.User;
4
 import org.springframework.data.jpa.repository.JpaRepository;
4
 import org.springframework.data.jpa.repository.JpaRepository;
5
+import org.springframework.data.rest.core.annotation.RepositoryRestResource;
5
 import org.springframework.stereotype.Repository;
6
 import org.springframework.stereotype.Repository;
6
 
7
 
7
-@Repository
8
+@RepositoryRestResource
8
 public interface UserRepository extends JpaRepository<User,Long> {
9
 public interface UserRepository extends JpaRepository<User,Long> {
9
 }
10
 }

+ 40
- 0
src/main/java/com/ziplinegreen/vault/Service/PostService.java 查看文件

1
+package com.ziplinegreen.vault.Service;
2
+
3
+
4
+import com.ziplinegreen.vault.Model.Post;
5
+import com.ziplinegreen.vault.Repository.PostRepository;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.stereotype.Service;
10
+
11
+@Service
12
+public class PostService {
13
+
14
+    @Autowired
15
+    private PostRepository postRepository;
16
+
17
+    @Autowired
18
+    public PostService(PostRepository postRepository) {
19
+        this.postRepository = postRepository;
20
+    }
21
+
22
+    public ResponseEntity<Post> createPost(Post post){
23
+        return new ResponseEntity<>(postRepository.save(post), HttpStatus.CREATED);
24
+    }
25
+
26
+    public ResponseEntity<Post> deletePost(Long id){
27
+        Post post = postRepository.getOne(id);
28
+        postRepository.delete(post);
29
+        return new ResponseEntity<>(HttpStatus.OK);
30
+    }
31
+
32
+    public ResponseEntity<Iterable<Post>> findByUserId(Long userId) {
33
+        return new ResponseEntity<>(postRepository.findByUserId(userId), HttpStatus.OK);
34
+    }
35
+
36
+//    public ResponseEntity<Post> updatePost(Long userId, Post post) {
37
+//
38
+//    }
39
+}
40
+

+ 58
- 0
src/main/java/com/ziplinegreen/vault/Service/UserService.java 查看文件

1
+package com.ziplinegreen.vault.Service;
2
+
3
+import com.ziplinegreen.vault.Controller.PostController;
4
+import com.ziplinegreen.vault.Exception.ResourceNotFoundException;
5
+import com.ziplinegreen.vault.Model.Post;
6
+import com.ziplinegreen.vault.Model.User;
7
+import com.ziplinegreen.vault.Repository.UserRepository;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.http.HttpStatus;
10
+import org.springframework.http.ResponseEntity;
11
+import org.springframework.stereotype.Service;
12
+import org.springframework.web.server.ResponseStatusException;
13
+
14
+import javax.xml.ws.Response;
15
+import java.util.List;
16
+
17
+@Service
18
+public class UserService {
19
+
20
+    @Autowired
21
+    private UserRepository userRepository;
22
+    //private PostController postController;
23
+
24
+    @Autowired
25
+    public UserService(UserRepository userRepository) {
26
+        this.userRepository = userRepository;
27
+    }
28
+
29
+    public ResponseEntity<User> createUser(User user){
30
+        return new ResponseEntity<>(userRepository.save(user), HttpStatus.CREATED);
31
+    }
32
+
33
+    public ResponseEntity<User> findUserById(Long id){
34
+        return new ResponseEntity<>(userRepository.findById(id).get(),HttpStatus.OK);
35
+    }
36
+
37
+    public User updateUsername(Long id, User updatedUser){return userRepository.findById(id).map(user -> {
38
+        user.setUsername(updatedUser.getUsername());
39
+        return userRepository.save(user);
40
+    }).orElseThrow(() -> new ResourceNotFoundException("UserId " + id + " not found"));
41
+    }
42
+
43
+    public ResponseEntity deleteUser(Long id){return userRepository.findById(id).map(user -> {
44
+        userRepository.delete(user);
45
+        return new ResponseEntity(HttpStatus.OK);
46
+    }).orElseThrow(() -> new ResourceNotFoundException("UserId " + id + " not found"));
47
+
48
+    }
49
+
50
+    public ResponseEntity<User> updatePosts(Long userId, Post post) {
51
+        User user = findUserById(userId).getBody();
52
+        List<Post> posts = user.getPosts();
53
+        posts.add(post);
54
+        return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
55
+    }
56
+}
57
+
58
+

+ 20
- 20
src/main/resources/application.properties 查看文件

1
-## H2
2
-#spring.h2.console.enabled=true
3
-#spring.h2.console.path=/h2
4
-#
5
-## Datasource
6
-#spring.datasource.url=jdbc:h2:file:~/test
7
-#spring.datasource.username=sa
8
-#spring.datasource.password=
9
-#spring.datasource.driver-class-name=org.h2.Driver
10
-
11
-
12
-spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
13
-spring.datasource.username=root
14
-spring.datasource.password=Calcifer1650
1
+# H2
2
+spring.h2.console.enabled=true
3
+spring.h2.console.path=/h2
15
 
4
 
16
-# The SQL dialect makes Hibernate generate better SQL for the chosen database
17
-spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
5
+# Datasource
6
+spring.datasource.url=jdbc:h2:file:~/test
7
+spring.datasource.username=sa
8
+spring.datasource.password=
9
+spring.datasource.driver-class-name=org.h2.Driver
18
 
10
 
19
-# Hibernate ddl auto (create, create-drop, validate, update)
20
-spring.jpa.hibernate.ddl-auto = update
21
 
11
 
22
-logging.level.org.hibernate.SQL=DEBUG
23
-logging.level.org.hibernate.type=TRACE
12
+#spring.datasource.url=jdbc:mysql://localhost:3306/zipLine?useSSL=false
13
+#spring.datasource.username=root
14
+#spring.datasource.password=Calcifer1650
15
+#
16
+## The SQL dialect makes Hibernate generate better SQL for the chosen database
17
+#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
18
+#
19
+## Hibernate ddl auto (create, create-drop, validate, update)
20
+#spring.jpa.hibernate.ddl-auto = update
21
+#
22
+#logging.level.org.hibernate.SQL=DEBUG
23
+#logging.level.org.hibernate.type=TRACE

+ 70
- 0
src/main/resources/static/app.js 查看文件

1
+var stompClient = null;
2
+
3
+function setConnected(connected) {
4
+    $('#connect').prop("disabled", connected);
5
+    $('#disconnect').prop("disabled", !connected);
6
+    if (connected) {
7
+        $("#conversation").show();
8
+    }
9
+    else {
10
+        $("#conversation").hide();
11
+    }
12
+    $("#messages").html("");
13
+}
14
+
15
+function connect() {
16
+    var socket = new SockJS('/vault-socket');
17
+    stompClient = Stomp.over(socket);
18
+    stompClient.connect({}, function (frame) {
19
+        setConnected(true);
20
+        console.log('Connected: ' + frame);
21
+        stompClient.subscribe('/topic/posts', function (greeting) {
22
+            showGreeting(JSON.parse(greeting.body).message, JSON.parse(greeting.body).userName);
23
+        });
24
+    });
25
+}
26
+
27
+function disconnect() {
28
+    if (stompClient !== null) {
29
+        stompClient.disconnect();
30
+    }
31
+    setConnected(false);
32
+    console.log("Disconnected");
33
+}
34
+
35
+var userId = 1;
36
+var userPostUrl = "/app/posts/1";
37
+
38
+function user1() {
39
+    $('#user1').prop("disabled", true);
40
+    $('#user2').prop("disabled", false);
41
+    userId = 1;
42
+}
43
+
44
+function user2() {
45
+    $('#user1').prop("disabled", false);
46
+    $('#user2').prop("disabled", true);
47
+    userId = 2;
48
+    userPostUrl = "/app/posts/2";
49
+}
50
+
51
+
52
+function sendName() {
53
+
54
+    stompClient.send(userPostUrl, {}, JSON.stringify({'id': '','message': $("#message").val(),'userId': userId}))
55
+}
56
+
57
+function showGreeting(message, userName) {
58
+    $("#messages").append("<tr><td>" + userName + ": " + message + "</td></tr>");
59
+}
60
+
61
+$(function () {
62
+    $("form").on('submit', function (e) {
63
+        e.preventDefault();
64
+    });
65
+    $( "#connect" ).click(function() { connect(); });
66
+    $( "#disconnect" ).click(function() { disconnect(); });
67
+    $( "#send" ).click(function() { sendName(); });
68
+    $( "#user1" ).click(function() { user1(); });
69
+    $( "#user2" ).click(function() { user2(); })
70
+});

+ 55
- 0
src/main/resources/static/index.html 查看文件

1
+<!DOCTYPE html>
2
+<html>
3
+<head>
4
+    <title>Hello WebSocket</title>
5
+    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
6
+    <!--<link href="/main.css" rel="stylesheet">-->
7
+    <script src="/webjars/jquery/jquery.min.js"></script>
8
+    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
9
+    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
10
+    <script src="./app.js"></script>
11
+</head>
12
+<body>
13
+<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
14
+    enabled. Please enable
15
+    Javascript and reload this page!</h2></noscript>
16
+<div id="main-content" class="container">
17
+    <div class="row">
18
+        <div class="col-md-6">
19
+            <form class="form-inline">
20
+                <div class="form-group">
21
+                    <label for="connect">WebSocket connection:</label>
22
+                    <button id="connect" class="btn btn-default" type="submit">Connect</button>
23
+                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
24
+                    </button>
25
+                    <button id="user1" class="btn btn-default" type="submit" disabled="disabled">User 1</button>
26
+                    <button id="user2" class="btn btn-default" type="submit">User 2</button>
27
+                </div>
28
+            </form>
29
+        </div>
30
+        <div class="col-md-6">
31
+            <form class="form-inline">
32
+                <div class="form-group">
33
+                    <label for="message">Message?</label>
34
+                    <input type="text" id="message" class="form-control" placeholder="What is your message...">
35
+                </div>
36
+                <button id="send" class="btn btn-default" type="submit">Send</button>
37
+            </form>
38
+        </div>
39
+    </div>
40
+    <div class="row">
41
+        <div class="col-md-12">
42
+            <table id="conversation" class="table table-striped">
43
+                <thead>
44
+                <tr>
45
+                    <th>Messages</th>
46
+                </tr>
47
+                </thead>
48
+                <tbody id="messages">
49
+                </tbody>
50
+            </table>
51
+        </div>
52
+    </div>
53
+</div>
54
+</body>
55
+</html>

+ 0
- 0
test.txt 查看文件