Skip to content

Commit

Permalink
refactored the codes.
Browse files Browse the repository at this point in the history
  • Loading branch information
hantsy committed Aug 13, 2017
1 parent cea4cc2 commit 82fe3e7
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 165 deletions.
45 changes: 45 additions & 0 deletions session/src/main/java/com/example/demo/DataInitializr.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

/**
*
* @author hantsy
*/
@Component
@Slf4j
class DataInitializr implements CommandLineRunner {

private final PostRepository posts;

public DataInitializr(PostRepository posts) {
this.posts = posts;
}

@Override
public void run(String[] args) {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap((title) -> this.posts.save(Post.builder().title(title).content("content of " + title).build()))
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}

}
165 changes: 0 additions & 165 deletions session/src/main/java/com/example/demo/DemoApplication.java
Original file line number Diff line number Diff line change
@@ -1,45 +1,16 @@
package com.example.demo;

import java.net.URI;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.MapUserDetailsRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;
import org.springframework.stereotype.Component;
import static org.springframework.web.reactive.function.server.RequestPredicates.DELETE;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.PUT;
import org.springframework.web.reactive.function.server.RouterFunction;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@SpringBootApplication
@EnableMongoAuditing
Expand All @@ -53,7 +24,6 @@ public static void main(String[] args) {
// HttpSessionStrategy httpSessionStrategy() {
// return new HeaderHttpSessionStrategy();
// }

@Bean
public RouterFunction<ServerResponse> routes(PostHandler postController) {
return route(GET("/posts"), postController::all)
Expand All @@ -62,139 +32,4 @@ public RouterFunction<ServerResponse> routes(PostHandler postController) {
.andRoute(PUT("/posts/{id}"), postController::update)
.andRoute(DELETE("/posts/{id}"), postController::delete);
}

}

@EnableWebFluxSecurity
class SecurityConfig {

@Bean
SecurityWebFilterChain springWebFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeExchange()
.pathMatchers(HttpMethod.GET, "/posts/**").permitAll()
.pathMatchers(HttpMethod.DELETE, "/posts/**").hasRole("ADMIN")
//.pathMatchers("/users/{user}/**").access(this::currentUserMatchesPath)
.anyExchange().authenticated()
.and()
.build();
}

private Mono<AuthorizationDecision> currentUserMatchesPath(Mono<Authentication> authentication, AuthorizationContext context) {
return authentication
.map(a -> context.getVariables().get("user").equals(a.getName()))
.map(granted -> new AuthorizationDecision(granted));
}

@Bean
public MapUserDetailsRepository userDetailsRepository() {
UserDetails rob = User.withUsername("test").password("test123").roles("USER").build();
UserDetails admin = User.withUsername("admin").password("admin123").roles("USER", "ADMIN").build();
return new MapUserDetailsRepository(rob, admin);
}

}

@Component
@Slf4j
class DataInitializr implements CommandLineRunner {

private final PostRepository posts;

public DataInitializr(PostRepository posts) {
this.posts = posts;
}

@Override
public void run(String[] args) {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);

}

}

@Component
class PostHandler {

private final PostRepository posts;

public PostHandler(PostRepository posts) {
this.posts = posts;
}

public Mono<ServerResponse> all(ServerRequest req) {
return ServerResponse.ok().body(this.posts.findAll(), Post.class);
}

public Mono<ServerResponse> create(ServerRequest req) {
return req.bodyToMono(Post.class)
.flatMap(post -> this.posts.save(post))
.flatMap(p -> ServerResponse.created(URI.create("/posts/" + p.getId())).build());
}

public Mono<ServerResponse> get(ServerRequest req) {
return this.posts.findById(req.pathVariable("id"))
.flatMap(post -> ServerResponse.ok().body(Mono.just(post), Post.class))
.switchIfEmpty(ServerResponse.notFound().build());
}

public Mono<ServerResponse> update(ServerRequest req) {

return Mono
.zip(
(data) -> {
Post p = (Post) data[0];
Post p2 = (Post) data[1];
p.setTitle(p2.getTitle());
p.setContent(p2.getContent());
return p;
},
this.posts.findById(req.pathVariable("id")),
req.bodyToMono(Post.class)
)
.cast(Post.class)
.flatMap(post -> this.posts.save(post))
.flatMap(post -> ServerResponse.noContent().build());

}

public Mono<ServerResponse> delete(ServerRequest req) {
return ServerResponse.noContent().build(this.posts.deleteById(req.pathVariable("id")));
}

}

interface PostRepository extends ReactiveMongoRepository<Post, String> {
}

@Document
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Post {

@Id
private String id;
private String title;
private String content;

@CreatedDate
private LocalDateTime createdDate;
}
37 changes: 37 additions & 0 deletions session/src/main/java/com/example/demo/Post.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;

import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
*
* @author hantsy
*/
@Document
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Post {

@Id
private String id;
private String title;
private String content;
@CreatedDate
private LocalDateTime createdDate;

}
67 changes: 67 additions & 0 deletions session/src/main/java/com/example/demo/PostHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;

import java.net.URI;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
*
* @author hantsy
*/
@Component
class PostHandler {

private final PostRepository posts;

public PostHandler(PostRepository posts) {
this.posts = posts;
}

public Mono<ServerResponse> all(ServerRequest req) {
return ServerResponse.ok().body(this.posts.findAll(), Post.class);
}

public Mono<ServerResponse> create(ServerRequest req) {
return req
.bodyToMono(Post.class)
.flatMap((post) -> this.posts.save(post))
.flatMap((p) -> ServerResponse.created(URI.create("/posts/" + p.getId())).build());
}

public Mono<ServerResponse> get(ServerRequest req) {
return this.posts
.findById(req.pathVariable("id"))
.flatMap((post) -> ServerResponse.ok().body(Mono.just(post), Post.class))
.switchIfEmpty(ServerResponse.notFound().build());
}

public Mono<ServerResponse> update(ServerRequest req) {
return Mono
.zip(
(data) -> {
Post p = (Post) data[0];
Post p2 = (Post) data[1];
p.setTitle(p2.getTitle());
p.setContent(p2.getContent());
return p;
},
this.posts.findById(req.pathVariable("id")),
req.bodyToMono(Post.class)
)
.cast(Post.class)
.flatMap((post) -> this.posts.save(post))
.flatMap((post) -> ServerResponse.noContent().build());
}

public Mono<ServerResponse> delete(ServerRequest req) {
return ServerResponse.noContent().build(this.posts.deleteById(req.pathVariable("id")));
}

}
14 changes: 14 additions & 0 deletions session/src/main/java/com/example/demo/PostRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;

import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

/**
*
* @author hantsy
*/
interface PostRepository extends ReactiveMongoRepository<Post, String> {}
Loading

0 comments on commit 82fe3e7

Please sign in to comment.