minor formatting cleanup

This commit is contained in:
eugenp 2017-01-29 15:57:30 +02:00
parent c565173601
commit bf95d0aa9d
11 changed files with 80 additions and 105 deletions

View File

@ -8,7 +8,7 @@ import com.lmax.disruptor.EventHandler;
public class MultiEventPrintConsumer implements EventConsumer { public class MultiEventPrintConsumer implements EventConsumer {
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public EventHandler<ValueEvent>[] getEventHandler() { public EventHandler<ValueEvent>[] getEventHandler() {

View File

@ -8,7 +8,7 @@ import com.lmax.disruptor.EventHandler;
public class SingleEventPrintConsumer implements EventConsumer { public class SingleEventPrintConsumer implements EventConsumer {
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public EventHandler<ValueEvent>[] getEventHandler() { public EventHandler<ValueEvent>[] getEventHandler() {

View File

@ -1,12 +1,13 @@
package com.baeldung.sparkjava; package com.baeldung.sparkjava;
import static spark.Spark.*; import static spark.Spark.*;
public class HelloWorldService { public class HelloWorldService {
public static void main(String[] args) { public static void main(String[] args) {
get("/hello", (req,res)->"Hello, Baeldung"); get("/hello", (req, res) -> "Hello, Baeldung");
get("/hello/:name", (req,res)->{ get("/hello/:name", (req, res) -> {
return "Hello: "+ req.params(":name"); return "Hello: " + req.params(":name");
}); });
} }
} }

View File

@ -11,10 +11,10 @@ import com.google.gson.Gson;
public class SparkRestExample { public class SparkRestExample {
public static void main(String[] args) { public static void main(String[] args) {
final UserService userService = new UserServiceMapImpl(); final UserService userService = new UserServiceMapImpl();
post("/users", (request, response) -> { post("/users", (request, response) -> {
response.type("application/json"); response.type("application/json");
User user = new Gson().fromJson(request.body(), User.class); User user = new Gson().fromJson(request.body(), User.class);
userService.addUser(user); userService.addUser(user);
@ -23,52 +23,40 @@ public class SparkRestExample {
get("/users", (request, response) -> { get("/users", (request, response) -> {
response.type("application/json"); response.type("application/json");
return new Gson().toJson( return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUsers())));
new StandardResponse(StatusResponse.SUCCESS,new Gson()
.toJsonTree(userService.getUsers())));
}); });
get("/users/:id", (request, response) -> { get("/users/:id", (request, response) -> {
response.type("application/json"); response.type("application/json");
return new Gson().toJson( return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(userService.getUser(request.params(":id")))));
new StandardResponse(StatusResponse.SUCCESS,new Gson()
.toJsonTree(userService.getUser(request.params(":id")))));
}); });
put("/users/:id", (request, response) -> { put("/users/:id", (request, response) -> {
response.type("application/json"); response.type("application/json");
User toEdit = new Gson().fromJson(request.body(), User.class); User toEdit = new Gson().fromJson(request.body(), User.class);
User editedUser = userService.editUser(toEdit); User editedUser = userService.editUser(toEdit);
if (editedUser != null) { if (editedUser != null) {
return new Gson().toJson( return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, new Gson().toJsonTree(editedUser)));
new StandardResponse(StatusResponse.SUCCESS,new Gson() } else {
.toJsonTree(editedUser))); return new Gson().toJson(new StandardResponse(StatusResponse.ERROR, new Gson().toJson("User not found or error in edit")));
}else {
return new Gson().toJson(
new StandardResponse(StatusResponse.ERROR,new Gson()
.toJson("User not found or error in edit")));
} }
}); });
delete("/users/:id", (request, response) -> { delete("/users/:id", (request, response) -> {
response.type("application/json"); response.type("application/json");
userService.deleteUser(request.params(":id")); userService.deleteUser(request.params(":id"));
return new Gson().toJson( return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, "user deleted"));
new StandardResponse(StatusResponse.SUCCESS, "user deleted"));
}); });
options("/users/:id", (request, response) -> { options("/users/:id", (request, response) -> {
response.type("application/json"); response.type("application/json");
return new Gson().toJson( return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS, (userService.userExist(request.params(":id"))) ? "User exists" : "User does not exists"));
new StandardResponse(StatusResponse.SUCCESS,
(userService.userExist(
request.params(":id"))) ? "User exists" : "User does not exists" ));
}); });
} }

View File

@ -1,15 +1,14 @@
package com.baeldung.sparkjava; package com.baeldung.sparkjava;
public enum StatusResponse { public enum StatusResponse {
SUCCESS ("Success"), SUCCESS("Success"), ERROR("Error");
ERROR ("Error");
final private String status; final private String status;
StatusResponse(String status) { StatusResponse(String status) {
this.status = status; this.status = status;
} }
public String getStatus() { public String getStatus() {
return status; return status;
} }

View File

@ -51,7 +51,7 @@ class User {
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
@Override @Override
public String toString() { public String toString() {
return new StringBuffer().append(getEmail()).toString(); return new StringBuffer().append(getEmail()).toString();

View File

@ -1,11 +1,11 @@
package com.baeldung.sparkjava; package com.baeldung.sparkjava;
public class UserException extends Exception{ public class UserException extends Exception {
public UserException() { public UserException() {
super(); super();
} }
public UserException(String message) { public UserException(String message) {
super(message); super(message);
} }

View File

@ -3,10 +3,15 @@ package com.baeldung.sparkjava;
import java.util.Collection; import java.util.Collection;
public interface UserService { public interface UserService {
public void addUser (User user) ; public void addUser(User user);
public Collection<User> getUsers () ;
public User getUser (String id) ; public Collection<User> getUsers();
public User editUser (User user) throws UserException;
public void deleteUser (String id) ; public User getUser(String id);
public boolean userExist (String id);
public User editUser(User user) throws UserException;
public void deleteUser(String id);
public boolean userExist(String id);
} }

View File

@ -3,65 +3,65 @@ package com.baeldung.sparkjava;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
public class UserServiceMapImpl implements UserService{ public class UserServiceMapImpl implements UserService {
private HashMap<String, User> userMap; private HashMap<String, User> userMap;
public UserServiceMapImpl() { public UserServiceMapImpl() {
userMap = new HashMap<>(); userMap = new HashMap<>();
} }
@Override @Override
public void addUser (User user) { public void addUser(User user) {
userMap.put(user.getId(), user); userMap.put(user.getId(), user);
} }
@Override @Override
public Collection<User> getUsers () { public Collection<User> getUsers() {
return userMap.values(); return userMap.values();
} }
@Override @Override
public User getUser (String id) { public User getUser(String id) {
return userMap.get(id); return userMap.get(id);
} }
@Override @Override
public User editUser (User forEdit) throws UserException{ public User editUser(User forEdit) throws UserException {
try{ try {
if (forEdit.getId() == null) if (forEdit.getId() == null)
throw new UserException("ID cannot be blank"); throw new UserException("ID cannot be blank");
User toEdit = userMap.get(forEdit.getId()); User toEdit = userMap.get(forEdit.getId());
if (toEdit == null ) if (toEdit == null)
throw new UserException("User not found"); throw new UserException("User not found");
if (forEdit.getEmail()!=null) { if (forEdit.getEmail() != null) {
toEdit.setEmail(forEdit.getEmail()); toEdit.setEmail(forEdit.getEmail());
} }
if (forEdit.getFirstName()!=null) { if (forEdit.getFirstName() != null) {
toEdit.setFirstName(forEdit.getFirstName()); toEdit.setFirstName(forEdit.getFirstName());
} }
if (forEdit.getLastName()!=null) { if (forEdit.getLastName() != null) {
toEdit.setLastName(forEdit.getLastName()); toEdit.setLastName(forEdit.getLastName());
} }
if (forEdit.getId()!=null) { if (forEdit.getId() != null) {
toEdit.setId(forEdit.getId()); toEdit.setId(forEdit.getId());
} }
return toEdit; return toEdit;
}catch (Exception ex) { } catch (Exception ex) {
throw new UserException(ex.getMessage()); throw new UserException(ex.getMessage());
} }
} }
@Override @Override
public void deleteUser (String id) { public void deleteUser(String id) {
userMap.remove(id); userMap.remove(id);
} }
@Override @Override
public boolean userExist (String id) { public boolean userExist(String id) {
return userMap.containsKey(id); return userMap.containsKey(id);
} }

View File

@ -15,25 +15,11 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.authorizeRequests().antMatchers("/css/**", "/js/**", "/loggedout").permitAll().anyRequest().authenticated().and().httpBasic().and().logout().disable().csrf().disable();
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/loggedout").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout().disable()
.csrf().disable();
} }
@Autowired @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth auth.inMemoryAuthentication().withUser("jim").password("jim").roles("USER").and().withUser("pam").password("pam").roles("USER").and().withUser("michael").password("michael").roles("MANAGER");
.inMemoryAuthentication()
.withUser("jim").password("jim").roles("USER")
.and()
.withUser("pam").password("pam").roles("USER")
.and()
.withUser("michael").password("michael").roles("MANAGER");
} }
} }

View File

@ -37,38 +37,34 @@ public class LiveTest {
@Test @Test
@WithMockUser(roles = "MANAGER") @WithMockUser(roles = "MANAGER")
public void givenUserIsManager_whenGetTasks_thenAllTasks() throws Exception { public void givenUserIsManager_whenGetTasks_thenAllTasks() throws Exception {
String allTasks = "[{'id':1,'description':'Send a fax','assignee':'pam'}," + String allTasks = "[{'id':1,'description':'Send a fax','assignee':'pam'}," + "{'id':2,'description':'Print a document','assignee':'pam'}," + "{'id':3,'description':'Answer the phone','assignee':'pam'},"
"{'id':2,'description':'Print a document','assignee':'pam'}," + + "{'id':4,'description':'Call a client','assignee':'jim'}," + "{'id':5,'description':'Organize a meeting','assignee':'michael'}]";
"{'id':3,'description':'Answer the phone','assignee':'pam'}," +
"{'id':4,'description':'Call a client','assignee':'jim'}," +
"{'id':5,'description':'Organize a meeting','assignee':'michael'}]";
mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(allTasks)); mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(allTasks));
} }
@Test @Test
@WithMockUser(username = "jim") @WithMockUser(username = "jim")
public void givenUserNotManager_whenGetTasks_thenReturnAssignedToMe() throws Exception { public void givenUserNotManager_whenGetTasks_thenReturnAssignedToMe() throws Exception {
String myTasks = "[{'id':4,'description':'Call a client','assignee':'jim'}]"; String myTasks = "[{'id':4,'description':'Call a client','assignee':'jim'}]";
mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(myTasks)); mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(myTasks));
} }
@Test @Test
@WithMockUser(roles = "MANAGER") @WithMockUser(roles = "MANAGER")
public void givenUserIsManager_whenPostTasks_thenIncludeAllTasks() throws Exception { public void givenUserIsManager_whenPostTasks_thenIncludeAllTasks() throws Exception {
String newTasks = "[{\"description\":\"New to Michael\",\"assignee\":\"michael\"}," + String newTasks = "[{\"description\":\"New to Michael\",\"assignee\":\"michael\"}," + "{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
"{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk())
mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk()).andExpect(content().json("[{'id': 6,'description':'New to Michael','assignee':'michael'}, {'id': 7,'description':'New to Pam','assignee':'pam'}]")); .andExpect(content().json("[{'id': 6,'description':'New to Michael','assignee':'michael'}, {'id': 7,'description':'New to Pam','assignee':'pam'}]"));
} }
@Test @Test
@WithMockUser(username = "jim") @WithMockUser(username = "jim")
public void givenUserNotManager_whenPostTasks_thenIncludeOnlyAssignedToMe() throws Exception { public void givenUserNotManager_whenPostTasks_thenIncludeOnlyAssignedToMe() throws Exception {
String newTasks = "[{\"description\":\"New to Jim\",\"assignee\":\"jim\"}," + String newTasks = "[{\"description\":\"New to Jim\",\"assignee\":\"jim\"}," + "{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
"{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk()).andExpect(content().json("[{'id': 8,'description':'New to Jim','assignee':'jim'}]")); mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk()).andExpect(content().json("[{'id': 8,'description':'New to Jim','assignee':'jim'}]"));
} }