2017-01-19 21:14:30 -05:00
package com.baeldung.sparkjava ;
import static spark.Spark.delete ;
import static spark.Spark.get ;
import static spark.Spark.options ;
import static spark.Spark.post ;
import static spark.Spark.put ;
import com.google.gson.Gson ;
public class SparkRestExample {
public static void main ( String [ ] args ) {
final UserService userService = new UserServiceMapImpl ( ) ;
2017-01-29 08:57:30 -05:00
2017-01-19 21:14:30 -05:00
post ( " /users " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
2017-01-19 21:14:30 -05:00
User user = new Gson ( ) . fromJson ( request . body ( ) , User . class ) ;
userService . addUser ( user ) ;
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS ) ) ;
} ) ;
get ( " /users " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS , new Gson ( ) . toJsonTree ( userService . getUsers ( ) ) ) ) ;
2017-01-19 21:14:30 -05:00
} ) ;
get ( " /users/:id " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS , new Gson ( ) . toJsonTree ( userService . getUser ( request . params ( " :id " ) ) ) ) ) ;
2017-01-19 21:14:30 -05:00
} ) ;
put ( " /users/:id " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
2017-01-19 21:14:30 -05:00
User toEdit = new Gson ( ) . fromJson ( request . body ( ) , User . class ) ;
User editedUser = userService . editUser ( toEdit ) ;
2017-01-29 08:57:30 -05:00
2017-01-19 21:14:30 -05:00
if ( editedUser ! = null ) {
2017-01-29 08:57:30 -05:00
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS , new Gson ( ) . toJsonTree ( editedUser ) ) ) ;
} else {
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . ERROR , new Gson ( ) . toJson ( " User not found or error in edit " ) ) ) ;
2017-01-19 21:14:30 -05:00
}
} ) ;
delete ( " /users/:id " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
2017-01-19 21:14:30 -05:00
userService . deleteUser ( request . params ( " :id " ) ) ;
2017-01-29 08:57:30 -05:00
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS , " user deleted " ) ) ;
2017-01-19 21:14:30 -05:00
} ) ;
options ( " /users/:id " , ( request , response ) - > {
response . type ( " application/json " ) ;
2017-01-29 08:57:30 -05:00
return new Gson ( ) . toJson ( new StandardResponse ( StatusResponse . SUCCESS , ( userService . userExist ( request . params ( " :id " ) ) ) ? " User exists " : " User does not exists " ) ) ;
2017-01-19 21:14:30 -05:00
} ) ;
}
}