Files
SpringRest/src/main/java/application/controllers/UserController.java
T
2014-04-30 01:38:56 +02:00

96 lines
3.2 KiB
Java

package application.controllers;
import application.model.Role;
import application.model.User;
import application.repositories.RoleRepository;
import application.repositories.UserRepository;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.ResponseBody;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Created by lukasgol on 21.04.14.
*/
@Controller
@RequestMapping(value="/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@PersistenceContext
private EntityManager entityManager;
@RequestMapping(value = "/add")
@ResponseBody
//powinno mapowac obiekt json na obiekt user
public String addUser(@RequestBody User user) {
/*User user = new User();
user.setFirstName(username);
Set<Role> roles = new HashSet<Role>();
roles.add(new Role("lala","lala"));
roles.add(new Role("lala1","lala1"));
user.setRoles(roles);*/
userRepository.save(user);
return "saved user: "+user.getUserId();
}
@RequestMapping("/{userId}")
public String getUser(@PathVariable("userId") Long userId) throws JSONException{
User user = userRepository.findOne(userId);
JSONObject userJSON = new JSONObject();
userJSON.put("id", user.getUserId());
userJSON.put("firstname", user.getFirstName());
userJSON.put("lastname", user.getLastName());
userJSON.put("email", user.getEmail());
JSONArray userArray = new JSONArray();
userArray.put(userJSON);
return userArray.toString();
}
@RequestMapping
public
@ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
JSONArray userArray = new JSONArray();
for (User user : userRepository.findAll()) {
JSONObject userJSON = new JSONObject();
userJSON.put("id", user.getUserId());
userJSON.put("firstname", user.getFirstName());
userJSON.put("lastname", user.getLastName());
userJSON.put("email", user.getEmail());
JSONArray roleArray = new JSONArray();
for(Role r:user.getRoles()){
JSONObject roleJSON = new JSONObject();
roleJSON.put("id", r.getRoleId());
roleJSON.put("name", r.getRoleName());
roleJSON.put("password", r.getPassword());
roleArray.put(roleJSON);
}
userJSON.put("roles", roleArray);
userArray.put(userJSON);
}
return userArray.toString();
}
@RequestMapping("/remove/{userId}")
public String removeUser(@PathVariable("userId") Long userId) {
userRepository.delete(userId);
return "user deleted: "+userId;
}
}