repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
thomas-kendall/trivia-microservices
trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository;
package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository;
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // } // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository; package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository;
public UserDTO authenticateUser(String email, String password) {
thomas-kendall/trivia-microservices
trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository;
package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository; public UserDTO authenticateUser(String email, String password) { UserDTO userDTO = null;
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // } // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository; package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository; public UserDTO authenticateUser(String email, String password) { UserDTO userDTO = null;
User user = userRepository.findByEmail(email);
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/UserController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/UserController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired
private TriviaUserManagementServiceAPI userManagementAPI;
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/UserController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST)
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/UserController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST)
public UserDTO createUser(@RequestBody UserDTO user) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/UserController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST) public UserDTO createUser(@RequestBody UserDTO user) { return userManagementAPI.createUser(getAuthorizationToken(), user); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteUser(@PathVariable int id) { userManagementAPI.deleteUser(getAuthorizationToken(), id); } @RequestMapping(method = RequestMethod.GET) public Iterable<UserDTO> findAllUsers() { return userManagementAPI.findAllUsers(getAuthorizationToken()); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public UserDTO findUserById(@PathVariable int id) { return userManagementAPI.findUserById(getAuthorizationToken(), id); } @RequestMapping(value = "/{id}/roles", method = RequestMethod.GET)
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/UserController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/users") public class UserController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST) public UserDTO createUser(@RequestBody UserDTO user) { return userManagementAPI.createUser(getAuthorizationToken(), user); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteUser(@PathVariable int id) { userManagementAPI.deleteUser(getAuthorizationToken(), id); } @RequestMapping(method = RequestMethod.GET) public Iterable<UserDTO> findAllUsers() { return userManagementAPI.findAllUsers(getAuthorizationToken()); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public UserDTO findUserById(@PathVariable int id) { return userManagementAPI.findUserById(getAuthorizationToken(), id); } @RequestMapping(value = "/{id}/roles", method = RequestMethod.GET)
public Iterable<RoleDTO> findUserRoles(@PathVariable int id) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO;
package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // Path: trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired
private TriviaUserManagementServiceAPI userManagementServiceAPI;
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO;
package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired private TriviaUserManagementServiceAPI userManagementServiceAPI; @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // Path: trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired private TriviaUserManagementServiceAPI userManagementServiceAPI; @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public AuthTokenDTO authenticate(@RequestBody AuthenticationDTO authenticationDTO) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO;
package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired private TriviaUserManagementServiceAPI userManagementServiceAPI; @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
// Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // Path: trivia-ui/src/main/java/trivia/ui/controller/AuthenticationController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; package trivia.ui.controller; @RestController public class AuthenticationController { @Autowired private TriviaUserManagementServiceAPI userManagementServiceAPI; @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public AuthTokenDTO authenticate(@RequestBody AuthenticationDTO authenticationDTO) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/BaseController.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // }
import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import trivia.common.security.JsonWebTokenAuthentication;
package trivia.ui.controller; public class BaseController { protected String getAuthorizationToken() { String token = null; Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/BaseController.java import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import trivia.common.security.JsonWebTokenAuthentication; package trivia.ui.controller; public class BaseController { protected String getAuthorizationToken() { String token = null; Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getClass().isAssignableFrom(JsonWebTokenAuthentication.class)) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/security/TriviaUiWebSecurityConfig.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenSecurityConfig.java // public abstract class JsonWebTokenSecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // private JsonWebTokenAuthenticationProvider authenticationProvider; // // @Autowired // private JsonWebTokenAuthenticationFilter jsonWebTokenFilter; // // @Bean // @Override // public AuthenticationManager authenticationManagerBean() throws Exception { // // This method is here with the @Bean annotation so that Spring can // // autowire it // return super.authenticationManagerBean(); // } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.authenticationProvider(authenticationProvider); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // // disable CSRF, http basic, form login // .csrf().disable() // // .httpBasic().disable() // // .formLogin().disable() // // // ReST is stateless, no sessions // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // // // .and() // // // return 403 when not authenticated // .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()); // // // Let child classes set up authorization paths // setupAuthorization(http); // // http.addFilterBefore(jsonWebTokenFilter, UsernamePasswordAuthenticationFilter.class); // } // // protected abstract void setupAuthorization(HttpSecurity http) throws Exception; // }
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import trivia.common.security.JsonWebTokenSecurityConfig;
package trivia.ui.security; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @ComponentScan(basePackages = "trivia.common.security")
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenSecurityConfig.java // public abstract class JsonWebTokenSecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // private JsonWebTokenAuthenticationProvider authenticationProvider; // // @Autowired // private JsonWebTokenAuthenticationFilter jsonWebTokenFilter; // // @Bean // @Override // public AuthenticationManager authenticationManagerBean() throws Exception { // // This method is here with the @Bean annotation so that Spring can // // autowire it // return super.authenticationManagerBean(); // } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.authenticationProvider(authenticationProvider); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // // disable CSRF, http basic, form login // .csrf().disable() // // .httpBasic().disable() // // .formLogin().disable() // // // ReST is stateless, no sessions // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // // // .and() // // // return 403 when not authenticated // .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()); // // // Let child classes set up authorization paths // setupAuthorization(http); // // http.addFilterBefore(jsonWebTokenFilter, UsernamePasswordAuthenticationFilter.class); // } // // protected abstract void setupAuthorization(HttpSecurity http) throws Exception; // } // Path: trivia-ui/src/main/java/trivia/ui/security/TriviaUiWebSecurityConfig.java import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import trivia.common.security.JsonWebTokenSecurityConfig; package trivia.ui.security; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @ComponentScan(basePackages = "trivia.common.security")
public class TriviaUiWebSecurityConfig extends JsonWebTokenSecurityConfig {
thomas-kendall/trivia-microservices
trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthenticationProvider.java
// Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/AuthTokenDetailsDTO.java // public class AuthTokenDetailsDTO { // public String userId; // public String email; // public List<String> roleNames; // // @JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") // public Date expirationDate; // } // // Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/JsonWebTokenUtility.java // public class JsonWebTokenUtility { // // private SignatureAlgorithm signatureAlgorithm; // private Key secretKey; // // public JsonWebTokenUtility() { // // // THIS IS NOT A SECURE PRACTICE! // // For simplicity, we are storing a static key here. // // Ideally, in a microservices environment, this key would kept on a // // config server. // signatureAlgorithm = SignatureAlgorithm.HS512; // String encodedKey = "L7A/6zARSkK1j7Vd5SDD9pSSqZlqF7mAhiOgRbgv9Smce6tf4cJnvKOjtKPxNNnWQj+2lQEScm3XIUjhW+YVZg=="; // secretKey = deserializeKey(encodedKey); // // // secretKey = MacProvider.generateKey(signatureAlgorithm); // } // // public String createJsonWebToken(AuthTokenDetailsDTO authTokenDetailsDTO) { // String token = Jwts.builder().setSubject(authTokenDetailsDTO.userId).claim("email", authTokenDetailsDTO.email) // .claim("roles", authTokenDetailsDTO.roleNames).setExpiration(authTokenDetailsDTO.expirationDate) // .signWith(getSignatureAlgorithm(), getSecretKey()).compact(); // return token; // } // // private Key deserializeKey(String encodedKey) { // byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // Key key = new SecretKeySpec(decodedKey, getSignatureAlgorithm().getJcaName()); // return key; // } // // private Key getSecretKey() { // return secretKey; // } // // public SignatureAlgorithm getSignatureAlgorithm() { // return signatureAlgorithm; // } // // public AuthTokenDetailsDTO parseAndValidate(String token) { // AuthTokenDetailsDTO authTokenDetailsDTO = null; // try { // Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody(); // String userId = claims.getSubject(); // String email = (String) claims.get("email"); // List<String> roleNames = (List<String>) claims.get("roles"); // Date expirationDate = claims.getExpiration(); // // authTokenDetailsDTO = new AuthTokenDetailsDTO(); // authTokenDetailsDTO.userId = userId; // authTokenDetailsDTO.email = email; // authTokenDetailsDTO.roleNames = roleNames; // authTokenDetailsDTO.expirationDate = expirationDate; // } catch (JwtException ex) { // System.out.println(ex); // } // return authTokenDetailsDTO; // } // // private String serializeKey(Key key) { // String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded()); // return encodedKey; // } // // }
import java.util.List; import java.util.stream.Collectors; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; import trivia.common.jsonwebtoken.AuthTokenDetailsDTO; import trivia.common.jsonwebtoken.JsonWebTokenUtility;
package trivia.common.security; @Component public class JsonWebTokenAuthenticationProvider implements AuthenticationProvider {
// Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/AuthTokenDetailsDTO.java // public class AuthTokenDetailsDTO { // public String userId; // public String email; // public List<String> roleNames; // // @JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") // public Date expirationDate; // } // // Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/JsonWebTokenUtility.java // public class JsonWebTokenUtility { // // private SignatureAlgorithm signatureAlgorithm; // private Key secretKey; // // public JsonWebTokenUtility() { // // // THIS IS NOT A SECURE PRACTICE! // // For simplicity, we are storing a static key here. // // Ideally, in a microservices environment, this key would kept on a // // config server. // signatureAlgorithm = SignatureAlgorithm.HS512; // String encodedKey = "L7A/6zARSkK1j7Vd5SDD9pSSqZlqF7mAhiOgRbgv9Smce6tf4cJnvKOjtKPxNNnWQj+2lQEScm3XIUjhW+YVZg=="; // secretKey = deserializeKey(encodedKey); // // // secretKey = MacProvider.generateKey(signatureAlgorithm); // } // // public String createJsonWebToken(AuthTokenDetailsDTO authTokenDetailsDTO) { // String token = Jwts.builder().setSubject(authTokenDetailsDTO.userId).claim("email", authTokenDetailsDTO.email) // .claim("roles", authTokenDetailsDTO.roleNames).setExpiration(authTokenDetailsDTO.expirationDate) // .signWith(getSignatureAlgorithm(), getSecretKey()).compact(); // return token; // } // // private Key deserializeKey(String encodedKey) { // byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // Key key = new SecretKeySpec(decodedKey, getSignatureAlgorithm().getJcaName()); // return key; // } // // private Key getSecretKey() { // return secretKey; // } // // public SignatureAlgorithm getSignatureAlgorithm() { // return signatureAlgorithm; // } // // public AuthTokenDetailsDTO parseAndValidate(String token) { // AuthTokenDetailsDTO authTokenDetailsDTO = null; // try { // Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody(); // String userId = claims.getSubject(); // String email = (String) claims.get("email"); // List<String> roleNames = (List<String>) claims.get("roles"); // Date expirationDate = claims.getExpiration(); // // authTokenDetailsDTO = new AuthTokenDetailsDTO(); // authTokenDetailsDTO.userId = userId; // authTokenDetailsDTO.email = email; // authTokenDetailsDTO.roleNames = roleNames; // authTokenDetailsDTO.expirationDate = expirationDate; // } catch (JwtException ex) { // System.out.println(ex); // } // return authTokenDetailsDTO; // } // // private String serializeKey(Key key) { // String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded()); // return encodedKey; // } // // } // Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthenticationProvider.java import java.util.List; import java.util.stream.Collectors; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; import trivia.common.jsonwebtoken.AuthTokenDetailsDTO; import trivia.common.jsonwebtoken.JsonWebTokenUtility; package trivia.common.security; @Component public class JsonWebTokenAuthenticationProvider implements AuthenticationProvider {
private JsonWebTokenUtility tokenService = new JsonWebTokenUtility();
thomas-kendall/trivia-microservices
trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthenticationProvider.java
// Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/AuthTokenDetailsDTO.java // public class AuthTokenDetailsDTO { // public String userId; // public String email; // public List<String> roleNames; // // @JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") // public Date expirationDate; // } // // Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/JsonWebTokenUtility.java // public class JsonWebTokenUtility { // // private SignatureAlgorithm signatureAlgorithm; // private Key secretKey; // // public JsonWebTokenUtility() { // // // THIS IS NOT A SECURE PRACTICE! // // For simplicity, we are storing a static key here. // // Ideally, in a microservices environment, this key would kept on a // // config server. // signatureAlgorithm = SignatureAlgorithm.HS512; // String encodedKey = "L7A/6zARSkK1j7Vd5SDD9pSSqZlqF7mAhiOgRbgv9Smce6tf4cJnvKOjtKPxNNnWQj+2lQEScm3XIUjhW+YVZg=="; // secretKey = deserializeKey(encodedKey); // // // secretKey = MacProvider.generateKey(signatureAlgorithm); // } // // public String createJsonWebToken(AuthTokenDetailsDTO authTokenDetailsDTO) { // String token = Jwts.builder().setSubject(authTokenDetailsDTO.userId).claim("email", authTokenDetailsDTO.email) // .claim("roles", authTokenDetailsDTO.roleNames).setExpiration(authTokenDetailsDTO.expirationDate) // .signWith(getSignatureAlgorithm(), getSecretKey()).compact(); // return token; // } // // private Key deserializeKey(String encodedKey) { // byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // Key key = new SecretKeySpec(decodedKey, getSignatureAlgorithm().getJcaName()); // return key; // } // // private Key getSecretKey() { // return secretKey; // } // // public SignatureAlgorithm getSignatureAlgorithm() { // return signatureAlgorithm; // } // // public AuthTokenDetailsDTO parseAndValidate(String token) { // AuthTokenDetailsDTO authTokenDetailsDTO = null; // try { // Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody(); // String userId = claims.getSubject(); // String email = (String) claims.get("email"); // List<String> roleNames = (List<String>) claims.get("roles"); // Date expirationDate = claims.getExpiration(); // // authTokenDetailsDTO = new AuthTokenDetailsDTO(); // authTokenDetailsDTO.userId = userId; // authTokenDetailsDTO.email = email; // authTokenDetailsDTO.roleNames = roleNames; // authTokenDetailsDTO.expirationDate = expirationDate; // } catch (JwtException ex) { // System.out.println(ex); // } // return authTokenDetailsDTO; // } // // private String serializeKey(Key key) { // String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded()); // return encodedKey; // } // // }
import java.util.List; import java.util.stream.Collectors; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; import trivia.common.jsonwebtoken.AuthTokenDetailsDTO; import trivia.common.jsonwebtoken.JsonWebTokenUtility;
package trivia.common.security; @Component public class JsonWebTokenAuthenticationProvider implements AuthenticationProvider { private JsonWebTokenUtility tokenService = new JsonWebTokenUtility(); @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authenticatedUser = null; // Only process the PreAuthenticatedAuthenticationToken if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class) && authentication.getPrincipal() != null) { String tokenHeader = (String) authentication.getPrincipal(); UserDetails userDetails = parseToken(tokenHeader); if (userDetails != null) { authenticatedUser = new JsonWebTokenAuthentication(userDetails, tokenHeader); } } else { // It is already a JsonWebTokenAuthentication authenticatedUser = authentication; } return authenticatedUser; } private UserDetails parseToken(String tokenHeader) { UserDetails principal = null;
// Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/AuthTokenDetailsDTO.java // public class AuthTokenDetailsDTO { // public String userId; // public String email; // public List<String> roleNames; // // @JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") // public Date expirationDate; // } // // Path: trivia-common/src/main/java/trivia/common/jsonwebtoken/JsonWebTokenUtility.java // public class JsonWebTokenUtility { // // private SignatureAlgorithm signatureAlgorithm; // private Key secretKey; // // public JsonWebTokenUtility() { // // // THIS IS NOT A SECURE PRACTICE! // // For simplicity, we are storing a static key here. // // Ideally, in a microservices environment, this key would kept on a // // config server. // signatureAlgorithm = SignatureAlgorithm.HS512; // String encodedKey = "L7A/6zARSkK1j7Vd5SDD9pSSqZlqF7mAhiOgRbgv9Smce6tf4cJnvKOjtKPxNNnWQj+2lQEScm3XIUjhW+YVZg=="; // secretKey = deserializeKey(encodedKey); // // // secretKey = MacProvider.generateKey(signatureAlgorithm); // } // // public String createJsonWebToken(AuthTokenDetailsDTO authTokenDetailsDTO) { // String token = Jwts.builder().setSubject(authTokenDetailsDTO.userId).claim("email", authTokenDetailsDTO.email) // .claim("roles", authTokenDetailsDTO.roleNames).setExpiration(authTokenDetailsDTO.expirationDate) // .signWith(getSignatureAlgorithm(), getSecretKey()).compact(); // return token; // } // // private Key deserializeKey(String encodedKey) { // byte[] decodedKey = Base64.getDecoder().decode(encodedKey); // Key key = new SecretKeySpec(decodedKey, getSignatureAlgorithm().getJcaName()); // return key; // } // // private Key getSecretKey() { // return secretKey; // } // // public SignatureAlgorithm getSignatureAlgorithm() { // return signatureAlgorithm; // } // // public AuthTokenDetailsDTO parseAndValidate(String token) { // AuthTokenDetailsDTO authTokenDetailsDTO = null; // try { // Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody(); // String userId = claims.getSubject(); // String email = (String) claims.get("email"); // List<String> roleNames = (List<String>) claims.get("roles"); // Date expirationDate = claims.getExpiration(); // // authTokenDetailsDTO = new AuthTokenDetailsDTO(); // authTokenDetailsDTO.userId = userId; // authTokenDetailsDTO.email = email; // authTokenDetailsDTO.roleNames = roleNames; // authTokenDetailsDTO.expirationDate = expirationDate; // } catch (JwtException ex) { // System.out.println(ex); // } // return authTokenDetailsDTO; // } // // private String serializeKey(Key key) { // String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded()); // return encodedKey; // } // // } // Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthenticationProvider.java import java.util.List; import java.util.stream.Collectors; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.stereotype.Component; import trivia.common.jsonwebtoken.AuthTokenDetailsDTO; import trivia.common.jsonwebtoken.JsonWebTokenUtility; package trivia.common.security; @Component public class JsonWebTokenAuthenticationProvider implements AuthenticationProvider { private JsonWebTokenUtility tokenService = new JsonWebTokenUtility(); @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authenticatedUser = null; // Only process the PreAuthenticatedAuthenticationToken if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class) && authentication.getPrincipal() != null) { String tokenHeader = (String) authentication.getPrincipal(); UserDetails userDetails = parseToken(tokenHeader); if (userDetails != null) { authenticatedUser = new JsonWebTokenAuthentication(userDetails, tokenHeader); } } else { // It is already a JsonWebTokenAuthentication authenticatedUser = authentication; } return authenticatedUser; } private UserDetails parseToken(String tokenHeader) { UserDetails principal = null;
AuthTokenDetailsDTO authTokenDetails = tokenService.parseAndValidate(tokenHeader);
thomas-kendall/trivia-microservices
trivia-user-management-service/src/main/java/trivia/usermanagement/security/TriviaUserManagementWebSecurityConfig.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenSecurityConfig.java // public abstract class JsonWebTokenSecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // private JsonWebTokenAuthenticationProvider authenticationProvider; // // @Autowired // private JsonWebTokenAuthenticationFilter jsonWebTokenFilter; // // @Bean // @Override // public AuthenticationManager authenticationManagerBean() throws Exception { // // This method is here with the @Bean annotation so that Spring can // // autowire it // return super.authenticationManagerBean(); // } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.authenticationProvider(authenticationProvider); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // // disable CSRF, http basic, form login // .csrf().disable() // // .httpBasic().disable() // // .formLogin().disable() // // // ReST is stateless, no sessions // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // // // .and() // // // return 403 when not authenticated // .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()); // // // Let child classes set up authorization paths // setupAuthorization(http); // // http.addFilterBefore(jsonWebTokenFilter, UsernamePasswordAuthenticationFilter.class); // } // // protected abstract void setupAuthorization(HttpSecurity http) throws Exception; // }
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import trivia.common.security.JsonWebTokenSecurityConfig;
package trivia.usermanagement.security; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @ComponentScan(basePackages = "trivia.common.security")
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenSecurityConfig.java // public abstract class JsonWebTokenSecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // private JsonWebTokenAuthenticationProvider authenticationProvider; // // @Autowired // private JsonWebTokenAuthenticationFilter jsonWebTokenFilter; // // @Bean // @Override // public AuthenticationManager authenticationManagerBean() throws Exception { // // This method is here with the @Bean annotation so that Spring can // // autowire it // return super.authenticationManagerBean(); // } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.authenticationProvider(authenticationProvider); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // // disable CSRF, http basic, form login // .csrf().disable() // // .httpBasic().disable() // // .formLogin().disable() // // // ReST is stateless, no sessions // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // // // .and() // // // return 403 when not authenticated // .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()); // // // Let child classes set up authorization paths // setupAuthorization(http); // // http.addFilterBefore(jsonWebTokenFilter, UsernamePasswordAuthenticationFilter.class); // } // // protected abstract void setupAuthorization(HttpSecurity http) throws Exception; // } // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/security/TriviaUserManagementWebSecurityConfig.java import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import trivia.common.security.JsonWebTokenSecurityConfig; package trivia.usermanagement.security; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @ComponentScan(basePackages = "trivia.common.security")
public class TriviaUserManagementWebSecurityConfig extends JsonWebTokenSecurityConfig {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO);
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO);
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST) AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); @RequestMapping(method = RequestMethod.POST, value = "/roles")
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST) AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); @RequestMapping(method = RequestMethod.POST, value = "/roles")
RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO);
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // }
import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO;
package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST) AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); @RequestMapping(method = RequestMethod.POST, value = "/roles") RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); @RequestMapping(method = RequestMethod.POST, value = "/users")
// Path: trivia-ui/src/main/java/trivia/ui/dto/AuthTokenDTO.java // public class AuthTokenDTO { // public String token; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/AuthenticationDTO.java // public class AuthenticationDTO { // public String email; // public String password; // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public List<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, List<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // } // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java import java.util.Collection; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import trivia.ui.dto.AuthTokenDTO; import trivia.ui.dto.AuthenticationDTO; import trivia.ui.dto.RoleDTO; import trivia.ui.dto.UserDTO; package trivia.ui.api; @FeignClient("trivia-user-management-service") public interface TriviaUserManagementServiceAPI { @RequestMapping(value = "/authenticate", method = RequestMethod.POST) AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); @RequestMapping(method = RequestMethod.POST, value = "/roles") RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); @RequestMapping(method = RequestMethod.POST, value = "/users")
UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO);
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/RoleController.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/RoleController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired
private TriviaUserManagementServiceAPI userManagementAPI;
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/RoleController.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST)
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/RoleController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST)
public RoleDTO createRole(@RequestBody RoleDTO role) {
thomas-kendall/trivia-microservices
trivia-ui/src/main/java/trivia/ui/controller/RoleController.java
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO;
package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST) public RoleDTO createRole(@RequestBody RoleDTO role) { return userManagementAPI.createRole(getAuthorizationToken(), role); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteRole(@PathVariable int id) { userManagementAPI.deleteRole(getAuthorizationToken(), id); } @RequestMapping(method = RequestMethod.GET)
// Path: trivia-common/src/main/java/trivia/common/security/JsonWebTokenAuthentication.java // public class JsonWebTokenAuthentication extends AbstractAuthenticationToken { // private static final long serialVersionUID = -6855809445272533821L; // // private UserDetails principal; // private String jsonWebToken; // // public JsonWebTokenAuthentication(UserDetails principal, String jsonWebToken) { // super(principal.getAuthorities()); // this.principal = principal; // this.jsonWebToken = jsonWebToken; // } // // @Override // public Object getCredentials() { // return null; // } // // public String getJsonWebToken() { // return jsonWebToken; // } // // @Override // public Object getPrincipal() { // return principal; // } // } // // Path: trivia-ui/src/main/java/trivia/ui/api/TriviaUserManagementServiceAPI.java // @FeignClient("trivia-user-management-service") // public interface TriviaUserManagementServiceAPI { // // @RequestMapping(value = "/authenticate", method = RequestMethod.POST) // AuthTokenDTO authenticateUser(@RequestBody AuthenticationDTO authenticationDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/roles") // RoleDTO createRole(@RequestHeader("Authorization") String authorizationToken, @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.POST, value = "/users") // UserDTO createUser(@RequestHeader("Authorization") String authorizationToken, @RequestBody UserDTO userDTO); // // @RequestMapping(method = RequestMethod.DELETE, value = "/roles/{id}") // void deleteRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.DELETE, value = "/users/{id}") // void deleteUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/roles") // Collection<RoleDTO> findAllRoles(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/users") // Collection<UserDTO> findAllUsers(@RequestHeader("Authorization") String authorizationToken); // // @RequestMapping(method = RequestMethod.GET, value = "/roles/{id}", produces = "application/json", consumes = "application/json") // RoleDTO findRoleById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = "application/json", consumes = "application/json") // UserDTO findUserById(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.GET, value = "/users/{id}/roles") // Collection<RoleDTO> findUserRoles(@RequestHeader("Authorization") String authorizationToken, // @PathVariable("id") int id); // // @RequestMapping(method = RequestMethod.PUT, value = "/roles/{id}") // void updateRole(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody RoleDTO roleDTO); // // @RequestMapping(method = RequestMethod.PUT, value = "/users/{id}") // void updateUser(@RequestHeader("Authorization") String authorizationToken, @PathVariable("id") int id, // @RequestBody UserDTO userDTO); // } // // Path: trivia-ui/src/main/java/trivia/ui/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // } // Path: trivia-ui/src/main/java/trivia/ui/controller/RoleController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import trivia.common.security.JsonWebTokenAuthentication; import trivia.ui.api.TriviaUserManagementServiceAPI; import trivia.ui.dto.RoleDTO; package trivia.ui.controller; @RestController @RequestMapping("/api/roles") public class RoleController extends BaseController { @Autowired private TriviaUserManagementServiceAPI userManagementAPI; @RequestMapping(method = RequestMethod.POST) public RoleDTO createRole(@RequestBody RoleDTO role) { return userManagementAPI.createRole(getAuthorizationToken(), role); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteRole(@PathVariable int id) { userManagementAPI.deleteRole(getAuthorizationToken(), id); } @RequestMapping(method = RequestMethod.GET)
public Iterable<RoleDTO> findAllRoles(@AuthenticationPrincipal JsonWebTokenAuthentication jwt) {
freeseawind/NinePatch
code/src/test/java/javafx/JavaFxTest.java
// Path: code/src/main/java/freeseawind/ninepatch/javafx/FxNinePatch.java // public class FxNinePatch extends AbstractNinePatch<Image, GraphicsContext> // { // public FxNinePatch(Image image) // { // super(image, null); // } // // public FxNinePatch(Image image, RepeatType repeatType) // { // super(image, repeatType); // } // // @Override // public int[] getPixels(Image img, int x, int y, int w, int h) // { // int[] pixels = new int[w * h]; // // PixelReader reader = img.getPixelReader(); // // PixelFormat.Type type = reader.getPixelFormat().getType(); // // WritablePixelFormat<IntBuffer> format = null; // // if(type == PixelFormat.Type.INT_ARGB_PRE) // { // format = PixelFormat.getIntArgbPreInstance(); // } // else // { // format = PixelFormat.getIntArgbInstance(); // } // // reader.getPixels(x, y, w, h, format, pixels, 0, w); // // return pixels; // } // // @Override // public int getImageWidth(Image img) // { // return img.widthProperty().intValue(); // } // // @Override // public int getImageHeight(Image img) // { // return img.heightProperty().intValue(); // } // // @Override // public void translate(GraphicsContext g2d, int x, int y) // { // g2d.translate(x, y); // } // // // @Override // public void drawImage(GraphicsContext g2d, // Image image, // int x, // int y, // int scaledWidth, // int scaledHeight) // { // g2d.drawImage(image, x, y, scaledWidth, scaledHeight); // } // // // @Override // public void drawImage(GraphicsContext g2d, // Image image, // int sx, // int sy, // int sw, // int sh, // int dx, // int dy, // int dw, // int dh) // { // g2d.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); // } // }
import freeseawind.ninepatch.javafx.FxNinePatch; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.stage.Stage;
package javafx; /** * * @author wallace * */ public class JavaFxTest extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("NinePatch Test"); Group root = new Group(); Scene sc = new Scene(root, 480, 360); primaryStage.setScene(sc); Canvas canvas = new Canvas(); canvas.widthProperty().bind(sc.widthProperty()); canvas.heightProperty().bind(sc.heightProperty()); GraphicsContext gc = canvas.getGraphicsContext2D(); Image img = new Image(getClass().getResource("/icon_qipao.9.png").toExternalForm());
// Path: code/src/main/java/freeseawind/ninepatch/javafx/FxNinePatch.java // public class FxNinePatch extends AbstractNinePatch<Image, GraphicsContext> // { // public FxNinePatch(Image image) // { // super(image, null); // } // // public FxNinePatch(Image image, RepeatType repeatType) // { // super(image, repeatType); // } // // @Override // public int[] getPixels(Image img, int x, int y, int w, int h) // { // int[] pixels = new int[w * h]; // // PixelReader reader = img.getPixelReader(); // // PixelFormat.Type type = reader.getPixelFormat().getType(); // // WritablePixelFormat<IntBuffer> format = null; // // if(type == PixelFormat.Type.INT_ARGB_PRE) // { // format = PixelFormat.getIntArgbPreInstance(); // } // else // { // format = PixelFormat.getIntArgbInstance(); // } // // reader.getPixels(x, y, w, h, format, pixels, 0, w); // // return pixels; // } // // @Override // public int getImageWidth(Image img) // { // return img.widthProperty().intValue(); // } // // @Override // public int getImageHeight(Image img) // { // return img.heightProperty().intValue(); // } // // @Override // public void translate(GraphicsContext g2d, int x, int y) // { // g2d.translate(x, y); // } // // // @Override // public void drawImage(GraphicsContext g2d, // Image image, // int x, // int y, // int scaledWidth, // int scaledHeight) // { // g2d.drawImage(image, x, y, scaledWidth, scaledHeight); // } // // // @Override // public void drawImage(GraphicsContext g2d, // Image image, // int sx, // int sy, // int sw, // int sh, // int dx, // int dy, // int dw, // int dh) // { // g2d.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); // } // } // Path: code/src/test/java/javafx/JavaFxTest.java import freeseawind.ninepatch.javafx.FxNinePatch; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.stage.Stage; package javafx; /** * * @author wallace * */ public class JavaFxTest extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("NinePatch Test"); Group root = new Group(); Scene sc = new Scene(root, 480, 360); primaryStage.setScene(sc); Canvas canvas = new Canvas(); canvas.widthProperty().bind(sc.widthProperty()); canvas.heightProperty().bind(sc.heightProperty()); GraphicsContext gc = canvas.getGraphicsContext2D(); Image img = new Image(getClass().getResource("/icon_qipao.9.png").toExternalForm());
FxNinePatch np = new FxNinePatch(img);
freeseawind/NinePatch
code/src/main/java/freeseawind/ninepatch/common/AbstractNinePatch.java
// Path: code/src/main/java/freeseawind/ninepatch/common/Row.java // static enum Type // { // FIX, // 固定类型 // HORIZONTALPATCH, // 水平拉伸类型 // VERTICALPATCH, // 垂直拉伸类型 // TILEPATCH // 平铺类型 // }
import java.awt.Rectangle; import java.util.Collections; import java.util.LinkedList; import java.util.List; import freeseawind.ninepatch.common.Row.Type;
// 逐行绘制 for(List<Row> rows : columns) { int rowCount = 0; int height = patchHeight; boolean isFirst = true; int preRowHeight = 0; // 防止图片拉伸高度大于实际需要拉伸高度 if(startY >= scaledHeight) { break; } for(Row row : rows) { Rectangle rect = row.getRectangle(); int width = rect.width; // 防止图片拉伸宽度大于实际需要拉伸宽度 if(startX >= scaledWidth) { break; }
// Path: code/src/main/java/freeseawind/ninepatch/common/Row.java // static enum Type // { // FIX, // 固定类型 // HORIZONTALPATCH, // 水平拉伸类型 // VERTICALPATCH, // 垂直拉伸类型 // TILEPATCH // 平铺类型 // } // Path: code/src/main/java/freeseawind/ninepatch/common/AbstractNinePatch.java import java.awt.Rectangle; import java.util.Collections; import java.util.LinkedList; import java.util.List; import freeseawind.ninepatch.common.Row.Type; // 逐行绘制 for(List<Row> rows : columns) { int rowCount = 0; int height = patchHeight; boolean isFirst = true; int preRowHeight = 0; // 防止图片拉伸高度大于实际需要拉伸高度 if(startY >= scaledHeight) { break; } for(Row row : rows) { Rectangle rect = row.getRectangle(); int width = rect.width; // 防止图片拉伸宽度大于实际需要拉伸宽度 if(startX >= scaledWidth) { break; }
if(Type.HORIZONTALPATCH == row.getType() || Type.TILEPATCH == row.getType())
freeseawind/NinePatch
code/src/test/java/swing/SwingTest.java
// Path: code/src/main/java/freeseawind/ninepatch/swing/SwingNinePatch.java // public class SwingNinePatch extends AbstractNinePatch<BufferedImage, Graphics2D> // { // public SwingNinePatch(BufferedImage image) // { // super(image); // } // // public SwingNinePatch(BufferedImage image, RepeatType repeatType) // { // super(image, repeatType); // } // // @Override // protected BufferedImage toCompatibleImage(BufferedImage image) // { // GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); // // GraphicsConfiguration config = device.getDefaultConfiguration(); // // BufferedImage bufImg = config.createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT); // // Graphics2D g2d = bufImg.createGraphics(); // // g2d.drawImage(image, 0, 0, null); // // g2d.dispose(); // // return bufImg; // } // // @Override // public int[] getPixels(BufferedImage img, int x, int y, int w, int h) // { // int[] pixels = new int[w * h]; // // int imageType = img.getType(); // // if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) // { // Raster raster = img.getRaster(); // // return (int[]) raster.getDataElements(x, y, w, h, pixels); // } // // return img.getRGB(x, y, w, h, pixels, 0, w); // } // // @Override // public int getImageWidth(BufferedImage img) // { // return img.getWidth(); // } // // @Override // public int getImageHeight(BufferedImage img) // { // return img.getHeight(); // } // // @Override // public void translate(Graphics2D g2d, int x, int y) // { // g2d.translate(x, y); // } // // @Override // public void drawImage(Graphics2D g2d, // BufferedImage image, // int x, // int y, // int scaledWidth, // int scaledHeight) // { // g2d.drawImage(image, x, y, scaledWidth, scaledHeight, null); // } // // @Override // public void drawImage(Graphics2D g2d, // BufferedImage image, // int sx, // int sy, // int sw, // int sh, // int dx, // int dy, // int dw, // int dh) // { // g2d.drawImage(image, dx, dy, dx + dw, dy + dh, sx, sy, sx + sw, sy + sh, null); // } // }
import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import freeseawind.ninepatch.swing.SwingNinePatch;
package swing; public class SwingTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InputStream input = SwingTest.class.getResourceAsStream("/progressbar_cell.9.png"); final BufferedImage img = ImageIO.read(input); JFrame frame = new JFrame(); frame.setTitle("NinePatch Test");
// Path: code/src/main/java/freeseawind/ninepatch/swing/SwingNinePatch.java // public class SwingNinePatch extends AbstractNinePatch<BufferedImage, Graphics2D> // { // public SwingNinePatch(BufferedImage image) // { // super(image); // } // // public SwingNinePatch(BufferedImage image, RepeatType repeatType) // { // super(image, repeatType); // } // // @Override // protected BufferedImage toCompatibleImage(BufferedImage image) // { // GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); // // GraphicsConfiguration config = device.getDefaultConfiguration(); // // BufferedImage bufImg = config.createCompatibleImage(image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT); // // Graphics2D g2d = bufImg.createGraphics(); // // g2d.drawImage(image, 0, 0, null); // // g2d.dispose(); // // return bufImg; // } // // @Override // public int[] getPixels(BufferedImage img, int x, int y, int w, int h) // { // int[] pixels = new int[w * h]; // // int imageType = img.getType(); // // if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) // { // Raster raster = img.getRaster(); // // return (int[]) raster.getDataElements(x, y, w, h, pixels); // } // // return img.getRGB(x, y, w, h, pixels, 0, w); // } // // @Override // public int getImageWidth(BufferedImage img) // { // return img.getWidth(); // } // // @Override // public int getImageHeight(BufferedImage img) // { // return img.getHeight(); // } // // @Override // public void translate(Graphics2D g2d, int x, int y) // { // g2d.translate(x, y); // } // // @Override // public void drawImage(Graphics2D g2d, // BufferedImage image, // int x, // int y, // int scaledWidth, // int scaledHeight) // { // g2d.drawImage(image, x, y, scaledWidth, scaledHeight, null); // } // // @Override // public void drawImage(Graphics2D g2d, // BufferedImage image, // int sx, // int sy, // int sw, // int sh, // int dx, // int dy, // int dw, // int dh) // { // g2d.drawImage(image, dx, dy, dx + dw, dy + dh, sx, sy, sx + sw, sy + sh, null); // } // } // Path: code/src/test/java/swing/SwingTest.java import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import freeseawind.ninepatch.swing.SwingNinePatch; package swing; public class SwingTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InputStream input = SwingTest.class.getResourceAsStream("/progressbar_cell.9.png"); final BufferedImage img = ImageIO.read(input); JFrame frame = new JFrame(); frame.setTitle("NinePatch Test");
final SwingNinePatch np = new SwingNinePatch(img);
russellb/androvoip
src/org/androvoip/ui/Accounts.java
// Path: src/org/androvoip/Account.java // public class Account implements Serializable { // private static final long serialVersionUID = 1539547929660026657L; // // public enum Protocol { // None, // IAX2, // }; // // Protocol mProtocol; // String mHost; // String mUserName; // String mPassword; // // public Account(SharedPreferences prefs) { // refresh(prefs); // } // // public void save(SharedPreferences prefs) { // Editor prefsEditor = prefs.edit(); // prefsEditor.putString("protocol", mProtocol.toString()); // prefsEditor.putString("host", mHost); // prefsEditor.putString("username", mUserName); // prefsEditor.putString("password", mPassword); // prefsEditor.commit(); // } // // public void refresh(SharedPreferences prefs) { // mProtocol = Protocol.valueOf(prefs.getString("protocol", "None")); // mHost = prefs.getString("host", ""); // mUserName = prefs.getString("username", ""); // mPassword = prefs.getString("password", ""); // } // // public Protocol getProtocol() { // return this.mProtocol; // } // // public void setProtocol(Protocol protocol) { // this.mProtocol = protocol; // } // // public void setProtocol(String protocol) { // this.mProtocol = Protocol.valueOf(protocol); // } // // public String getHost() { // return this.mHost; // } // // public void setHost(String host) { // this.mHost = host; // } // // public String getUserName() { // return this.mUserName; // } // // public void setUserName(String username) { // this.mUserName = username; // } // // public String getPassword() { // return this.mPassword; // } // // public void setPassword(String password) { // this.mPassword = password; // } // }
import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import org.androvoip.R; import org.androvoip.Account; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
/* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2009, Jason Parker * * Jason Parker <north@ntbox.com> * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package org.androvoip.ui; public class Accounts extends ListActivity implements OnItemClickListener { private final String PREFS_FILE = "AndroVoIP_settings"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.accounts); ListView listView = getListView(); listView.setOnItemClickListener(this); listView.setEmptyView(findViewById(R.id.empty)); refresh(); } @Override public void onResume() { super.onResume(); refresh(); } private void refresh() {
// Path: src/org/androvoip/Account.java // public class Account implements Serializable { // private static final long serialVersionUID = 1539547929660026657L; // // public enum Protocol { // None, // IAX2, // }; // // Protocol mProtocol; // String mHost; // String mUserName; // String mPassword; // // public Account(SharedPreferences prefs) { // refresh(prefs); // } // // public void save(SharedPreferences prefs) { // Editor prefsEditor = prefs.edit(); // prefsEditor.putString("protocol", mProtocol.toString()); // prefsEditor.putString("host", mHost); // prefsEditor.putString("username", mUserName); // prefsEditor.putString("password", mPassword); // prefsEditor.commit(); // } // // public void refresh(SharedPreferences prefs) { // mProtocol = Protocol.valueOf(prefs.getString("protocol", "None")); // mHost = prefs.getString("host", ""); // mUserName = prefs.getString("username", ""); // mPassword = prefs.getString("password", ""); // } // // public Protocol getProtocol() { // return this.mProtocol; // } // // public void setProtocol(Protocol protocol) { // this.mProtocol = protocol; // } // // public void setProtocol(String protocol) { // this.mProtocol = Protocol.valueOf(protocol); // } // // public String getHost() { // return this.mHost; // } // // public void setHost(String host) { // this.mHost = host; // } // // public String getUserName() { // return this.mUserName; // } // // public void setUserName(String username) { // this.mUserName = username; // } // // public String getPassword() { // return this.mPassword; // } // // public void setPassword(String password) { // this.mPassword = password; // } // } // Path: src/org/androvoip/ui/Accounts.java import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import org.androvoip.R; import org.androvoip.Account; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2009, Jason Parker * * Jason Parker <north@ntbox.com> * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package org.androvoip.ui; public class Accounts extends ListActivity implements OnItemClickListener { private final String PREFS_FILE = "AndroVoIP_settings"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.accounts); ListView listView = getListView(); listView.setOnItemClickListener(this); listView.setEmptyView(findViewById(R.id.empty)); refresh(); } @Override public void onResume() { super.onResume(); refresh(); } private void refresh() {
Account[] accounts = new Account[1];
russellb/androvoip
src/com/mexuar/corraleta/protocol/ProtocolControlFrameNew.java
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // }
import com.mexuar.corraleta.audio.AudioInterface;
/* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.protocol; /** * Special cases for outbound 'New' messages. * * @author <a href="mailto:thp@westhawk.co.uk">Tim Panton</a> * @version $Revision: 1.19 $ $Date: 2006/11/14 16:46:37 $ */ class ProtocolControlFrameNew extends ProtocolControlFrame { /** * The outbound constructor. This sets the destination call number * to zero. * * @param p0 The Call object */ public ProtocolControlFrameNew(Call p0) { super(p0); _dCall = 0; _subclass = ProtocolControlFrame.NEW; this.setTimestampVal(0); _call.resetClock(); } /** * The inbound constructor. * * @param p0 The Call object * @param p1 The incoming message bytes */ public ProtocolControlFrameNew(Call p0, byte[] p1) { super(p0, p1); } /** * Returns if this is a NEW message. True by default. * * @return true if NEW, false otherwise */ public boolean isANew() { return true; } /** * Sends this NEW message. * * @param cno The source call number * @param username The username (sent in IE) * @param calledNo The number we're calling (sent in IE) * @param callingNo Number/extension we call from (sent in IE) * @param callingName Name of the person calling (sent in IE) */ /* IE that can be sent: - 8.6.1. CALLED NUMBER - 8.6.2. CALLING NUMBER - 8.6.3. CALLING ANI - 8.6.4. CALLING NAME - 8.6.5. CALLED CONTEXT - 8.6.6. USERNAME - 8.6.8. CAPABILITY - 8.6.9. FORMAT - 8.6.10. LANGUAGE - 8.6.11. VERSION (MUST, and should be first) - 8.6.12. ADSICPE - 8.6.13. DNID - 8.6.25. AUTOANSWER - 8.6.31. DATETIME - 8.6.38. CALLINGPRES - 8.6.39. CALLINGTON - 8.6.43. ENCRYPTION - 8.6.45. CODEC PREFS */ public void sendNew(Character cno, String username, String calledNo, String callingNo, String callingName) { Log.debug("ProtocolControlFrameNew.sendNew: calledNo=" + calledNo + ", callingNo=" + callingNo + ", callingName=" + callingName + ", username=" + username); _sCall = cno.charValue(); _iseq = _call.getIseq(); _oseq = _call.getOseqInc(); InfoElement ie = new InfoElement(); ie.calledNo = calledNo; ie.callingNo = callingNo; ie.callingName = callingName; ie.username = username;
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // Path: src/com/mexuar/corraleta/protocol/ProtocolControlFrameNew.java import com.mexuar.corraleta.audio.AudioInterface; /* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.protocol; /** * Special cases for outbound 'New' messages. * * @author <a href="mailto:thp@westhawk.co.uk">Tim Panton</a> * @version $Revision: 1.19 $ $Date: 2006/11/14 16:46:37 $ */ class ProtocolControlFrameNew extends ProtocolControlFrame { /** * The outbound constructor. This sets the destination call number * to zero. * * @param p0 The Call object */ public ProtocolControlFrameNew(Call p0) { super(p0); _dCall = 0; _subclass = ProtocolControlFrame.NEW; this.setTimestampVal(0); _call.resetClock(); } /** * The inbound constructor. * * @param p0 The Call object * @param p1 The incoming message bytes */ public ProtocolControlFrameNew(Call p0, byte[] p1) { super(p0, p1); } /** * Returns if this is a NEW message. True by default. * * @return true if NEW, false otherwise */ public boolean isANew() { return true; } /** * Sends this NEW message. * * @param cno The source call number * @param username The username (sent in IE) * @param calledNo The number we're calling (sent in IE) * @param callingNo Number/extension we call from (sent in IE) * @param callingName Name of the person calling (sent in IE) */ /* IE that can be sent: - 8.6.1. CALLED NUMBER - 8.6.2. CALLING NUMBER - 8.6.3. CALLING ANI - 8.6.4. CALLING NAME - 8.6.5. CALLED CONTEXT - 8.6.6. USERNAME - 8.6.8. CAPABILITY - 8.6.9. FORMAT - 8.6.10. LANGUAGE - 8.6.11. VERSION (MUST, and should be first) - 8.6.12. ADSICPE - 8.6.13. DNID - 8.6.25. AUTOANSWER - 8.6.31. DATETIME - 8.6.38. CALLINGPRES - 8.6.39. CALLINGTON - 8.6.43. ENCRYPTION - 8.6.45. CODEC PREFS */ public void sendNew(Character cno, String username, String calledNo, String callingNo, String callingName) { Log.debug("ProtocolControlFrameNew.sendNew: calledNo=" + calledNo + ", callingNo=" + callingNo + ", callingName=" + callingName + ", username=" + username); _sCall = cno.charValue(); _iseq = _call.getIseq(); _oseq = _call.getOseqInc(); InfoElement ie = new InfoElement(); ie.calledNo = calledNo; ie.callingNo = callingNo; ie.callingName = callingName; ie.username = username;
AudioInterface a = _call.getAudioFace();
russellb/androvoip
src/com/mexuar/corraleta/ui/BeanCanFrameManager.java
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // }
import java.net.*; import java.awt.event.*; import com.mexuar.corraleta.protocol.*; import com.mexuar.corraleta.protocol.netse.*; import com.mexuar.corraleta.audio.AudioInterface;
/* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.ui; /** * Place to put code specific to the protocol - allowing BeanCanFrame to * keep the UI code only * @author <a href="mailto:thp@westhawk.co.uk">Tim Panton</a> * @version $Revision: 1.24 $ $Date: 2006/11/14 16:46:37 $ * */ public class BeanCanFrameManager extends BeanCanFrame implements ProtocolEventListener, CallManager { private static final String version_id = "@(#)$Id: BeanCanFrameManager.java,v 1.24 2006/11/14 16:46:37 uid100 Exp $ Copyright Mexuar Technologies Ltd"; private Call _ca = null; private Friend _peer = null; private String _username = ""; private String _password = ""; private String _host = ""; private Binder _bind = null; private boolean _isApplet = false;
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // Path: src/com/mexuar/corraleta/ui/BeanCanFrameManager.java import java.net.*; import java.awt.event.*; import com.mexuar.corraleta.protocol.*; import com.mexuar.corraleta.protocol.netse.*; import com.mexuar.corraleta.audio.AudioInterface; /* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.ui; /** * Place to put code specific to the protocol - allowing BeanCanFrame to * keep the UI code only * @author <a href="mailto:thp@westhawk.co.uk">Tim Panton</a> * @version $Revision: 1.24 $ $Date: 2006/11/14 16:46:37 $ * */ public class BeanCanFrameManager extends BeanCanFrame implements ProtocolEventListener, CallManager { private static final String version_id = "@(#)$Id: BeanCanFrameManager.java,v 1.24 2006/11/14 16:46:37 uid100 Exp $ Copyright Mexuar Technologies Ltd"; private Call _ca = null; private Friend _peer = null; private String _username = ""; private String _password = ""; private String _host = ""; private Binder _bind = null; private boolean _isApplet = false;
private AudioInterface _audioBase = null;
russellb/androvoip
src/com/mexuar/corraleta/audio/dev/RawDev.java
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // // Path: src/com/mexuar/corraleta/protocol/AudioSender.java // public class AudioSender { // // private Call _call; // private int _formatBit; // private boolean _done = false; // private long _astart; // private long _cstart; // private long _nextdue; // private int _stamp; // private char _lastminisent; // private boolean _first; // private AudioInterface _aif; // private byte [] _buff; // // /** // * Constructor for the AudioSender object // * // * @param aif The audio interface // * @param ca The call object // */ // AudioSender(AudioInterface aif, Call ca) { // _call = ca; // _aif = aif; // _formatBit = aif.getFormatBit(); // _buff = new byte[_aif.getSampSz()]; // // _cstart = this._call.getTimestamp(); // _nextdue = _cstart; // _lastminisent = 0; // _first = true; // // } // // /** // * sending audio, using VoiceFrame and MiniFrame frames. // */ // public void send() throws IOException { // // if (!_done) { // // long stamp = _aif.readWithTime(_buff); // @SuppressWarnings("unused") // long now = stamp - _astart + _cstart; // _stamp = (int) _nextdue; // char mstamp = (char) (0xffff & _stamp); // if (_first || (mstamp < _lastminisent)) { // _first = false; // VoiceFrame vf = new VoiceFrame(_call); // vf._sCall = _call.getLno().charValue(); // vf._dCall = _call.getRno().charValue(); // vf.setTimestampVal(_stamp); // vf._subclass = _formatBit; // vf.sendMe(_buff); // Log.debug("sent Full voice frame"); // // send a full audio frame // } // else { // // send a miniframe // MiniFrame mf = new MiniFrame(_call); // mf._sCall = _call.getLno().charValue(); // mf.setTimestampVal(mstamp); // ? // mf.sendMe(_buff); // Log.verb("sent voice mini frame " + (int) (mstamp / 20)); // } // // eitherway note it down // _lastminisent = mstamp; // // now workout how long to wait... // _nextdue += 20; // // } // // } // // } // // Path: src/com/mexuar/corraleta/audio/SampleListener.java // public interface SampleListener { // public void setSampleValue(int sampleValue); // }
import com.mexuar.corraleta.audio.AudioInterface; import java.io.IOException; import com.mexuar.corraleta.protocol.AudioSender; import java.io.*; import com.mexuar.corraleta.audio.SampleListener;
/* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.audio.dev; public class RawDev implements AudioInterface , Runnable { InputStream _inS; OutputStream _outS; long _readTime = 0; boolean _playing;
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // // Path: src/com/mexuar/corraleta/protocol/AudioSender.java // public class AudioSender { // // private Call _call; // private int _formatBit; // private boolean _done = false; // private long _astart; // private long _cstart; // private long _nextdue; // private int _stamp; // private char _lastminisent; // private boolean _first; // private AudioInterface _aif; // private byte [] _buff; // // /** // * Constructor for the AudioSender object // * // * @param aif The audio interface // * @param ca The call object // */ // AudioSender(AudioInterface aif, Call ca) { // _call = ca; // _aif = aif; // _formatBit = aif.getFormatBit(); // _buff = new byte[_aif.getSampSz()]; // // _cstart = this._call.getTimestamp(); // _nextdue = _cstart; // _lastminisent = 0; // _first = true; // // } // // /** // * sending audio, using VoiceFrame and MiniFrame frames. // */ // public void send() throws IOException { // // if (!_done) { // // long stamp = _aif.readWithTime(_buff); // @SuppressWarnings("unused") // long now = stamp - _astart + _cstart; // _stamp = (int) _nextdue; // char mstamp = (char) (0xffff & _stamp); // if (_first || (mstamp < _lastminisent)) { // _first = false; // VoiceFrame vf = new VoiceFrame(_call); // vf._sCall = _call.getLno().charValue(); // vf._dCall = _call.getRno().charValue(); // vf.setTimestampVal(_stamp); // vf._subclass = _formatBit; // vf.sendMe(_buff); // Log.debug("sent Full voice frame"); // // send a full audio frame // } // else { // // send a miniframe // MiniFrame mf = new MiniFrame(_call); // mf._sCall = _call.getLno().charValue(); // mf.setTimestampVal(mstamp); // ? // mf.sendMe(_buff); // Log.verb("sent voice mini frame " + (int) (mstamp / 20)); // } // // eitherway note it down // _lastminisent = mstamp; // // now workout how long to wait... // _nextdue += 20; // // } // // } // // } // // Path: src/com/mexuar/corraleta/audio/SampleListener.java // public interface SampleListener { // public void setSampleValue(int sampleValue); // } // Path: src/com/mexuar/corraleta/audio/dev/RawDev.java import com.mexuar.corraleta.audio.AudioInterface; import java.io.IOException; import com.mexuar.corraleta.protocol.AudioSender; import java.io.*; import com.mexuar.corraleta.audio.SampleListener; /* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2006, Mexuar Technologies Ltd. * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package com.mexuar.corraleta.audio.dev; public class RawDev implements AudioInterface , Runnable { InputStream _inS; OutputStream _outS; long _readTime = 0; boolean _playing;
private AudioSender _as;
russellb/androvoip
src/com/mexuar/corraleta/audio/dev/RawDev.java
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // // Path: src/com/mexuar/corraleta/protocol/AudioSender.java // public class AudioSender { // // private Call _call; // private int _formatBit; // private boolean _done = false; // private long _astart; // private long _cstart; // private long _nextdue; // private int _stamp; // private char _lastminisent; // private boolean _first; // private AudioInterface _aif; // private byte [] _buff; // // /** // * Constructor for the AudioSender object // * // * @param aif The audio interface // * @param ca The call object // */ // AudioSender(AudioInterface aif, Call ca) { // _call = ca; // _aif = aif; // _formatBit = aif.getFormatBit(); // _buff = new byte[_aif.getSampSz()]; // // _cstart = this._call.getTimestamp(); // _nextdue = _cstart; // _lastminisent = 0; // _first = true; // // } // // /** // * sending audio, using VoiceFrame and MiniFrame frames. // */ // public void send() throws IOException { // // if (!_done) { // // long stamp = _aif.readWithTime(_buff); // @SuppressWarnings("unused") // long now = stamp - _astart + _cstart; // _stamp = (int) _nextdue; // char mstamp = (char) (0xffff & _stamp); // if (_first || (mstamp < _lastminisent)) { // _first = false; // VoiceFrame vf = new VoiceFrame(_call); // vf._sCall = _call.getLno().charValue(); // vf._dCall = _call.getRno().charValue(); // vf.setTimestampVal(_stamp); // vf._subclass = _formatBit; // vf.sendMe(_buff); // Log.debug("sent Full voice frame"); // // send a full audio frame // } // else { // // send a miniframe // MiniFrame mf = new MiniFrame(_call); // mf._sCall = _call.getLno().charValue(); // mf.setTimestampVal(mstamp); // ? // mf.sendMe(_buff); // Log.verb("sent voice mini frame " + (int) (mstamp / 20)); // } // // eitherway note it down // _lastminisent = mstamp; // // now workout how long to wait... // _nextdue += 20; // // } // // } // // } // // Path: src/com/mexuar/corraleta/audio/SampleListener.java // public interface SampleListener { // public void setSampleValue(int sampleValue); // }
import com.mexuar.corraleta.audio.AudioInterface; import java.io.IOException; import com.mexuar.corraleta.protocol.AudioSender; import java.io.*; import com.mexuar.corraleta.audio.SampleListener;
return com.mexuar.corraleta.protocol.VoiceFrame.ULAW_BIT; } /** * setAudioSender * * @param as AudioSender * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */ public void setAudioSender(AudioSender as) { _as = as; } /** * playAudioStream * * @param in InputStream * @throws IOException * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */ public void playAudioStream(InputStream in) throws IOException { } /** * sampleRecord * * @param list SampleListener * @throws IOException * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */
// Path: src/com/mexuar/corraleta/audio/AudioInterface.java // public interface AudioInterface { // /** // * Return the minimum sample size for use in creating buffers etc. // * @return int // */ // public int getSampSz() ; // // /** // * Read from the Microphone, using the buffer provided, // * but _only_ filling getSampSz() bytes. // * returns the timestamp of the sample from the audio clock. // * @param buff byte[] // * @return long // */ // public long readWithTime(byte[] buff) throws IOException ; // public long readDirect(byte[] buff) throws IOException ; // // /** // * stop the reccorder - but don't throw it away. // */ // public void stopRec() ; // // /** // * start the recorder // * returning the time... // */ // // public long startRec() ; // // /** // * The Audio properties have changed so attempt to // * re connect to a new device // */ // public void changedProps() ; // // /** // * Start the player // */ // public void startPlay() ; // // /** // * Stop the player // */ // public void stopPlay(); // // /** // * play the sample given (getSampSz() bytes) // * assuming that it's timestamp is long // * @param buff byte[] // * @param timestamp long // */ // // public void write(byte[] buff, long timestamp) throws IOException; // // public void writeDirect(byte[] buff) throws IOException; // // /** // * startRinging // */ // public void startRinging(); // // /** // * stopRinging // */ // public void stopRinging(); // public int getFormatBit(); // public void setAudioSender(com.mexuar.corraleta.protocol.AudioSender as); // // public void playAudioStream(java.io.InputStream in) throws IOException; // public void sampleRecord(SampleListener list) throws IOException; // public Integer supportedCodecs(); // public String codecPrefString(); // public void cleanUp(); // public AudioInterface getByFormat(Integer format); // } // // Path: src/com/mexuar/corraleta/protocol/AudioSender.java // public class AudioSender { // // private Call _call; // private int _formatBit; // private boolean _done = false; // private long _astart; // private long _cstart; // private long _nextdue; // private int _stamp; // private char _lastminisent; // private boolean _first; // private AudioInterface _aif; // private byte [] _buff; // // /** // * Constructor for the AudioSender object // * // * @param aif The audio interface // * @param ca The call object // */ // AudioSender(AudioInterface aif, Call ca) { // _call = ca; // _aif = aif; // _formatBit = aif.getFormatBit(); // _buff = new byte[_aif.getSampSz()]; // // _cstart = this._call.getTimestamp(); // _nextdue = _cstart; // _lastminisent = 0; // _first = true; // // } // // /** // * sending audio, using VoiceFrame and MiniFrame frames. // */ // public void send() throws IOException { // // if (!_done) { // // long stamp = _aif.readWithTime(_buff); // @SuppressWarnings("unused") // long now = stamp - _astart + _cstart; // _stamp = (int) _nextdue; // char mstamp = (char) (0xffff & _stamp); // if (_first || (mstamp < _lastminisent)) { // _first = false; // VoiceFrame vf = new VoiceFrame(_call); // vf._sCall = _call.getLno().charValue(); // vf._dCall = _call.getRno().charValue(); // vf.setTimestampVal(_stamp); // vf._subclass = _formatBit; // vf.sendMe(_buff); // Log.debug("sent Full voice frame"); // // send a full audio frame // } // else { // // send a miniframe // MiniFrame mf = new MiniFrame(_call); // mf._sCall = _call.getLno().charValue(); // mf.setTimestampVal(mstamp); // ? // mf.sendMe(_buff); // Log.verb("sent voice mini frame " + (int) (mstamp / 20)); // } // // eitherway note it down // _lastminisent = mstamp; // // now workout how long to wait... // _nextdue += 20; // // } // // } // // } // // Path: src/com/mexuar/corraleta/audio/SampleListener.java // public interface SampleListener { // public void setSampleValue(int sampleValue); // } // Path: src/com/mexuar/corraleta/audio/dev/RawDev.java import com.mexuar.corraleta.audio.AudioInterface; import java.io.IOException; import com.mexuar.corraleta.protocol.AudioSender; import java.io.*; import com.mexuar.corraleta.audio.SampleListener; return com.mexuar.corraleta.protocol.VoiceFrame.ULAW_BIT; } /** * setAudioSender * * @param as AudioSender * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */ public void setAudioSender(AudioSender as) { _as = as; } /** * playAudioStream * * @param in InputStream * @throws IOException * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */ public void playAudioStream(InputStream in) throws IOException { } /** * sampleRecord * * @param list SampleListener * @throws IOException * @todo Implement this com.mexuar.corraleta.audio.AudioInterface method */
public void sampleRecord(SampleListener list) throws IOException {
russellb/androvoip
src/org/androvoip/ui/Settings.java
// Path: src/org/androvoip/Account.java // public class Account implements Serializable { // private static final long serialVersionUID = 1539547929660026657L; // // public enum Protocol { // None, // IAX2, // }; // // Protocol mProtocol; // String mHost; // String mUserName; // String mPassword; // // public Account(SharedPreferences prefs) { // refresh(prefs); // } // // public void save(SharedPreferences prefs) { // Editor prefsEditor = prefs.edit(); // prefsEditor.putString("protocol", mProtocol.toString()); // prefsEditor.putString("host", mHost); // prefsEditor.putString("username", mUserName); // prefsEditor.putString("password", mPassword); // prefsEditor.commit(); // } // // public void refresh(SharedPreferences prefs) { // mProtocol = Protocol.valueOf(prefs.getString("protocol", "None")); // mHost = prefs.getString("host", ""); // mUserName = prefs.getString("username", ""); // mPassword = prefs.getString("password", ""); // } // // public Protocol getProtocol() { // return this.mProtocol; // } // // public void setProtocol(Protocol protocol) { // this.mProtocol = protocol; // } // // public void setProtocol(String protocol) { // this.mProtocol = Protocol.valueOf(protocol); // } // // public String getHost() { // return this.mHost; // } // // public void setHost(String host) { // this.mHost = host; // } // // public String getUserName() { // return this.mUserName; // } // // public void setUserName(String username) { // this.mUserName = username; // } // // public String getPassword() { // return this.mPassword; // } // // public void setPassword(String password) { // this.mPassword = password; // } // }
import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import org.androvoip.R; import org.androvoip.Account; import org.androvoip.iax2.IAX2ServiceAPI; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle;
/* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2009, Russell Bryant * * Russell Bryant <russell@russellbryant.net> * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package org.androvoip.ui; public class Settings extends Activity implements OnClickListener, ServiceConnection { public static final String PREFS_FILE = "AndroVoIP_settings"; private IAX2ServiceAPI serviceConnection = null;
// Path: src/org/androvoip/Account.java // public class Account implements Serializable { // private static final long serialVersionUID = 1539547929660026657L; // // public enum Protocol { // None, // IAX2, // }; // // Protocol mProtocol; // String mHost; // String mUserName; // String mPassword; // // public Account(SharedPreferences prefs) { // refresh(prefs); // } // // public void save(SharedPreferences prefs) { // Editor prefsEditor = prefs.edit(); // prefsEditor.putString("protocol", mProtocol.toString()); // prefsEditor.putString("host", mHost); // prefsEditor.putString("username", mUserName); // prefsEditor.putString("password", mPassword); // prefsEditor.commit(); // } // // public void refresh(SharedPreferences prefs) { // mProtocol = Protocol.valueOf(prefs.getString("protocol", "None")); // mHost = prefs.getString("host", ""); // mUserName = prefs.getString("username", ""); // mPassword = prefs.getString("password", ""); // } // // public Protocol getProtocol() { // return this.mProtocol; // } // // public void setProtocol(Protocol protocol) { // this.mProtocol = protocol; // } // // public void setProtocol(String protocol) { // this.mProtocol = Protocol.valueOf(protocol); // } // // public String getHost() { // return this.mHost; // } // // public void setHost(String host) { // this.mHost = host; // } // // public String getUserName() { // return this.mUserName; // } // // public void setUserName(String username) { // this.mUserName = username; // } // // public String getPassword() { // return this.mPassword; // } // // public void setPassword(String password) { // this.mPassword = password; // } // } // Path: src/org/androvoip/ui/Settings.java import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import org.androvoip.R; import org.androvoip.Account; import org.androvoip.iax2.IAX2ServiceAPI; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; /* * AndroVoIP -- VoIP for Android. * * Copyright (C), 2009, Russell Bryant * * Russell Bryant <russell@russellbryant.net> * * AndroVoIP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroVoIP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroVoIP. If not, see <http://www.gnu.org/licenses/>. */ package org.androvoip.ui; public class Settings extends Activity implements OnClickListener, ServiceConnection { public static final String PREFS_FILE = "AndroVoIP_settings"; private IAX2ServiceAPI serviceConnection = null;
private Account mAccount;
jsunsoftware/http-request
src/test/java/com/jsunsoft/http/ResponseBodyReaderTest.java
// Path: src/main/java/com/jsunsoft/http/BasicDateDeserializeContext.java // static final DateDeserializeContext DEFAULT = new BasicDateDeserializeContext("dd/MM/yyyy", "HH:mm:ss", "dd/MM/yyyy HH:mm:ss");
import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import static com.jsunsoft.http.BasicDateDeserializeContext.DEFAULT; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.joda.time.LocalDate; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream;
/* * Copyright 2017 Benik Arakelyan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jsunsoft.http; public class ResponseBodyReaderTest { private ResponseBodyReaderContext<Result> responseContext; @Before public final void before() throws UnsupportedEncodingException { String content = "{\n" + " \"value\": 1,\n" + " \"message\": \"Test message\",\n" + " \"relations\": [\n" + " {\n" + " \"string\": \"12345\",\n" + " \"localDate\": \"11/05/1993\"\n" + " },\n" + " {\n" + " \"string\": \"54321\",\n" + " \"javaLocalDate\": \"08/09/2017\"\n" + " }\n" + " ]\n" + " }"; InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8.name())); BasicHttpEntity basicHttpEntity = new BasicHttpEntity(); basicHttpEntity.setContent(inputStream); basicHttpEntity.setContentLength(content.length()); basicHttpEntity.setContentType(ContentType.APPLICATION_JSON.getMimeType()); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("", 1, 1), 200, "")); httpResponse.setEntity(basicHttpEntity); responseContext = new BasicResponseBodyReaderContext<>(httpResponse, Result.class, Result.class); } @Test public void testDeserializeResponse() throws IOException {
// Path: src/main/java/com/jsunsoft/http/BasicDateDeserializeContext.java // static final DateDeserializeContext DEFAULT = new BasicDateDeserializeContext("dd/MM/yyyy", "HH:mm:ss", "dd/MM/yyyy HH:mm:ss"); // Path: src/test/java/com/jsunsoft/http/ResponseBodyReaderTest.java import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import static com.jsunsoft.http.BasicDateDeserializeContext.DEFAULT; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.joda.time.LocalDate; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /* * Copyright 2017 Benik Arakelyan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jsunsoft.http; public class ResponseBodyReaderTest { private ResponseBodyReaderContext<Result> responseContext; @Before public final void before() throws UnsupportedEncodingException { String content = "{\n" + " \"value\": 1,\n" + " \"message\": \"Test message\",\n" + " \"relations\": [\n" + " {\n" + " \"string\": \"12345\",\n" + " \"localDate\": \"11/05/1993\"\n" + " },\n" + " {\n" + " \"string\": \"54321\",\n" + " \"javaLocalDate\": \"08/09/2017\"\n" + " }\n" + " ]\n" + " }"; InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8.name())); BasicHttpEntity basicHttpEntity = new BasicHttpEntity(); basicHttpEntity.setContent(inputStream); basicHttpEntity.setContentLength(content.length()); basicHttpEntity.setContentType(ContentType.APPLICATION_JSON.getMimeType()); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("", 1, 1), 200, "")); httpResponse.setEntity(basicHttpEntity); responseContext = new BasicResponseBodyReaderContext<>(httpResponse, Result.class, Result.class); } @Test public void testDeserializeResponse() throws IOException {
ResponseBodyReader<Result> responseBodyReader = new DefaultResponseBodyReader<>(DEFAULT);
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/junit/WithFsTestRunner.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/OSTest.java // public class OSTest { // public static boolean isWindows() { // return OS.isWindows(); // } // // public static boolean isMac() { // return OS.isMac(); // } // // public static boolean isUnix() { // return OS.isUnix(); // } // }
import java.io.IOException; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.junit.internal.runners.model.EachTestNotifier; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import com.github.sbridges.ephemeralfs.OSTest;
return; } } if (method.getAnnotation(IgnoreIfNoSymlink.class) != null) { List<FsType> ignoreTypes = Arrays.asList(FsType.WINDOWS); if(ignoreTypes.contains(type) || type == FsType.SYSTEM && ignoreTypes.contains(getNativeType())) { notifier.fireTestIgnored(description); return; } } try { super.runChild(method, notifier); } finally { if(cleanup != null) { try { cleanup.run(); } catch(Exception e) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.addFailure(e); } cleanup = null; } } } public static FsType getNativeType() {
// Path: src/test/java/com/github/sbridges/ephemeralfs/OSTest.java // public class OSTest { // public static boolean isWindows() { // return OS.isWindows(); // } // // public static boolean isMac() { // return OS.isMac(); // } // // public static boolean isUnix() { // return OS.isUnix(); // } // } // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/WithFsTestRunner.java import java.io.IOException; import java.lang.reflect.Field; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.junit.internal.runners.model.EachTestNotifier; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import com.github.sbridges.ephemeralfs.OSTest; return; } } if (method.getAnnotation(IgnoreIfNoSymlink.class) != null) { List<FsType> ignoreTypes = Arrays.asList(FsType.WINDOWS); if(ignoreTypes.contains(type) || type == FsType.SYSTEM && ignoreTypes.contains(getNativeType())) { notifier.fireTestIgnored(description); return; } } try { super.runChild(method, notifier); } finally { if(cleanup != null) { try { cleanup.run(); } catch(Exception e) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.addFailure(e); } cleanup = null; } } } public static FsType getNativeType() {
if(OSTest.isMac()) {
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/DosFileAttributesTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import static org.junit.Assert.*; import static org.junit.Assume.*; import java.io.IOException; import java.io.OutputStream; import java.nio.file.AccessDeniedException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.DosFileAttributes; import java.util.Arrays; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner;
}); } @Test public void testReadDos() throws Exception { DosFileAttributes attributes = Files.readAttributes(root, DosFileAttributes.class); assertNotNull(attributes); assertNotNull(attributes.creationTime()); } @Test public void testSetGetSystem() throws Exception { for(Path path : Arrays.asList( Files.createDirectory(root.resolve("dir")), Files.createFile(root.resolve("file")))) { DosFileAttributes attributes = Files.readAttributes(path, DosFileAttributes.class); assertFalse(attributes.isSystem()); DosFileAttributeView view = Files.getFileAttributeView(path, DosFileAttributeView.class); view.setSystem(true); attributes = Files.readAttributes(path, DosFileAttributes.class); assertTrue(attributes.isSystem()); } }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/DosFileAttributesTest.java import static org.junit.Assert.*; import static org.junit.Assume.*; import java.io.IOException; import java.io.OutputStream; import java.nio.file.AccessDeniedException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.DosFileAttributes; import java.util.Arrays; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; }); } @Test public void testReadDos() throws Exception { DosFileAttributes attributes = Files.readAttributes(root, DosFileAttributes.class); assertNotNull(attributes); assertNotNull(attributes.creationTime()); } @Test public void testSetGetSystem() throws Exception { for(Path path : Arrays.asList( Files.createDirectory(root.resolve("dir")), Files.createFile(root.resolve("file")))) { DosFileAttributes attributes = Files.readAttributes(path, DosFileAttributes.class); assertFalse(attributes.isSystem()); DosFileAttributeView view = Files.getFileAttributeView(path, DosFileAttributeView.class); view.setSystem(true); attributes = Files.readAttributes(path, DosFileAttributes.class); assertTrue(attributes.isSystem()); } }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/LinkTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.junit.Assert.*; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotLinkException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner;
@Test public void testCreateSymLinkFileAlreadyExists() throws Exception { Path real = root.resolve("real"); Path link = root.resolve("link"); Files.createFile(real); try { Files.createSymbolicLink(real, link.getFileName()); fail(); } catch(FileAlreadyExistsException e) { //pass } } @IgnoreIfNoSymlink @Test public void testCreateFileSymLinkAlreadyExists() throws Exception { Path real = root.resolve("real"); Path link = root.resolve("link"); Files.createSymbolicLink(real, link.getFileName()); try { Files.createFile(real); fail(); } catch(FileAlreadyExistsException e) { //pass } }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/LinkTest.java import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.junit.Assert.*; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotLinkException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; @Test public void testCreateSymLinkFileAlreadyExists() throws Exception { Path real = root.resolve("real"); Path link = root.resolve("link"); Files.createFile(real); try { Files.createSymbolicLink(real, link.getFileName()); fail(); } catch(FileAlreadyExistsException e) { //pass } } @IgnoreIfNoSymlink @Test public void testCreateFileSymLinkAlreadyExists() throws Exception { Path real = root.resolve("real"); Path link = root.resolve("link"); Files.createSymbolicLink(real, link.getFileName()); try { Files.createFile(real); fail(); } catch(FileAlreadyExistsException e) { //pass } }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/DirectoryWalkTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.util.Iterator; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException;
//pass } } @Test public void testGetAttributesThenMoveFile() throws Exception { long start = System.currentTimeMillis(); Path parent = root.resolve("test"); Files.createFile(parent); BasicFileAttributeView attributes = Files.getFileAttributeView(parent, BasicFileAttributeView.class); assertTrue(attributes.readAttributes().creationTime().toMillis() > start - 6000); Files.move(parent, parent.resolveSibling("test2")); try { attributes.readAttributes(); fail(); } catch(NoSuchFileException e) { //pass } } @Test public void testCreateFile() throws Exception { Path child = Files.createFile(root.resolve("test")); assertTrue(Files.exists(child)); assertFalse(Files.isDirectory(child)); }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/DirectoryWalkTest.java import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.util.Iterator; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; //pass } } @Test public void testGetAttributesThenMoveFile() throws Exception { long start = System.currentTimeMillis(); Path parent = root.resolve("test"); Files.createFile(parent); BasicFileAttributeView attributes = Files.getFileAttributeView(parent, BasicFileAttributeView.class); assertTrue(attributes.readAttributes().creationTime().toMillis() > start - 6000); Files.move(parent, parent.resolveSibling("test2")); try { attributes.readAttributes(); fail(); } catch(NoSuchFileException e) { //pass } } @Test public void testCreateFile() throws Exception { Path child = Files.createFile(root.resolve("test")); assertTrue(Files.exists(child)); assertFalse(Files.isDirectory(child)); }
@IgnoreUnless(FsType.UNIX)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/DotsInFileNamesTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*;
//pass } } @Test public void testListWithDot() throws Exception { Path testFile = root.resolve("test"); Files.createFile(testFile); Path withDot = root.resolve("."); TestUtil.assertChildren( withDot, withDot.resolve("test")); } @Test public void testListFileWithDotDot() throws Exception { Path testFile = root.resolve("test"); Files.createFile(testFile); Files.createDirectory(root.resolve("foo")); Path withDotDot = root.resolve("foo").resolve(".."); TestUtil.assertChildren( withDotDot, withDotDot.resolve("test"), withDotDot.resolve("foo")); }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/DotsInFileNamesTest.java import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; //pass } } @Test public void testListWithDot() throws Exception { Path testFile = root.resolve("test"); Files.createFile(testFile); Path withDot = root.resolve("."); TestUtil.assertChildren( withDot, withDot.resolve("test")); } @Test public void testListFileWithDotDot() throws Exception { Path testFile = root.resolve("test"); Files.createFile(testFile); Files.createDirectory(root.resolve("foo")); Path withDotDot = root.resolve("foo").resolve(".."); TestUtil.assertChildren( withDotDot, withDotDot.resolve("test"), withDotDot.resolve("foo")); }
@IgnoreUnless(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/OSTest.java
// Path: src/main/java/com/github/sbridges/ephemeralfs/OS.java // final class OS { // // private static final boolean isWindows; // private static final boolean isMac; // // static { // String osName = System.getProperty("os.name"); // isWindows = osName.toLowerCase(Locale.ENGLISH).contains("windows"); // isMac = osName.contains("OS X"); // } // // public static boolean isWindows() { // return isWindows; // } // // public static boolean isMac() { // return isMac; // } // // public static boolean isUnix() { // //cause, like, what else is there // return !isWindows() && !isMac(); // } // }
import com.github.sbridges.ephemeralfs.OS;
/* * Copyright 2015 Sean Bridges. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * * */ package com.github.sbridges.ephemeralfs; /** * A hack to expose OS which is package level to test code in * different packages */ public class OSTest { public static boolean isWindows() {
// Path: src/main/java/com/github/sbridges/ephemeralfs/OS.java // final class OS { // // private static final boolean isWindows; // private static final boolean isMac; // // static { // String osName = System.getProperty("os.name"); // isWindows = osName.toLowerCase(Locale.ENGLISH).contains("windows"); // isMac = osName.contains("OS X"); // } // // public static boolean isWindows() { // return isWindows; // } // // public static boolean isMac() { // return isMac; // } // // public static boolean isUnix() { // //cause, like, what else is there // return !isWindows() && !isMac(); // } // } // Path: src/test/java/com/github/sbridges/ephemeralfs/OSTest.java import com.github.sbridges.ephemeralfs.OS; /* * Copyright 2015 Sean Bridges. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * * */ package com.github.sbridges.ephemeralfs; /** * A hack to expose OS which is package level to test code in * different packages */ public class OSTest { public static boolean isWindows() {
return OS.isWindows();
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/MoveTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*;
assertTrue(Files.exists(target.resolve("aFile"))); } @Test public void testDirMoveFailsExistingFile() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path target = Files.createDirectory(root.resolve("targetDir")); try { Files.move(sourceDir, target); fail(); } catch(FileAlreadyExistsException e) { //pass } } @Test public void testDirMoveAlreadyExists() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path targetDir = Files.createDirectory(root.resolve("targetDir")); Files.move(sourceDir, targetDir, StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.exists(targetDir.resolve("aFile"))); }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/MoveTest.java import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; assertTrue(Files.exists(target.resolve("aFile"))); } @Test public void testDirMoveFailsExistingFile() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path target = Files.createDirectory(root.resolve("targetDir")); try { Files.move(sourceDir, target); fail(); } catch(FileAlreadyExistsException e) { //pass } } @Test public void testDirMoveAlreadyExists() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path targetDir = Files.createDirectory(root.resolve("targetDir")); Files.move(sourceDir, targetDir, StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.exists(targetDir.resolve("aFile"))); }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/BasicFileAttributesTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.EnumSet; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner;
fail(); } catch(NoSuchFileException e) { //ignore } } @Test public void testCheckAccessNonExistent() throws Exception { Path path = root.resolve("path"); assertFalse(Files.isReadable(path)); assertFalse(Files.isWritable(path)); assertFalse(Files.exists(path)); assertFalse(Files.exists(path, LinkOption.NOFOLLOW_LINKS)); assertFalse(Files.isExecutable(path)); } @Test public void testCheckAccessDir() throws Exception { Path path = root.resolve("path"); Files.createDirectory(path); assertTrue(Files.isReadable(path)); assertTrue(Files.isWritable(path)); assertTrue(Files.exists(path)); assertTrue(Files.exists(path, LinkOption.NOFOLLOW_LINKS)); assertTrue(Files.isExecutable(path)); }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/BasicFileAttributesTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.EnumSet; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; fail(); } catch(NoSuchFileException e) { //ignore } } @Test public void testCheckAccessNonExistent() throws Exception { Path path = root.resolve("path"); assertFalse(Files.isReadable(path)); assertFalse(Files.isWritable(path)); assertFalse(Files.exists(path)); assertFalse(Files.exists(path, LinkOption.NOFOLLOW_LINKS)); assertFalse(Files.isExecutable(path)); } @Test public void testCheckAccessDir() throws Exception { Path path = root.resolve("path"); Files.createDirectory(path); assertTrue(Files.isReadable(path)); assertTrue(Files.isWritable(path)); assertTrue(Files.exists(path)); assertTrue(Files.exists(path, LinkOption.NOFOLLOW_LINKS)); assertTrue(Files.isExecutable(path)); }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/DirectoryStreamTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/TestUtil.java // public static void assertFound(DirectoryStream<Path> stream, Path...paths) throws IOException { // try { // // Set<Path> actual = new HashSet<>(); // Set<Path> expected = new HashSet<>(); // for(Path p : stream) { // if(!actual.add(p)) { // throw new AssertionError("dupe"); // } // } // for(Path p : paths) { // if(!expected.add(p)) { // throw new AssertionError("dupe"); // } // } // // assertEquals(expected, actual); // } finally { // if(stream != null) { // stream.close(); // } // } // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import static org.junit.Assert.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.util.Iterator; import java.util.NoSuchElementException; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static com.github.sbridges.ephemeralfs.TestUtil.assertFound;
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { stream.iterator(); try { stream.iterator(); fail(); } catch(IllegalStateException e) { //pass } } } @Test public void testCanDeleteDirWithOpenDirStraem() throws Exception { Path dir = root.resolve("dir"); Files.createDirectories(dir); Path child = dir.resolve("child"); Files.createDirectories(child); try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { Files.delete(child); assertFalse(Files.exists(child)); Files.delete(dir); } }
// Path: src/test/java/com/github/sbridges/ephemeralfs/TestUtil.java // public static void assertFound(DirectoryStream<Path> stream, Path...paths) throws IOException { // try { // // Set<Path> actual = new HashSet<>(); // Set<Path> expected = new HashSet<>(); // for(Path p : stream) { // if(!actual.add(p)) { // throw new AssertionError("dupe"); // } // } // for(Path p : paths) { // if(!expected.add(p)) { // throw new AssertionError("dupe"); // } // } // // assertEquals(expected, actual); // } finally { // if(stream != null) { // stream.close(); // } // } // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/DirectoryStreamTest.java import static org.junit.Assert.*; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.util.Iterator; import java.util.NoSuchElementException; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static com.github.sbridges.ephemeralfs.TestUtil.assertFound; try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { stream.iterator(); try { stream.iterator(); fail(); } catch(IllegalStateException e) { //pass } } } @Test public void testCanDeleteDirWithOpenDirStraem() throws Exception { Path dir = root.resolve("dir"); Files.createDirectories(dir); Path child = dir.resolve("child"); Files.createDirectories(child); try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { Files.delete(child); assertFalse(Files.exists(child)); Files.delete(dir); } }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/PathTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*;
public void testDotAndDotDotInFileNameCompare() throws Exception { assertFalse( root.resolve("a").resolve("..").resolve("b").equals( root.resolve("a").resolve("b")) ); assertFalse( root.resolve("a").resolve("..").resolve("b").equals( root.resolve("b")) ); } @Test public void testNormalizeMultipleDotDots() { FileSystem fs = root.getFileSystem(); assertEquals(fs.getPath("../.."), fs.getPath("../..").normalize()); assertEquals(fs.getPath("../.."), fs.getPath(".././..").normalize()); assertEquals(fs.getPath("../../a/b/c"), fs.getPath("../../a/b/c").normalize()); assertEquals(fs.getPath("../../a/b"), fs.getPath("../../a/b/c/..").normalize()); assertEquals(fs.getPath("../../a/b"), fs.getPath("../../a/b/c/./..").normalize()); } @Test public void testResolveRootRelative() { FileSystem fs = root.getFileSystem(); assertFalse(fs.getPath("").isAbsolute()); assertFalse(fs.getPath("").resolve("a").isAbsolute()); }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/PathTest.java import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; public void testDotAndDotDotInFileNameCompare() throws Exception { assertFalse( root.resolve("a").resolve("..").resolve("b").equals( root.resolve("a").resolve("b")) ); assertFalse( root.resolve("a").resolve("..").resolve("b").equals( root.resolve("b")) ); } @Test public void testNormalizeMultipleDotDots() { FileSystem fs = root.getFileSystem(); assertEquals(fs.getPath("../.."), fs.getPath("../..").normalize()); assertEquals(fs.getPath("../.."), fs.getPath(".././..").normalize()); assertEquals(fs.getPath("../../a/b/c"), fs.getPath("../../a/b/c").normalize()); assertEquals(fs.getPath("../../a/b"), fs.getPath("../../a/b/c/..").normalize()); assertEquals(fs.getPath("../../a/b"), fs.getPath("../../a/b/c/./..").normalize()); } @Test public void testResolveRootRelative() { FileSystem fs = root.getFileSystem(); assertFalse(fs.getPath("").isAbsolute()); assertFalse(fs.getPath("").resolve("a").isAbsolute()); }
@IgnoreIf(FsType.WINDOWS)
sbridges/ephemeralfs
src/test/java/com/github/sbridges/ephemeralfs/CopyTest.java
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // }
import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Random; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*;
Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.exists(dest)); assertTrue(Files.isDirectory(dest)); assertTrue(Files.exists(source)); } @Test public void testCopyDirDoesNotCopyChildren() throws Exception { Path source = root.resolve("source"); Path child = source.resolve("child"); Path dest = root.resolve("dest"); Files.createDirectories(source); Files.createFile(child); Files.copy(source, dest); assertTrue(Files.isDirectory(dest)); //files are not copied with the directory try(DirectoryStream<Path> stream = Files.newDirectoryStream(dest)) { assertFalse(stream.iterator().hasNext()); } }
// Path: src/test/java/com/github/sbridges/ephemeralfs/junit/FsType.java // public enum FsType { // // UNIX { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.unixFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // WINDOWS { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.windowsFs().build(); // return fs.getRootDirectories().iterator().next(); // } // // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // MAC { // @Override // public Path createTestRoot(Class testKlass) { // FileSystem fs = EphemeralFsFileSystemBuilder.macFs().build(); // return fs.getRootDirectories().iterator().next(); // } // @Override // public void cleanUpRoot(Path root) throws IOException { // root.getFileSystem().close(); // } // }, // SYSTEM { // @Override // public Path createTestRoot(Class testKlass) { // try { // File tempDir = Files.createTempDirectory(testKlass.getSimpleName()).toFile(); // tempDir = tempDir.getCanonicalFile(); // return tempDir.toPath(); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // // @Override // public void cleanUpRoot(Path root) { // TestUtil.deleteTempDirRecursive(root); // // } // // @Override // public String toString() { // if(OSTest.isMac()) { // return "SYSTEM-MAC"; // } // if(OSTest.isWindows()) { // return "SYSTEM-WINDOWS"; // } // if(OSTest.isUnix()) { // return "SYSTEM-UNIX"; // } // throw new IllegalStateException(); // } // }; // // public abstract void cleanUpRoot(Path root) throws IOException; // public abstract Path createTestRoot(Class testKlass); // // // } // // Path: src/test/java/com/github/sbridges/ephemeralfs/junit/MultiFsRunner.java // public class MultiFsRunner extends ParentRunner<Runner> { // // private final List<Runner> children; // // public MultiFsRunner(Class<?> testClass) throws InitializationError { // super(testClass); // children = new ArrayList<>(); // // EnumSet<FsType> validTypes = EnumSet.allOf(FsType.class); // if(testClass.getAnnotation(RunWithTypes.class) != null ) { // validTypes.clear(); // List<FsType> allowedTypes = Arrays.asList(testClass.getAnnotation(RunWithTypes.class).value()); // validTypes.addAll(allowedTypes); // if(validTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.add(FsType.SYSTEM); // } // } // if(testClass.getAnnotation(RunUnlessType.class) != null ) { // // List<FsType> dissallowedTypes = Arrays.asList(testClass.getAnnotation(RunUnlessType.class).value()); // validTypes.removeAll(dissallowedTypes); // // if(dissallowedTypes.contains(WithFsTestRunner.getNativeType())) { // validTypes.remove(FsType.SYSTEM); // } // } // // for(FsType type : validTypes) { // children.add(new WithFsTestRunner(testClass, type)); // } // } // // @Override // protected List<Runner> getChildren() { // return children; // } // // @Override // protected Description describeChild(Runner child) { // return child.getDescription(); // } // // @Override // protected void runChild(Runner child, RunNotifier notifier) { // child.run(notifier); // } // // // // // } // Path: src/test/java/com/github/sbridges/ephemeralfs/CopyTest.java import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Random; import org.junit.Test; import org.junit.runner.RunWith; import com.github.sbridges.ephemeralfs.junit.FsType; import com.github.sbridges.ephemeralfs.junit.IgnoreIf; import com.github.sbridges.ephemeralfs.junit.IgnoreIfNoSymlink; import com.github.sbridges.ephemeralfs.junit.IgnoreUnless; import com.github.sbridges.ephemeralfs.junit.MultiFsRunner; import static org.junit.Assert.*; Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.exists(dest)); assertTrue(Files.isDirectory(dest)); assertTrue(Files.exists(source)); } @Test public void testCopyDirDoesNotCopyChildren() throws Exception { Path source = root.resolve("source"); Path child = source.resolve("child"); Path dest = root.resolve("dest"); Files.createDirectories(source); Files.createFile(child); Files.copy(source, dest); assertTrue(Files.isDirectory(dest)); //files are not copied with the directory try(DirectoryStream<Path> stream = Files.newDirectoryStream(dest)) { assertFalse(stream.iterator().hasNext()); } }
@IgnoreUnless(FsType.WINDOWS)
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/ClassInjector.java // public class ClassInjector implements ResourceBundle { // // private WeakReference<CtClass> ctClass; // private WeakReference<ClassPool> pool; // // public ClassInjector(CtClass ctClass, ClassPool pool) { // this.ctClass = new WeakReference<>(ctClass); // this.pool = new WeakReference<>(pool); // } // // public InterfaceInjector insertInterface() { // return new InterfaceInjector(this); // } // // public FieldInjector insertField(Class type, String name) { // return insertField(type.getCanonicalName(), name); // } // // public FieldInjector insertField(String type, String name) { // return new FieldInjector(this, type, name); // } // // public MethodInjector insertMethod(String methodName) { // return insertMethod(methodName, new String[0]); // } // // public MethodInjector insertMethod(String methodName, Class... parameters) { // String[] parametersName = new String[parameters.length]; // for (int i = 0; i < parametersName.length; i++) { // parametersName[i] = parameters[i].getCanonicalName(); // } // return insertMethod(methodName, parametersName); // } // // public MethodInjector insertMethod(String methodName, String... parameters) { // return new MethodInjector(this, methodName, parameters); // } // // @Override // public CtClass getCtClass() { // return ctClass.get(); // } // // @Override // public ClassPool getPool() { // return pool.get(); // } // }
import javassist.ClassPool; import javassist.CtClass; import weaver.instrumentation.injection.ClassInjector;
package weaver.instrumentation; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class Instrumentation { private ClassPool pool; public Instrumentation(ClassPool pool) { this.pool = pool; }
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/ClassInjector.java // public class ClassInjector implements ResourceBundle { // // private WeakReference<CtClass> ctClass; // private WeakReference<ClassPool> pool; // // public ClassInjector(CtClass ctClass, ClassPool pool) { // this.ctClass = new WeakReference<>(ctClass); // this.pool = new WeakReference<>(pool); // } // // public InterfaceInjector insertInterface() { // return new InterfaceInjector(this); // } // // public FieldInjector insertField(Class type, String name) { // return insertField(type.getCanonicalName(), name); // } // // public FieldInjector insertField(String type, String name) { // return new FieldInjector(this, type, name); // } // // public MethodInjector insertMethod(String methodName) { // return insertMethod(methodName, new String[0]); // } // // public MethodInjector insertMethod(String methodName, Class... parameters) { // String[] parametersName = new String[parameters.length]; // for (int i = 0; i < parametersName.length; i++) { // parametersName[i] = parameters[i].getCanonicalName(); // } // return insertMethod(methodName, parametersName); // } // // public MethodInjector insertMethod(String methodName, String... parameters) { // return new MethodInjector(this, methodName, parameters); // } // // @Override // public CtClass getCtClass() { // return ctClass.get(); // } // // @Override // public ClassPool getPool() { // return pool.get(); // } // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java import javassist.ClassPool; import javassist.CtClass; import weaver.instrumentation.injection.ClassInjector; package weaver.instrumentation; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class Instrumentation { private ClassPool pool; public Instrumentation(ClassPool pool) { this.pool = pool; }
public ClassInjector startWeaving(CtClass ctClass) {
SaeedMasoumi/Weaver
weaver-instrumentation/src/test/java/weaver/instrumentation/test/weaving/method/MethodExistsButNotOverrideTest.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public final class InternalUtils { // // static boolean hasInterface(CtClass ctClass, CtClass givenInterface) throws // NotFoundException { // for (CtClass interfaceClass : ctClass.getInterfaces()) { // if (givenInterface.getName().equals(interfaceClass.getName())) return true; // } // return false; // } // // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // static boolean sameSignature(List<String> parameters, CtMethod method) // throws NotFoundException { // CtClass[] methodParameters = method.getParameterTypes(); // if (methodParameters.length == 0 && parameters.size() == 0) return true; // if (methodParameters.length != 0 && parameters.size() == 0) return false; // if (methodParameters.length == 0 && parameters.size() != 0) return false; // for (CtClass clazz : method.getParameterTypes()) { // if (!parameters.contains(clazz.getName())) return false; // } // return true; // } // // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // } // } // // Path: weaver-instrumentation/src/test/java/weaver/instrumentation/test/weaving/WeavingSpec.java // public abstract class WeavingSpec { // // protected Instrumentation instrumentation; // protected CtClass ctClass; // // @Before // public void initClassPool() throws NotFoundException { // ClassPool pool = ClassPool.getDefault(); // instrumentation = new Instrumentation(pool); // ctClass = pool.get(getSampleClassName()); // ctClass.setName(ctClass.getName() + getTransformedName()); // } // // protected abstract String getSampleClassName(); // // protected abstract String getTransformedName(); // // protected <T> T invokeMethod(Class<T> returnType, String methodName, // Object instance) { // return invokeMethod(returnType, methodName, instance, null, null); // } // // protected <T> T invokeMethod(Class<T> returnType, String methodName, // Object instance, Class<?>[] params,Object[] args) { // try { // Method method = instance.getClass().getMethod(methodName, params); // method.setAccessible(true); // return (T) method.invoke(instance, args); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // return null; // } // // @After // public void storeCtClass() throws CannotCompileException, IOException { // ctClass.writeFile(getClass().getResource("/").getPath()); // } // }
import org.junit.Test; import javassist.CtMethod; import javassist.Modifier; import weaver.instrumentation.injection.InternalUtils; import weaver.instrumentation.test.weaving.WeavingSpec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
.addModifiers(Modifier.PRIVATE) .inject() //override onResume .insertMethod("onResume", Bundle.class) .ifExistsButNotOverride() .override("{" + "System.out.println(\"before super\");" + "super.onResume($$);" + "System.out.println(\"after super \"+delegate);\n" + "}") .inject() .inject() //override on pause .insertMethod("onPause") .ifExistsButNotOverride() .override("{" + "return 10;" + "}") .inject() .inject() //override on stop .insertMethod("onStop") .ifExistsButNotOverride() .override("{" + "return super.onStop();" + "}") .inject() .inject() ;
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public final class InternalUtils { // // static boolean hasInterface(CtClass ctClass, CtClass givenInterface) throws // NotFoundException { // for (CtClass interfaceClass : ctClass.getInterfaces()) { // if (givenInterface.getName().equals(interfaceClass.getName())) return true; // } // return false; // } // // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // static boolean sameSignature(List<String> parameters, CtMethod method) // throws NotFoundException { // CtClass[] methodParameters = method.getParameterTypes(); // if (methodParameters.length == 0 && parameters.size() == 0) return true; // if (methodParameters.length != 0 && parameters.size() == 0) return false; // if (methodParameters.length == 0 && parameters.size() != 0) return false; // for (CtClass clazz : method.getParameterTypes()) { // if (!parameters.contains(clazz.getName())) return false; // } // return true; // } // // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // } // } // // Path: weaver-instrumentation/src/test/java/weaver/instrumentation/test/weaving/WeavingSpec.java // public abstract class WeavingSpec { // // protected Instrumentation instrumentation; // protected CtClass ctClass; // // @Before // public void initClassPool() throws NotFoundException { // ClassPool pool = ClassPool.getDefault(); // instrumentation = new Instrumentation(pool); // ctClass = pool.get(getSampleClassName()); // ctClass.setName(ctClass.getName() + getTransformedName()); // } // // protected abstract String getSampleClassName(); // // protected abstract String getTransformedName(); // // protected <T> T invokeMethod(Class<T> returnType, String methodName, // Object instance) { // return invokeMethod(returnType, methodName, instance, null, null); // } // // protected <T> T invokeMethod(Class<T> returnType, String methodName, // Object instance, Class<?>[] params,Object[] args) { // try { // Method method = instance.getClass().getMethod(methodName, params); // method.setAccessible(true); // return (T) method.invoke(instance, args); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // return null; // } // // @After // public void storeCtClass() throws CannotCompileException, IOException { // ctClass.writeFile(getClass().getResource("/").getPath()); // } // } // Path: weaver-instrumentation/src/test/java/weaver/instrumentation/test/weaving/method/MethodExistsButNotOverrideTest.java import org.junit.Test; import javassist.CtMethod; import javassist.Modifier; import weaver.instrumentation.injection.InternalUtils; import weaver.instrumentation.test.weaving.WeavingSpec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; .addModifiers(Modifier.PRIVATE) .inject() //override onResume .insertMethod("onResume", Bundle.class) .ifExistsButNotOverride() .override("{" + "System.out.println(\"before super\");" + "super.onResume($$);" + "System.out.println(\"after super \"+delegate);\n" + "}") .inject() .inject() //override on pause .insertMethod("onPause") .ifExistsButNotOverride() .override("{" + "return 10;" + "}") .inject() .inject() //override on stop .insertMethod("onStop") .ifExistsButNotOverride() .override("{" + "return super.onStop();" + "}") .inject() .inject() ;
CtMethod onResumeMethod = InternalUtils.findMethod("onResume",
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // }
import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER;
package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception {
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER; package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception {
CtMethod[] allMethods = getAllMethods(getCtClass());
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // }
import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER;
package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass());
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER; package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass());
CtMethod[] declaredMethods = getDeclaredMethods(getCtClass());
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // }
import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER;
package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass()); CtMethod[] declaredMethods = getDeclaredMethods(getCtClass());
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER; package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class MethodInjector extends BaseInjector<ClassInjector> { private String methodName; private String[] parameters = null; private MethodInjectorExistsMode existsMode = null; private MethodInjectorOverrideMode overrideMode = null; private MethodInjectorNotExistsMode notExistsMode = null; MethodInjector(ClassInjector classInjector, String methodName, String[] parameters) { super(classInjector); this.methodName = methodName; this.parameters = parameters; } public MethodInjectorExistsMode ifExists() { existsMode = new MethodInjectorExistsMode(this); return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass()); CtMethod[] declaredMethods = getDeclaredMethods(getCtClass());
CtMethod methodInParent = findMethod(methodName, parameters, allMethods);
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // }
import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER;
return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass()); CtMethod[] declaredMethods = getDeclaredMethods(getCtClass()); CtMethod methodInParent = findMethod(methodName, parameters, allMethods); CtMethod methodInClass = findMethod(methodName, parameters, declaredMethods); //method not exists CtMethod method = null; if (methodInParent == null && methodInClass == null && notExistsMode != null) { method = CtNewMethod.make(notExistsMode.getFullMethod(), getCtClass()); } //if method exists but not override else if (methodInParent != null && methodInClass == null && overrideMode != null) { method = CtNewMethod.make(methodInParent.getReturnType(), methodInParent.getName(), methodInParent.getParameterTypes(), methodInParent.getExceptionTypes(), overrideMode.getFullMethod(), getCtClass());
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // public static CtMethod findMethod(String methodName, String[] parameters, // CtMethod[] allMethods) throws NotFoundException { // List<String> paramsList = Arrays.asList(parameters); // for (CtMethod method : allMethods) { // if (method.getName().equals(methodName) && sameSignature(paramsList, method)) { // return method; // } // } // return null; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getAllMethods(CtClass ctClass) { // return ctClass.getMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static CtMethod[] getDeclaredMethods(CtClass ctClass) { // return ctClass.getDeclaredMethods(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/MethodInjector.java import java.util.ArrayList; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import static weaver.instrumentation.injection.InternalUtils.findMethod; import static weaver.instrumentation.injection.InternalUtils.getAllMethods; import static weaver.instrumentation.injection.InternalUtils.getDeclaredMethods; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AFTER_SUPER; import static weaver.instrumentation.injection.MethodInjectionMode.AROUND_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_BEGINNING; import static weaver.instrumentation.injection.MethodInjectionMode.AT_THE_END; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_A_CALL; import static weaver.instrumentation.injection.MethodInjectionMode.BEFORE_SUPER; return existsMode; } public MethodInjectorOverrideMode ifExistsButNotOverride() { overrideMode = new MethodInjectorOverrideMode(this); return overrideMode; } public MethodInjectorNotExistsMode createIfNotExists() { notExistsMode = new MethodInjectorNotExistsMode(this); return notExistsMode; } @Override public ClassInjector inject() throws Exception { CtMethod[] allMethods = getAllMethods(getCtClass()); CtMethod[] declaredMethods = getDeclaredMethods(getCtClass()); CtMethod methodInParent = findMethod(methodName, parameters, allMethods); CtMethod methodInClass = findMethod(methodName, parameters, declaredMethods); //method not exists CtMethod method = null; if (methodInParent == null && methodInClass == null && notExistsMode != null) { method = CtNewMethod.make(notExistsMode.getFullMethod(), getCtClass()); } //if method exists but not override else if (methodInParent != null && methodInClass == null && overrideMode != null) { method = CtNewMethod.make(methodInParent.getReturnType(), methodInParent.getName(), methodInParent.getParameterTypes(), methodInParent.getExceptionTypes(), overrideMode.getFullMethod(), getCtClass());
method.setModifiers(methodInParent.getModifiers() & ~Modifier.ABSTRACT);
SaeedMasoumi/Weaver
weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // }
import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation;
package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment;
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // } // Path: weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation; package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment;
protected Logger logger;
SaeedMasoumi/Weaver
weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // }
import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation;
package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment; protected Logger logger;
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // } // Path: weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation; package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment; protected Logger logger;
protected Instrumentation instrumentation;
SaeedMasoumi/Weaver
weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // }
import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation;
package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment; protected Logger logger; protected Instrumentation instrumentation; private String outputPath; /** * {@inheritDoc} */ public synchronized void init(WeaveEnvironment env) { weaveEnvironment = env; logger = env.getLogger(); instrumentation = new Instrumentation(env.getClassPool()); try { outputPath = weaveEnvironment.getOutputDir().getCanonicalPath(); } catch (IOException e) { outputPath = weaveEnvironment.getOutputDir().getAbsolutePath(); } } /** * {@inheritDoc} */ @Override
// Path: weaver-common/src/main/java/weaver/common/Logger.java // public interface Logger { // // /** // * To see your debug messages run your gradle task with -d option. // * // * @param message the log message. // */ // void debug(String message); // // /** // * To see your quiet messages run your gradle task with -q option. // * // * @param message the log message. // */ // void quiet(String message); // // /** // * To see your info messages run your gradle task with -i option. // * // * @param message the log message. // */ // void info(String message); // // /** // * Log a message at the WARN level. // * // * @param message the log message. // */ // void warning(String message); // // } // // Path: weaver-common/src/main/java/weaver/common/Processor.java // public interface Processor { // // /** // * Initializes the processor with the weave environment. // * // * @param processingEnvironment Weave environment for processor. // */ // void init(WeaveEnvironment processingEnvironment); // // /** // * Weaver plugin will call this method for all defined processors, it gives all classes // * <p> // * Transformation can be confirmed by calling {@linkplain #writeClass(CtClass)}. // * // * @param candidateClasses All classes from project source set. // * @throws Exception Throws if an error occurred during bytecode manipulation. // */ // void transform(Set<? extends CtClass> candidateClasses) throws Exception; // // /** // * Specifies which classes should be transformed, for example by returning {@link Scope#PROJECT} // * all classes from source set will be passed to {@link #transform(Set)}. // * // * @return Returns the scope. // */ // Scope getScope(); // // /** // * @return // */ // String getName(); // // /** // * Call this method to store manipulated class otherwise your source will not take effect. // * <p> // * Note: No need to call this method, if you are using android transform API. // * // * @param candidateClass Given {@link CtClass}. // * @return Returns true, if writes successfully the <code>CtClass</code> in the proper directory // * otherwise returns false. // */ // boolean writeClass(CtClass candidateClass); // } // // Path: weaver-common/src/main/java/weaver/common/Scope.java // public enum Scope { // PROJECT // } // // Path: weaver-common/src/main/java/weaver/common/WeaveEnvironment.java // public interface WeaveEnvironment { // // /** // * @return Returns the logger. // */ // Logger getLogger(); // // /** // * @return Returns the ClassPool. // */ // ClassPool getClassPool(); // // /** // * @return Returns the output directory which contains all transformed classes. // */ // File getOutputDir(); // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/Instrumentation.java // public class Instrumentation { // private ClassPool pool; // // public Instrumentation(ClassPool pool) { // this.pool = pool; // } // // public ClassInjector startWeaving(CtClass ctClass) { // return new ClassInjector(ctClass, pool); // } // // } // Path: weaver-processor/src/main/java/weaver/processor/WeaverProcessor.java import java.io.IOException; import javassist.CannotCompileException; import javassist.CtClass; import weaver.common.Logger; import weaver.common.Processor; import weaver.common.Scope; import weaver.common.WeaveEnvironment; import weaver.instrumentation.Instrumentation; package weaver.processor; /** * A concrete implementation of {@link Processor}. It also provides {@link Instrumentation} utilities. * * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class WeaverProcessor implements Processor { protected WeaveEnvironment weaveEnvironment; protected Logger logger; protected Instrumentation instrumentation; private String outputPath; /** * {@inheritDoc} */ public synchronized void init(WeaveEnvironment env) { weaveEnvironment = env; logger = env.getLogger(); instrumentation = new Instrumentation(env.getClassPool()); try { outputPath = weaveEnvironment.getOutputDir().getCanonicalPath(); } catch (IOException e) { outputPath = weaveEnvironment.getOutputDir().getAbsolutePath(); } } /** * {@inheritDoc} */ @Override
public Scope getScope() {
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InterfaceInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static boolean hasInterface(CtClass ctClass, CtClass givenInterface) throws // NotFoundException { // for (CtClass interfaceClass : ctClass.getInterfaces()) { // if (givenInterface.getName().equals(interfaceClass.getName())) return true; // } // return false; // }
import java.lang.reflect.Modifier; import java.util.ArrayList; import javassist.CtClass; import static weaver.instrumentation.injection.InternalUtils.hasInterface;
package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class InterfaceInjector extends BaseInjector<ClassInjector> { private ArrayList<String> qualifiedNames = new ArrayList<>(); InterfaceInjector(ClassInjector classInjector) { super(classInjector); } public InterfaceInjector implement(String fullQualifiedName) { if (!qualifiedNames.contains(fullQualifiedName)) { qualifiedNames.add(fullQualifiedName); } return this; } public InterfaceInjector implement(Class clazz) { return implement(clazz.getCanonicalName()); } @Override public ClassInjector inject() throws Exception { //TODO check modifiers, e.g. different package names with private modifiers is not allowed. CtClass ctClass = getCtClass(); for (String qualifiedName : qualifiedNames) { CtClass interfaceCtClass = getPool().get(qualifiedName); if (!Modifier.isInterface(interfaceCtClass.getModifiers())) { throw new Exception("InterfaceWeaver: Tried to weave " + interfaceCtClass.getName() + " but it's not an interface. "); }
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static boolean hasInterface(CtClass ctClass, CtClass givenInterface) throws // NotFoundException { // for (CtClass interfaceClass : ctClass.getInterfaces()) { // if (givenInterface.getName().equals(interfaceClass.getName())) return true; // } // return false; // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InterfaceInjector.java import java.lang.reflect.Modifier; import java.util.ArrayList; import javassist.CtClass; import static weaver.instrumentation.injection.InternalUtils.hasInterface; package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class InterfaceInjector extends BaseInjector<ClassInjector> { private ArrayList<String> qualifiedNames = new ArrayList<>(); InterfaceInjector(ClassInjector classInjector) { super(classInjector); } public InterfaceInjector implement(String fullQualifiedName) { if (!qualifiedNames.contains(fullQualifiedName)) { qualifiedNames.add(fullQualifiedName); } return this; } public InterfaceInjector implement(Class clazz) { return implement(clazz.getCanonicalName()); } @Override public ClassInjector inject() throws Exception { //TODO check modifiers, e.g. different package names with private modifiers is not allowed. CtClass ctClass = getCtClass(); for (String qualifiedName : qualifiedNames) { CtClass interfaceCtClass = getPool().get(qualifiedName); if (!Modifier.isInterface(interfaceCtClass.getModifiers())) { throw new Exception("InterfaceWeaver: Tried to weave " + interfaceCtClass.getName() + " but it's not an interface. "); }
if (!hasInterface(ctClass, interfaceCtClass)) {
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/FieldInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // }
import javassist.CtClass; import javassist.CtField; import javassist.CtNewMethod; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.InternalUtils.capitalize;
package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class FieldInjector extends BaseInjector<ClassInjector> { private int modifiers = 0; private String fieldTypeQualifiedName; private String fieldName; private boolean instantiateIt = false; private boolean addSetter = false; private boolean addGetter = false; private String instantiateValue = ""; FieldInjector(ClassInjector classInjector, String type, String fieldName) { super(classInjector); this.fieldTypeQualifiedName = type; this.fieldName = fieldName; } public FieldInjector addModifiers(int... modifiers) {
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/FieldInjector.java import javassist.CtClass; import javassist.CtField; import javassist.CtNewMethod; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.InternalUtils.capitalize; package weaver.instrumentation.injection; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public class FieldInjector extends BaseInjector<ClassInjector> { private int modifiers = 0; private String fieldTypeQualifiedName; private String fieldName; private boolean instantiateIt = false; private boolean addSetter = false; private boolean addGetter = false; private String instantiateValue = ""; FieldInjector(ClassInjector classInjector, String type, String fieldName) { super(classInjector); this.fieldTypeQualifiedName = type; this.fieldName = fieldName; } public FieldInjector addModifiers(int... modifiers) {
this.modifiers = getModifiers(this.modifiers, modifiers);
SaeedMasoumi/Weaver
weaver-instrumentation/src/main/java/weaver/instrumentation/injection/FieldInjector.java
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // }
import javassist.CtClass; import javassist.CtField; import javassist.CtNewMethod; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.InternalUtils.capitalize;
addGetter = true; return this; } public FieldInjector initializeIt() { this.instantiateIt = true; return this; } public FieldInjector withInitializer(String value) { this.instantiateValue = value; return this; } @Override public ClassInjector inject() throws Exception { CtClass fieldType = getPool().get(fieldTypeQualifiedName); CtClass ctClass = getCtClass(); //TODO skip if field already exists CtField field = new CtField(fieldType, fieldName, ctClass); field.setModifiers(modifiers); if (!instantiateValue.isEmpty()) { ctClass.addField(field, instantiateValue); } else if (instantiateIt) { ctClass.addField(field, "new " + fieldTypeQualifiedName + "()"); } else { ctClass.addField(field); } if (addSetter) {
// Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static int getModifiers(int defaultModifier, int... newModifiers) { // for (int m : newModifiers) defaultModifier |= m; // return defaultModifier; // } // // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/InternalUtils.java // static String capitalize(final String line) { // return Character.toUpperCase(line.charAt(0)) + line.substring(1); // } // Path: weaver-instrumentation/src/main/java/weaver/instrumentation/injection/FieldInjector.java import javassist.CtClass; import javassist.CtField; import javassist.CtNewMethod; import static weaver.instrumentation.injection.InternalUtils.getModifiers; import static weaver.instrumentation.injection.InternalUtils.capitalize; addGetter = true; return this; } public FieldInjector initializeIt() { this.instantiateIt = true; return this; } public FieldInjector withInitializer(String value) { this.instantiateValue = value; return this; } @Override public ClassInjector inject() throws Exception { CtClass fieldType = getPool().get(fieldTypeQualifiedName); CtClass ctClass = getCtClass(); //TODO skip if field already exists CtField field = new CtField(fieldType, fieldName, ctClass); field.setModifiers(modifiers); if (!instantiateValue.isEmpty()) { ctClass.addField(field, instantiateValue); } else if (instantiateIt) { ctClass.addField(field, "new " + fieldTypeQualifiedName + "()"); } else { ctClass.addField(field); } if (addSetter) {
ctClass.addMethod(CtNewMethod.setter("set" + capitalize(fieldName), field));
JeffLi1993/springboot-learning-example
springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler {
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler {
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
public Mono<City> save(City city) {
JeffLi1993/springboot-learning-example
springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.domain.City; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong;
package org.spring.springboot.dao; @Repository public class CityRepository {
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java import org.spring.springboot.domain.City; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; package org.spring.springboot.dao; @Repository public class CityRepository {
private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>();
JeffLi1993/springboot-learning-example
springboot-webflux-9-test/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-9-test/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
private CityHandler cityHandler;
JeffLi1993/springboot-learning-example
springboot-webflux-9-test/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}")
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-9-test/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
private CityHandler cityHandler;
JeffLi1993/springboot-learning-example
springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}") @ResponseBody
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}") @ResponseBody
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/impl/BookServiceImpl.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/BookRepository.java // public interface BookRepository extends JpaRepository<Book, Long> { // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.domain.BookRepository; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;
package demo.springboot.service.impl; /** * Book 业务层实现 * * Created by bysocket on 30/09/2017. */ @Service public class BookServiceImpl implements BookService { @Autowired
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/BookRepository.java // public interface BookRepository extends JpaRepository<Book, Long> { // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/impl/BookServiceImpl.java import demo.springboot.domain.Book; import demo.springboot.domain.BookRepository; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; package demo.springboot.service.impl; /** * Book 业务层实现 * * Created by bysocket on 30/09/2017. */ @Service public class BookServiceImpl implements BookService { @Autowired
BookRepository bookRepository;
JeffLi1993/springboot-learning-example
chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/impl/BookServiceImpl.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/BookRepository.java // public interface BookRepository extends JpaRepository<Book, Long> { // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.domain.BookRepository; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;
package demo.springboot.service.impl; /** * Book 业务层实现 * * Created by bysocket on 30/09/2017. */ @Service public class BookServiceImpl implements BookService { @Autowired BookRepository bookRepository; @Override
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/BookRepository.java // public interface BookRepository extends JpaRepository<Book, Long> { // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/impl/BookServiceImpl.java import demo.springboot.domain.Book; import demo.springboot.domain.BookRepository; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; package demo.springboot.service.impl; /** * Book 业务层实现 * * Created by bysocket on 30/09/2017. */ @Service public class BookServiceImpl implements BookService { @Autowired BookRepository bookRepository; @Override
public List<Book> findAll() {
JeffLi1993/springboot-learning-example
springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler {
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler {
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
public Mono<Long> save(City city) {
JeffLi1993/springboot-learning-example
springboot-hbase/src/main/java/org/spring/springboot/service/impl/CityServiceImpl.java
// Path: springboot-hbase/src/main/java/org/spring/springboot/dao/CityRowMapper.java // public class CityRowMapper implements RowMapper<City> { // // private static byte[] COLUMN_FAMILY = "f".getBytes(); // private static byte[] NAME = "name".getBytes(); // private static byte[] AGE = "age".getBytes(); // // @Override // public City mapRow(Result result, int rowNum) throws Exception { // String name = Bytes.toString(result.getValue(COLUMN_FAMILY, NAME)); // int age = Bytes.toInt(result.getValue(COLUMN_FAMILY, AGE)); // // City dto = new City(); // dto.setCityName(name); // dto.setAge(age); // return dto; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.spring.springboot.dao.CityRowMapper; import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
package org.spring.springboot.service.impl; /** * 城市业务逻辑实现类 * <p> * Created by bysocket on 07/02/2017. */ @Service public class CityServiceImpl implements CityService { @Autowired private HbaseTemplate hbaseTemplate;
// Path: springboot-hbase/src/main/java/org/spring/springboot/dao/CityRowMapper.java // public class CityRowMapper implements RowMapper<City> { // // private static byte[] COLUMN_FAMILY = "f".getBytes(); // private static byte[] NAME = "name".getBytes(); // private static byte[] AGE = "age".getBytes(); // // @Override // public City mapRow(Result result, int rowNum) throws Exception { // String name = Bytes.toString(result.getValue(COLUMN_FAMILY, NAME)); // int age = Bytes.toInt(result.getValue(COLUMN_FAMILY, AGE)); // // City dto = new City(); // dto.setCityName(name); // dto.setAge(age); // return dto; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: springboot-hbase/src/main/java/org/spring/springboot/service/impl/CityServiceImpl.java import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.spring.springboot.dao.CityRowMapper; import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; package org.spring.springboot.service.impl; /** * 城市业务逻辑实现类 * <p> * Created by bysocket on 07/02/2017. */ @Service public class CityServiceImpl implements CityService { @Autowired private HbaseTemplate hbaseTemplate;
public List<City> query(String startRow, String stopRow) {
JeffLi1993/springboot-learning-example
springboot-hbase/src/main/java/org/spring/springboot/service/impl/CityServiceImpl.java
// Path: springboot-hbase/src/main/java/org/spring/springboot/dao/CityRowMapper.java // public class CityRowMapper implements RowMapper<City> { // // private static byte[] COLUMN_FAMILY = "f".getBytes(); // private static byte[] NAME = "name".getBytes(); // private static byte[] AGE = "age".getBytes(); // // @Override // public City mapRow(Result result, int rowNum) throws Exception { // String name = Bytes.toString(result.getValue(COLUMN_FAMILY, NAME)); // int age = Bytes.toInt(result.getValue(COLUMN_FAMILY, AGE)); // // City dto = new City(); // dto.setCityName(name); // dto.setAge(age); // return dto; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.spring.springboot.dao.CityRowMapper; import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
package org.spring.springboot.service.impl; /** * 城市业务逻辑实现类 * <p> * Created by bysocket on 07/02/2017. */ @Service public class CityServiceImpl implements CityService { @Autowired private HbaseTemplate hbaseTemplate; public List<City> query(String startRow, String stopRow) { Scan scan = new Scan(Bytes.toBytes(startRow), Bytes.toBytes(stopRow)); scan.setCaching(5000);
// Path: springboot-hbase/src/main/java/org/spring/springboot/dao/CityRowMapper.java // public class CityRowMapper implements RowMapper<City> { // // private static byte[] COLUMN_FAMILY = "f".getBytes(); // private static byte[] NAME = "name".getBytes(); // private static byte[] AGE = "age".getBytes(); // // @Override // public City mapRow(Result result, int rowNum) throws Exception { // String name = Bytes.toString(result.getValue(COLUMN_FAMILY, NAME)); // int age = Bytes.toInt(result.getValue(COLUMN_FAMILY, AGE)); // // City dto = new City(); // dto.setCityName(name); // dto.setAge(age); // return dto; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: springboot-hbase/src/main/java/org/spring/springboot/service/impl/CityServiceImpl.java import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.spring.springboot.dao.CityRowMapper; import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; package org.spring.springboot.service.impl; /** * 城市业务逻辑实现类 * <p> * Created by bysocket on 07/02/2017. */ @Service public class CityServiceImpl implements CityService { @Autowired private HbaseTemplate hbaseTemplate; public List<City> query(String startRow, String stopRow) { Scan scan = new Scan(Bytes.toBytes(startRow), Bytes.toBytes(stopRow)); scan.setCaching(5000);
List<City> dtos = this.hbaseTemplate.find("people_table", scan, new CityRowMapper());
JeffLi1993/springboot-learning-example
chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/impl/UserServiceImpl.java
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // } // // Path: chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/UserService.java // public interface UserService { // // /** // * 获取用户分页列表 // * // * @param pageable // * @return // */ // Page<User> findByPage(Pageable pageable); // // /** // * 新增用户 // * // * @param user // * @return // */ // User insertByUser(User user); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import spring.boot.core.domain.User; import spring.boot.core.domain.UserRepository; import spring.boot.core.service.UserService;
package spring.boot.core.service.impl; /** * User 业务层实现 * * Created by bysocket on 18/09/2017. */ @Service public class UserServiceImpl implements UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired UserRepository userRepository; @Override
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // } // // Path: chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/UserService.java // public interface UserService { // // /** // * 获取用户分页列表 // * // * @param pageable // * @return // */ // Page<User> findByPage(Pageable pageable); // // /** // * 新增用户 // * // * @param user // * @return // */ // User insertByUser(User user); // } // Path: chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/impl/UserServiceImpl.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import spring.boot.core.domain.User; import spring.boot.core.domain.UserRepository; import spring.boot.core.service.UserService; package spring.boot.core.service.impl; /** * User 业务层实现 * * Created by bysocket on 18/09/2017. */ @Service public class UserServiceImpl implements UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired UserRepository userRepository; @Override
public Page<User> findByPage(Pageable pageable) {
JeffLi1993/springboot-learning-example
springboot-webflux-6-redis/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private RedisTemplate redisTemplate; @GetMapping(value = "/{id}")
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-6-redis/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private RedisTemplate redisTemplate; @GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
springboot-webflux-7-redis-cache/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class); @Autowired private RedisTemplate redisTemplate;
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-7-redis-cache/src/main/java/org/spring/springboot/handler/CityHandler.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class); @Autowired private RedisTemplate redisTemplate;
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-7-redis-cache/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class); @Autowired private RedisTemplate redisTemplate; private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-7-redis-cache/src/main/java/org/spring/springboot/handler/CityHandler.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CityHandler.class); @Autowired private RedisTemplate redisTemplate; private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
public Mono<City> save(City city) {
JeffLi1993/springboot-learning-example
springboot-webflux-9-test/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler {
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-9-test/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler {
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-9-test/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-9-test/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
public Mono<City> save(City city) {
JeffLi1993/springboot-learning-example
springboot-webflux-2-restful/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-2-restful/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
private CityHandler cityHandler;
JeffLi1993/springboot-learning-example
springboot-webflux-2-restful/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}")
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-2-restful/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
springboot-hbase/src/main/java/org/spring/springboot/controller/CityRestController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package org.spring.springboot.controller; /** * Created by bysocket on 07/02/2017. */ @RestController public class CityRestController { @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: springboot-hbase/src/main/java/org/spring/springboot/controller/CityRestController.java import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package org.spring.springboot.controller; /** * Created by bysocket on 07/02/2017. */ @RestController public class CityRestController { @Autowired
private CityService cityService;
JeffLi1993/springboot-learning-example
springboot-hbase/src/main/java/org/spring/springboot/controller/CityRestController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package org.spring.springboot.controller; /** * Created by bysocket on 07/02/2017. */ @RestController public class CityRestController { @Autowired private CityService cityService; @RequestMapping(value = "/api/city/save", method = RequestMethod.GET)
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: springboot-hbase/src/main/java/org/spring/springboot/controller/CityRestController.java import org.spring.springboot.domain.City; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package org.spring.springboot.controller; /** * Created by bysocket on 07/02/2017. */ @RestController public class CityRestController { @Autowired private CityService cityService; @RequestMapping(value = "/api/city/save", method = RequestMethod.GET)
public City save() {
JeffLi1993/springboot-learning-example
spring-data-elasticsearch-query/src/main/java/org/spring/springboot/service/impl/CityESServiceImpl.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: spring-data-elasticsearch-crud/src/main/java/org/spring/springboot/repository/CityRepository.java // public interface CityRepository extends ElasticsearchRepository<City, Long> { // /** // * AND 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionAndScore(String description, Integer score); // // /** // * OR 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionOrScore(String description, Integer score); // // /** // * 查询城市描述 // * // * 等同于下面代码 // * @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}") // * Page<City> findByDescription(String description, Pageable pageable); // * // * @param description // * @param page // * @return // */ // Page<City> findByDescription(String description, Pageable page); // // /** // * NOT 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionNot(String description, Pageable page); // // /** // * LIKE 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionLike(String description, Pageable page); // // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.domain.City; import org.spring.springboot.repository.CityRepository; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.stereotype.Service; import java.util.List;
package org.spring.springboot.service.impl; /** * 城市 ES 业务逻辑实现类 * <p> * Created by bysocket on 20/06/2017. */ @Service public class CityESServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); /* 分页参数 */ Integer PAGE_SIZE = 12; // 每页数量 Integer DEFAULT_PAGE_NUMBER = 0; // 默认当前页码 /* 搜索模式 */ String SCORE_MODE_SUM = "sum"; // 权重分求和模式 Float MIN_SCORE = 10.0F; // 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: spring-data-elasticsearch-crud/src/main/java/org/spring/springboot/repository/CityRepository.java // public interface CityRepository extends ElasticsearchRepository<City, Long> { // /** // * AND 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionAndScore(String description, Integer score); // // /** // * OR 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionOrScore(String description, Integer score); // // /** // * 查询城市描述 // * // * 等同于下面代码 // * @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}") // * Page<City> findByDescription(String description, Pageable pageable); // * // * @param description // * @param page // * @return // */ // Page<City> findByDescription(String description, Pageable page); // // /** // * NOT 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionNot(String description, Pageable page); // // /** // * LIKE 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionLike(String description, Pageable page); // // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: spring-data-elasticsearch-query/src/main/java/org/spring/springboot/service/impl/CityESServiceImpl.java import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.domain.City; import org.spring.springboot.repository.CityRepository; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.stereotype.Service; import java.util.List; package org.spring.springboot.service.impl; /** * 城市 ES 业务逻辑实现类 * <p> * Created by bysocket on 20/06/2017. */ @Service public class CityESServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); /* 分页参数 */ Integer PAGE_SIZE = 12; // 每页数量 Integer DEFAULT_PAGE_NUMBER = 0; // 默认当前页码 /* 搜索模式 */ String SCORE_MODE_SUM = "sum"; // 权重分求和模式 Float MIN_SCORE = 10.0F; // 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 @Autowired
CityRepository cityRepository; // ES 操作类
JeffLi1993/springboot-learning-example
spring-data-elasticsearch-query/src/main/java/org/spring/springboot/service/impl/CityESServiceImpl.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: spring-data-elasticsearch-crud/src/main/java/org/spring/springboot/repository/CityRepository.java // public interface CityRepository extends ElasticsearchRepository<City, Long> { // /** // * AND 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionAndScore(String description, Integer score); // // /** // * OR 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionOrScore(String description, Integer score); // // /** // * 查询城市描述 // * // * 等同于下面代码 // * @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}") // * Page<City> findByDescription(String description, Pageable pageable); // * // * @param description // * @param page // * @return // */ // Page<City> findByDescription(String description, Pageable page); // // /** // * NOT 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionNot(String description, Pageable page); // // /** // * LIKE 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionLike(String description, Pageable page); // // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // }
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.domain.City; import org.spring.springboot.repository.CityRepository; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.stereotype.Service; import java.util.List;
package org.spring.springboot.service.impl; /** * 城市 ES 业务逻辑实现类 * <p> * Created by bysocket on 20/06/2017. */ @Service public class CityESServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); /* 分页参数 */ Integer PAGE_SIZE = 12; // 每页数量 Integer DEFAULT_PAGE_NUMBER = 0; // 默认当前页码 /* 搜索模式 */ String SCORE_MODE_SUM = "sum"; // 权重分求和模式 Float MIN_SCORE = 10.0F; // 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 @Autowired CityRepository cityRepository; // ES 操作类
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: spring-data-elasticsearch-crud/src/main/java/org/spring/springboot/repository/CityRepository.java // public interface CityRepository extends ElasticsearchRepository<City, Long> { // /** // * AND 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionAndScore(String description, Integer score); // // /** // * OR 语句查询 // * // * @param description // * @param score // * @return // */ // List<City> findByDescriptionOrScore(String description, Integer score); // // /** // * 查询城市描述 // * // * 等同于下面代码 // * @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}") // * Page<City> findByDescription(String description, Pageable pageable); // * // * @param description // * @param page // * @return // */ // Page<City> findByDescription(String description, Pageable page); // // /** // * NOT 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionNot(String description, Pageable page); // // /** // * LIKE 语句查询 // * // * @param description // * @param page // * @return // */ // Page<City> findByDescriptionLike(String description, Pageable page); // // } // // Path: springboot-hbase/src/main/java/org/spring/springboot/service/CityService.java // public interface CityService { // // List<City> query(String startRow, String stopRow); // // public City query(String row); // // void saveOrUpdate(); // } // Path: spring-data-elasticsearch-query/src/main/java/org/spring/springboot/service/impl/CityESServiceImpl.java import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spring.springboot.domain.City; import org.spring.springboot.repository.CityRepository; import org.spring.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.stereotype.Service; import java.util.List; package org.spring.springboot.service.impl; /** * 城市 ES 业务逻辑实现类 * <p> * Created by bysocket on 20/06/2017. */ @Service public class CityESServiceImpl implements CityService { private static final Logger LOGGER = LoggerFactory.getLogger(CityESServiceImpl.class); /* 分页参数 */ Integer PAGE_SIZE = 12; // 每页数量 Integer DEFAULT_PAGE_NUMBER = 0; // 默认当前页码 /* 搜索模式 */ String SCORE_MODE_SUM = "sum"; // 权重分求和模式 Float MIN_SCORE = 10.0F; // 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 @Autowired CityRepository cityRepository; // ES 操作类
public Long saveCity(City city) {
JeffLi1993/springboot-learning-example
chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/web/BookController.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*;
package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 30/09/2017. */ @Controller @RequestMapping(value = "/book") public class BookController { private static final String BOOK_FORM_PATH_NAME = "bookForm"; private static final String BOOK_LIST_PATH_NAME = "bookList"; private static final String REDIRECT_TO_BOOK_URL = "redirect:/book"; @Autowired
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/web/BookController.java import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 30/09/2017. */ @Controller @RequestMapping(value = "/book") public class BookController { private static final String BOOK_FORM_PATH_NAME = "bookForm"; private static final String BOOK_LIST_PATH_NAME = "bookList"; private static final String REDIRECT_TO_BOOK_URL = "redirect:/book"; @Autowired
BookService bookService;
JeffLi1993/springboot-learning-example
chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/web/BookController.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*;
package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 30/09/2017. */ @Controller @RequestMapping(value = "/book") public class BookController { private static final String BOOK_FORM_PATH_NAME = "bookForm"; private static final String BOOK_LIST_PATH_NAME = "bookList"; private static final String REDIRECT_TO_BOOK_URL = "redirect:/book"; @Autowired BookService bookService; /** * 获取 Book 列表 * 处理 "/book" 的 GET 请求,用来获取 Book 列表 */ @RequestMapping(method = RequestMethod.GET) public String getBookList(ModelMap map) { map.addAttribute("bookList",bookService.findAll()); return BOOK_LIST_PATH_NAME; } /** * 获取创建 Book 表单 */ @RequestMapping(value = "/create", method = RequestMethod.GET) public String createBookForm(ModelMap map) {
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/web/BookController.java import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 30/09/2017. */ @Controller @RequestMapping(value = "/book") public class BookController { private static final String BOOK_FORM_PATH_NAME = "bookForm"; private static final String BOOK_LIST_PATH_NAME = "bookList"; private static final String REDIRECT_TO_BOOK_URL = "redirect:/book"; @Autowired BookService bookService; /** * 获取 Book 列表 * 处理 "/book" 的 GET 请求,用来获取 Book 列表 */ @RequestMapping(method = RequestMethod.GET) public String getBookList(ModelMap map) { map.addAttribute("bookList",bookService.findAll()); return BOOK_LIST_PATH_NAME; } /** * 获取创建 Book 表单 */ @RequestMapping(value = "/create", method = RequestMethod.GET) public String createBookForm(ModelMap map) {
map.addAttribute("book", new Book());
JeffLi1993/springboot-learning-example
2-x-spring-boot-webflux-handling-errors/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: 2-x-spring-boot-webflux-handling-errors/src/main/java/org/spring/springboot/error/GlobalException.java // public class GlobalException extends ResponseStatusException { // // public GlobalException(HttpStatus status, String message) { // super(status, message); // } // // public GlobalException(HttpStatus status, String message, Throwable e) { // super(status, message, e); // } // }
import org.spring.springboot.error.GlobalException; import org.springframework.http.HttpStatus; 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; import java.util.Optional;
package org.spring.springboot.handler; @Component public class CityHandler { public Mono<ServerResponse> helloCity(ServerRequest request) { return ServerResponse.ok().body(sayHelloCity(request), String.class); } private Mono<String> sayHelloCity(ServerRequest request) { Optional<String> cityParamOptional = request.queryParam("city"); if (!cityParamOptional.isPresent()) {
// Path: 2-x-spring-boot-webflux-handling-errors/src/main/java/org/spring/springboot/error/GlobalException.java // public class GlobalException extends ResponseStatusException { // // public GlobalException(HttpStatus status, String message) { // super(status, message); // } // // public GlobalException(HttpStatus status, String message, Throwable e) { // super(status, message, e); // } // } // Path: 2-x-spring-boot-webflux-handling-errors/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.error.GlobalException; import org.springframework.http.HttpStatus; 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; import java.util.Optional; package org.spring.springboot.handler; @Component public class CityHandler { public Mono<ServerResponse> helloCity(ServerRequest request) { return ServerResponse.ok().body(sayHelloCity(request), String.class); } private Mono<String> sayHelloCity(ServerRequest request) { Optional<String> cityParamOptional = request.queryParam("city"); if (!cityParamOptional.isPresent()) {
throw new GlobalException(HttpStatus.INTERNAL_SERVER_ERROR, "request param city is ERROR");
JeffLi1993/springboot-learning-example
chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import spring.boot.core.domain.User; import spring.boot.core.domain.UserRepository;
package spring.boot.core; @SpringBootApplication public class ValidatingFormInputApplication implements CommandLineRunner { private Logger LOG = LoggerFactory.getLogger(ValidatingFormInputApplication.class); @Autowired private UserRepository userRepository; public static void main(String[] args) { SpringApplication.run(ValidatingFormInputApplication.class, args); } @Override public void run(String... args) throws Exception {
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // } // Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/ValidatingFormInputApplication.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import spring.boot.core.domain.User; import spring.boot.core.domain.UserRepository; package spring.boot.core; @SpringBootApplication public class ValidatingFormInputApplication implements CommandLineRunner { private Logger LOG = LoggerFactory.getLogger(ValidatingFormInputApplication.class); @Autowired private UserRepository userRepository; public static void main(String[] args) { SpringApplication.run(ValidatingFormInputApplication.class, args); } @Override public void run(String... args) throws Exception {
User user1 = new User("Sergey", 24, "1994-01-01");
JeffLi1993/springboot-learning-example
chapter-3-spring-boot-web/src/test/java/demo/springboot/web/BookControllerTest.java
// Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/WebApplication.java // @SpringBootApplication // public class WebApplication { // public static void main(String[] args) { // SpringApplication.run(WebApplication.class, args); // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import com.fasterxml.jackson.databind.ObjectMapper; import demo.springboot.WebApplication; import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package demo.springboot.web; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class) @AutoConfigureMockMvc @TestPropertySource(locations = "classpath:application.properties") public class BookControllerTest { private MockMvc mockMvc; @Mock
// Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/WebApplication.java // @SpringBootApplication // public class WebApplication { // public static void main(String[] args) { // SpringApplication.run(WebApplication.class, args); // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-3-spring-boot-web/src/test/java/demo/springboot/web/BookControllerTest.java import com.fasterxml.jackson.databind.ObjectMapper; import demo.springboot.WebApplication; import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package demo.springboot.web; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class) @AutoConfigureMockMvc @TestPropertySource(locations = "classpath:application.properties") public class BookControllerTest { private MockMvc mockMvc; @Mock
private BookService bookService;
JeffLi1993/springboot-learning-example
chapter-3-spring-boot-web/src/test/java/demo/springboot/web/BookControllerTest.java
// Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/WebApplication.java // @SpringBootApplication // public class WebApplication { // public static void main(String[] args) { // SpringApplication.run(WebApplication.class, args); // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import com.fasterxml.jackson.databind.ObjectMapper; import demo.springboot.WebApplication; import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package demo.springboot.web; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class) @AutoConfigureMockMvc @TestPropertySource(locations = "classpath:application.properties") public class BookControllerTest { private MockMvc mockMvc; @Mock private BookService bookService; @InjectMocks private BookController bookController; @Before public void init() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders .standaloneSetup(bookController) //.addFilters(new CORSFilter()) .build(); } @Test public void getBookList() throws Exception { mockMvc.perform(get("/book") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$", hasSize(0))); } @Test public void test_create_book_success() throws Exception {
// Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/WebApplication.java // @SpringBootApplication // public class WebApplication { // public static void main(String[] args) { // SpringApplication.run(WebApplication.class, args); // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-3-spring-boot-web/src/test/java/demo/springboot/web/BookControllerTest.java import com.fasterxml.jackson.databind.ObjectMapper; import demo.springboot.WebApplication; import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package demo.springboot.web; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class) @AutoConfigureMockMvc @TestPropertySource(locations = "classpath:application.properties") public class BookControllerTest { private MockMvc mockMvc; @Mock private BookService bookService; @InjectMocks private BookController bookController; @Before public void init() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders .standaloneSetup(bookController) //.addFilters(new CORSFilter()) .build(); } @Test public void getBookList() throws Exception { mockMvc.perform(get("/book") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$", hasSize(0))); } @Test public void test_create_book_success() throws Exception {
Book book = createOneBook();
JeffLi1993/springboot-learning-example
2-x-spring-boot-groovy/src/main/java/org/spring/springboot/web/GroovyScriptController.java
// Path: 2-x-spring-boot-groovy/src/main/java/org/spring/springboot/filter/RouteRuleFilter.java // @Component // public class RouteRuleFilter { // // public Map<String,Object> filter(Map<String,Object> input) { // // Binding binding = new Binding(); // binding.setVariable("input", input); // // GroovyShell shell = new GroovyShell(binding); // // String filterScript = "def field = input.get('field')\n" // + "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n" // + "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n"; // Script script = shell.parse(filterScript); // Object ret = script.run(); // System.out.println(ret); // return (Map<String, Object>) ret; // } // }
import org.spring.springboot.filter.RouteRuleFilter; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map;
package org.spring.springboot.web; @RestController @RequestMapping("/groovy/script") public class GroovyScriptController { @RequestMapping(value = "/filter", method = RequestMethod.GET) public String filter() {
// Path: 2-x-spring-boot-groovy/src/main/java/org/spring/springboot/filter/RouteRuleFilter.java // @Component // public class RouteRuleFilter { // // public Map<String,Object> filter(Map<String,Object> input) { // // Binding binding = new Binding(); // binding.setVariable("input", input); // // GroovyShell shell = new GroovyShell(binding); // // String filterScript = "def field = input.get('field')\n" // + "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n" // + "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n"; // Script script = shell.parse(filterScript); // Object ret = script.run(); // System.out.println(ret); // return (Map<String, Object>) ret; // } // } // Path: 2-x-spring-boot-groovy/src/main/java/org/spring/springboot/web/GroovyScriptController.java import org.spring.springboot.filter.RouteRuleFilter; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; package org.spring.springboot.web; @RestController @RequestMapping("/groovy/script") public class GroovyScriptController { @RequestMapping(value = "/filter", method = RequestMethod.GET) public String filter() {
RouteRuleFilter routeRuleFilter = new RouteRuleFilter();
JeffLi1993/springboot-learning-example
springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/impl/CityServiceImpl.java
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/dao/CityRepository.java // @Repository // public interface CityRepository extends ReactiveMongoRepository<City, Long> { // // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // }
import demo.springboot.dao.CityRepository; import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package demo.springboot.service.impl; @Component public class CityServiceImpl implements CityService {
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/dao/CityRepository.java // @Repository // public interface CityRepository extends ReactiveMongoRepository<City, Long> { // // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // } // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/impl/CityServiceImpl.java import demo.springboot.dao.CityRepository; import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package demo.springboot.service.impl; @Component public class CityServiceImpl implements CityService {
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/impl/CityServiceImpl.java
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/dao/CityRepository.java // @Repository // public interface CityRepository extends ReactiveMongoRepository<City, Long> { // // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // }
import demo.springboot.dao.CityRepository; import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package demo.springboot.service.impl; @Component public class CityServiceImpl implements CityService { private final CityRepository cityRepository; @Autowired public CityServiceImpl(CityRepository cityRepository) { this.cityRepository = cityRepository; } @Override
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/dao/CityRepository.java // @Repository // public interface CityRepository extends ReactiveMongoRepository<City, Long> { // // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // } // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/impl/CityServiceImpl.java import demo.springboot.dao.CityRepository; import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package demo.springboot.service.impl; @Component public class CityServiceImpl implements CityService { private final CityRepository cityRepository; @Autowired public CityServiceImpl(CityRepository cityRepository) { this.cityRepository = cityRepository; } @Override
public Flux<City> findAll() {
JeffLi1993/springboot-learning-example
springboot-webflux-3-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler {
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-3-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler {
private final CityRepository cityRepository;
JeffLi1993/springboot-learning-example
springboot-webflux-3-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
// Path: springboot-webflux-4-thymeleaf/src/main/java/org/spring/springboot/dao/CityRepository.java // @Repository // public class CityRepository { // // private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>(); // // private static final AtomicLong idGenerator = new AtomicLong(0); // // public Long save(City city) { // Long id = idGenerator.incrementAndGet(); // city.setId(id); // repository.put(id, city); // return id; // } // // public Collection<City> findAll() { // return repository.values(); // } // // // public City findCityById(Long id) { // return repository.get(id); // } // // public Long updateCity(City city) { // repository.put(city.getId(), city); // return city.getId(); // } // // public Long deleteCity(Long id) { // repository.remove(id); // return id; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-3-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java import org.spring.springboot.dao.CityRepository; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.handler; @Component public class CityHandler { private final CityRepository cityRepository; @Autowired public CityHandler(CityRepository cityRepository) { this.cityRepository = cityRepository; }
public Mono<City> save(City city) {
JeffLi1993/springboot-learning-example
springboot-webflux-1-quickstart/src/main/java/org/spring/springboot/router/CityRouter.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.handler.CityHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse;
package org.spring.springboot.router; @Configuration public class CityRouter { @Bean
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-1-quickstart/src/main/java/org/spring/springboot/router/CityRouter.java import org.spring.springboot.handler.CityHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; package org.spring.springboot.router; @Configuration public class CityRouter { @Bean
public RouterFunction<ServerResponse> routeCity(CityHandler cityHandler) {
JeffLi1993/springboot-learning-example
springboot-webflux-6-redis/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxReactiveController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city2") public class CityWebFluxReactiveController { @Autowired private ReactiveRedisTemplate reactiveRedisTemplate; @GetMapping(value = "/{id}")
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-6-redis/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxReactiveController.java import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @RestController @RequestMapping(value = "/city2") public class CityWebFluxReactiveController { @Autowired private ReactiveRedisTemplate reactiveRedisTemplate; @GetMapping(value = "/{id}")
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
chapter-2-spring-boot-config/src/main/java/demo/springboot/web/HelloBookController.java
// Path: chapter-2-spring-boot-config/src/main/java/demo/springboot/config/BookProperties.java // @Component // public class BookProperties { // // /** // * 书名 // */ // @Value("${demo.book.name}") // private String name; // // /** // * 作者 // */ // @Value("${demo.book.writer}") // private String writer; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // }
import demo.springboot.config.BookProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
package demo.springboot.web; /** * Spring Boot Hello案例 * * Created by bysocket on 26/09/2017. */ @RestController public class HelloBookController { @Autowired
// Path: chapter-2-spring-boot-config/src/main/java/demo/springboot/config/BookProperties.java // @Component // public class BookProperties { // // /** // * 书名 // */ // @Value("${demo.book.name}") // private String name; // // /** // * 作者 // */ // @Value("${demo.book.writer}") // private String writer; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // } // Path: chapter-2-spring-boot-config/src/main/java/demo/springboot/web/HelloBookController.java import demo.springboot.config.BookProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; package demo.springboot.web; /** * Spring Boot Hello案例 * * Created by bysocket on 26/09/2017. */ @RestController public class HelloBookController { @Autowired
BookProperties bookProperties;
JeffLi1993/springboot-learning-example
springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired
private CityHandler cityHandler;
JeffLi1993/springboot-learning-example
springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // }
import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}") @ResponseBody
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/handler/CityHandler.java // @Component // public class CityHandler { // // private final CityRepository cityRepository; // // @Autowired // public CityHandler(CityRepository cityRepository) { // this.cityRepository = cityRepository; // } // // public Mono<City> save(City city) { // return cityRepository.save(city); // } // // public Mono<City> findCityById(Long id) { // // return cityRepository.findById(id); // } // // public Flux<City> findAllCity() { // // return cityRepository.findAll(); // } // // public Mono<City> modifyCity(City city) { // // return cityRepository.save(city); // } // // public Mono<Long> deleteCity(Long id) { // cityRepository.deleteById(id); // return Mono.create(cityMonoSink -> cityMonoSink.success(id)); // } // // public Mono<City> getByCityName(String cityName) { // return cityRepository.findByCityName(cityName); // } // } // Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/webflux/controller/CityWebFluxController.java import org.spring.springboot.domain.City; import org.spring.springboot.handler.CityHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; package org.spring.springboot.webflux.controller; @Controller @RequestMapping(value = "/city") public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}") @ResponseBody
public Mono<City> findCityById(@PathVariable("id") Long id) {
JeffLi1993/springboot-learning-example
springboot-webflux-9-test/src/test/java/org/spring/springboot/handler/CityHandlerTest.java
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import java.util.HashMap; import java.util.Map;
package org.spring.springboot.handler; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CityHandlerTest { @Autowired private WebTestClient webClient;
// Path: springboot-webflux-5-thymeleaf-mongodb/src/main/java/org/spring/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: springboot-webflux-9-test/src/test/java/org/spring/springboot/handler/CityHandlerTest.java import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.spring.springboot.domain.City; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import java.util.HashMap; import java.util.Map; package org.spring.springboot.handler; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CityHandlerTest { @Autowired private WebTestClient webClient;
private static Map<String, City> cityMap = new HashMap<>();
JeffLi1993/springboot-learning-example
springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/web/CityController.java
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // }
import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import reactor.core.publisher.Mono; import java.awt.print.Book;
package demo.springboot.web; /** * city 控制层 * <p> * Created by bysocket */ @Controller @RequestMapping(value = "/city") public class CityController { private static final String CITY_FORM_PATH_NAME = "cityForm"; private static final String CITY_LIST_PATH_NAME = "cityList"; private static final String REDIRECT_TO_CITY_URL = "redirect:/city"; @Autowired
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // } // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/web/CityController.java import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import reactor.core.publisher.Mono; import java.awt.print.Book; package demo.springboot.web; /** * city 控制层 * <p> * Created by bysocket */ @Controller @RequestMapping(value = "/city") public class CityController { private static final String CITY_FORM_PATH_NAME = "cityForm"; private static final String CITY_LIST_PATH_NAME = "cityList"; private static final String REDIRECT_TO_CITY_URL = "redirect:/city"; @Autowired
CityService cityService;
JeffLi1993/springboot-learning-example
springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/web/CityController.java
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // }
import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import reactor.core.publisher.Mono; import java.awt.print.Book;
package demo.springboot.web; /** * city 控制层 * <p> * Created by bysocket */ @Controller @RequestMapping(value = "/city") public class CityController { private static final String CITY_FORM_PATH_NAME = "cityForm"; private static final String CITY_LIST_PATH_NAME = "cityList"; private static final String REDIRECT_TO_CITY_URL = "redirect:/city"; @Autowired CityService cityService; @RequestMapping(method = RequestMethod.GET) public String getCityList(final Model model) { model.addAttribute("cityList", cityService.findAll()); return CITY_LIST_PATH_NAME; } @RequestMapping(value = "/create", method = RequestMethod.GET) public String createCityForm(final Model model) {
// Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/domain/City.java // public class City { // // /** // * 城市编号 // */ // private Long id; // // /** // * 省份编号 // */ // private Long provinceId; // // /** // * 城市名称 // */ // private String cityName; // // /** // * 描述 // */ // private String description; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getProvinceId() { // return provinceId; // } // // public void setProvinceId(Long provinceId) { // this.provinceId = provinceId; // } // // public String getCityName() { // return cityName; // } // // public void setCityName(String cityName) { // this.cityName = cityName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/service/CityService.java // public interface CityService { // // Flux<City> findAll(); // // Mono<City> insertByCity(City city); // // Mono<City> update(City city); // // Mono<Void> delete(Long id); // // Mono<City> findById(Long id); // } // Path: springboot-webflux-10-book-manage-sys/src/main/java/demo/springboot/web/CityController.java import demo.springboot.domain.City; import demo.springboot.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import reactor.core.publisher.Mono; import java.awt.print.Book; package demo.springboot.web; /** * city 控制层 * <p> * Created by bysocket */ @Controller @RequestMapping(value = "/city") public class CityController { private static final String CITY_FORM_PATH_NAME = "cityForm"; private static final String CITY_LIST_PATH_NAME = "cityList"; private static final String REDIRECT_TO_CITY_URL = "redirect:/city"; @Autowired CityService cityService; @RequestMapping(method = RequestMethod.GET) public String getCityList(final Model model) { model.addAttribute("cityList", cityService.findAll()); return CITY_LIST_PATH_NAME; } @RequestMapping(value = "/create", method = RequestMethod.GET) public String createCityForm(final Model model) {
model.addAttribute("city", new City());
JeffLi1993/springboot-learning-example
chapter-3-spring-boot-web/src/main/java/demo/springboot/web/BookController.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.List;
package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 27/09/2017. */ @RestController @RequestMapping(value = "/book") public class BookController { private final Logger LOG = LoggerFactory.getLogger(BookController.class); @Autowired
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/web/BookController.java import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.List; package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 27/09/2017. */ @RestController @RequestMapping(value = "/book") public class BookController { private final Logger LOG = LoggerFactory.getLogger(BookController.class); @Autowired
BookService bookService;
JeffLi1993/springboot-learning-example
chapter-3-spring-boot-web/src/main/java/demo/springboot/web/BookController.java
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // }
import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.List;
package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 27/09/2017. */ @RestController @RequestMapping(value = "/book") public class BookController { private final Logger LOG = LoggerFactory.getLogger(BookController.class); @Autowired BookService bookService; /** * 获取 Book 列表 * 处理 "/book" 的 GET 请求,用来获取 Book 列表 */ @RequestMapping(method = RequestMethod.GET)
// Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/domain/Book.java // @Entity // public class Book implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 书名 // */ // private String name; // // /** // * 作者 // */ // private String writer; // // /** // * 简介 // */ // private String introduction; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getWriter() { // return writer; // } // // public void setWriter(String writer) { // this.writer = writer; // } // // public String getIntroduction() { // return introduction; // } // // public void setIntroduction(String introduction) { // this.introduction = introduction; // } // } // // Path: chapter-5-spring-boot-data-jpa/src/main/java/demo/springboot/service/BookService.java // public interface BookService { // /** // * 获取所有 Book // */ // List<Book> findAll(); // // /** // * 新增 Book // * // * @param book {@link Book} // */ // Book insertByBook(Book book); // // /** // * 更新 Book // * // * @param book {@link Book} // */ // Book update(Book book); // // /** // * 删除 Book // * // * @param id 编号 // */ // Book delete(Long id); // // /** // * 获取 Book // * // * @param id 编号 // */ // Book findById(Long id); // } // Path: chapter-3-spring-boot-web/src/main/java/demo/springboot/web/BookController.java import demo.springboot.domain.Book; import demo.springboot.service.BookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.List; package demo.springboot.web; /** * Book 控制层 * * Created by bysocket on 27/09/2017. */ @RestController @RequestMapping(value = "/book") public class BookController { private final Logger LOG = LoggerFactory.getLogger(BookController.class); @Autowired BookService bookService; /** * 获取 Book 列表 * 处理 "/book" 的 GET 请求,用来获取 Book 列表 */ @RequestMapping(method = RequestMethod.GET)
public List<Book> getBookList() {
JeffLi1993/springboot-learning-example
chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // } // // Path: chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/UserService.java // public interface UserService { // // /** // * 获取用户分页列表 // * // * @param pageable // * @return // */ // Page<User> findByPage(Pageable pageable); // // /** // * 新增用户 // * // * @param user // * @return // */ // User insertByUser(User user); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import spring.boot.core.domain.User; import spring.boot.core.service.UserService; import javax.validation.Valid;
package spring.boot.core.web; /** * 用户控制层 * * Created by bysocket on 24/07/2017. */ @Controller @RequestMapping(value = "/users") // 通过这里配置使下面的映射都在 /users public class UserController { @Autowired
// Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/domain/User.java // @Entity // public class User implements Serializable { // // /** // * 编号 // */ // @Id // @GeneratedValue // private Long id; // // /** // * 名称 // */ // @NotEmpty(message = "姓名不能为空") // @Size(min = 2, max = 8, message = "姓名长度必须大于 2 且小于 20 字") // private String name; // // /** // * 年龄 // */ // @NotNull(message = "年龄不能为空") // @Min(value = 0, message = "年龄大于 0") // @Max(value = 300, message = "年龄不大于 300") // private Integer age; // // /** // * 出生时间 // */ // @NotEmpty(message = "出生时间不能为空") // private String birthday; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getAge() { // return age; // } // // public void setAge(Integer age) { // this.age = age; // } // // public String getBirthday() { // return birthday; // } // // public void setBirthday(String birthday) { // this.birthday = birthday; // } // // // public User(String name, Integer age, String birthday) { // this.name = name; // this.age = age; // this.birthday = birthday; // } // // public User() {} // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", age=" + age + // ", birthday=" + birthday + // '}'; // } // } // // Path: chapter-5-spring-boot-paging-sorting/src/main/java/spring/boot/core/service/UserService.java // public interface UserService { // // /** // * 获取用户分页列表 // * // * @param pageable // * @return // */ // Page<User> findByPage(Pageable pageable); // // /** // * 新增用户 // * // * @param user // * @return // */ // User insertByUser(User user); // } // Path: chapter-4-spring-boot-validating-form-input/src/main/java/spring/boot/core/web/UserController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import spring.boot.core.domain.User; import spring.boot.core.service.UserService; import javax.validation.Valid; package spring.boot.core.web; /** * 用户控制层 * * Created by bysocket on 24/07/2017. */ @Controller @RequestMapping(value = "/users") // 通过这里配置使下面的映射都在 /users public class UserController { @Autowired
UserService userService; // 用户服务层