Advertisement
Guest User

bla

a guest
Feb 2nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.13 KB | None | 0 0
  1. package de.teamzhang.controller;
  2.  
  3. import com.mongodb.*;
  4. import com.mongodb.util.JSON;
  5. import de.teamzhang.model.*;
  6. import de.teamzhang.repository.UserRepository;
  7. import org.json.simple.JSONArray;
  8. import org.json.simple.JSONObject;
  9. import org.json.simple.parser.JSONParser;
  10. import org.json.simple.parser.ParseException;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.data.mongodb.core.MongoTemplate;
  13. import org.springframework.http.HttpStatus;
  14. import org.springframework.http.ResponseEntity;
  15. import org.springframework.security.core.Authentication;
  16. import org.springframework.security.core.context.SecurityContextHolder;
  17. import org.springframework.security.crypto.password.PasswordEncoder;
  18. import org.springframework.stereotype.Controller;
  19. import org.springframework.ui.Model;
  20. import org.springframework.web.bind.annotation.*;
  21. import org.springframework.web.servlet.ModelAndView;
  22. import org.springframework.web.servlet.view.RedirectView;
  23.  
  24. import javax.servlet.http.HttpServletRequest;
  25. import java.io.*;
  26. import java.util.ArrayList;
  27. import java.util.Base64;
  28. import java.util.Collections;
  29. import java.util.List;
  30.  
  31. @Controller
  32. public class AdminController {
  33.  
  34. @Autowired
  35. private UserRepository userRepository;
  36.  
  37. @Autowired
  38. private MongoTemplate mongoTemplate;
  39.  
  40. @Autowired
  41. private PasswordEncoder passwordEncoder;
  42.  
  43.  
  44. @GetMapping(value="/me")
  45. public @ResponseBody User getMe()
  46. {
  47. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  48. SecUserDetails userDetails = (SecUserDetails) authentication.getPrincipal();
  49.  
  50. User user = userDetails.getUser();
  51. user.setPassword("");
  52. user.setId(null);
  53.  
  54. return user;
  55. }
  56.  
  57. @GetMapping(value = "/user/{mail}")
  58. public @ResponseBody User getUser(@PathVariable String mail) {
  59.  
  60. String sMail = "";
  61.  
  62. try
  63. {
  64. byte[] bMail = Base64.getDecoder().decode(mail);
  65. sMail = new String(bMail, "UTF-8");
  66. }
  67. catch(UnsupportedEncodingException uee)
  68. {
  69. uee.printStackTrace();
  70. }
  71.  
  72. User user = userRepository.findByMail(sMail);
  73.  
  74. if(user == null)
  75. return new User();
  76.  
  77.  
  78. user.setPassword("");
  79. user.setId(null);
  80. return user;
  81. }
  82.  
  83. @GetMapping(value = "/users")
  84. public @ResponseBody List<User> getUsers() {
  85.  
  86. List<User> usersList = userRepository.findAll();
  87.  
  88. if(usersList.isEmpty())
  89. return new ArrayList<>();
  90.  
  91.  
  92. for(User user : usersList) {
  93. user.setPassword("");
  94. user.setId(null);
  95. }
  96.  
  97. return usersList;
  98. }
  99.  
  100. @PostMapping(value = "/createUser")
  101. public ResponseEntity<String> createUser(@RequestBody String body) {
  102.  
  103. JSONParser parser = new JSONParser();
  104. JSONObject json = new JSONObject();
  105.  
  106. try
  107. {
  108. json = (JSONObject) parser.parse(body);
  109. }
  110. catch (ParseException e)
  111. {
  112. e.printStackTrace();
  113. }
  114.  
  115. String firstName = (String) json.get("firstName");
  116. String lastName = (String) json.get("lastName");
  117. int role = Integer.valueOf((String) json.get("role"));
  118. String mail = (String) json.get("mail");
  119. String password = (String) json.get("password");
  120.  
  121. User user = new User();
  122. user.setUsername(mail);
  123. user.setFirstName(firstName);
  124. user.setLastName(lastName);
  125. user.setRole(role);
  126. user.setMail(mail);
  127. user.setPassword(passwordEncoder.encode(password));
  128.  
  129. if(userRepository.findByMail(user.getMail()) != null)
  130. {
  131. return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
  132. }
  133. else
  134. {
  135. mongoTemplate.insert(user, "user");
  136.  
  137. // check if user was inserted
  138. if(userRepository.findByMail(user.getMail()) != null)
  139. return new ResponseEntity<String>(HttpStatus.OK);
  140. else
  141. return new ResponseEntity<String>(HttpStatus.CONFLICT); // TODO corect code ?
  142. }
  143. }
  144.  
  145.  
  146. @DeleteMapping(value = "/users/{mail}")
  147. public ResponseEntity<String> deleteUser(@PathVariable String mail) {
  148.  
  149. String sMail = "";
  150.  
  151. try
  152. {
  153. byte[] bMail = Base64.getDecoder().decode(mail);
  154. sMail = new String(bMail, "UTF-8");
  155. }
  156. catch(UnsupportedEncodingException uee)
  157. {
  158. uee.printStackTrace();
  159. }
  160.  
  161. if(userRepository.findByMail(sMail) == null)
  162. {
  163. return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
  164. }
  165. else
  166. {
  167. BasicDBObject query = new BasicDBObject();
  168. query.put("mail", sMail);
  169. mongoTemplate.getCollection("user").remove(query);
  170.  
  171.  
  172. if(userRepository.findByMail(sMail) == null)
  173. return new ResponseEntity<String>(HttpStatus.OK);
  174. else
  175. return new ResponseEntity<String>(HttpStatus.CONFLICT);
  176. }
  177. }
  178.  
  179. @GetMapping(value = "/courses")
  180. public @ResponseBody List<JSONObject> getCourses()
  181. {
  182. List<JSONObject> courseDescriptions = new ArrayList<>();
  183.  
  184. DBCursor cursor = mongoTemplate.getCollection("coursesDescription").find();
  185.  
  186. while(cursor.hasNext())
  187. {
  188. DBObject course = cursor.next();
  189.  
  190. String courseDescription = (String) course.get("kurzname");
  191.  
  192. JSONObject jsonCourse = new JSONObject();
  193. jsonCourse.put("kurzname", courseDescription);
  194.  
  195. courseDescriptions.add(jsonCourse);
  196. }
  197.  
  198. return courseDescriptions;
  199. }
  200.  
  201. @PostMapping(value = "/users/courses/{mail}")
  202. public ResponseEntity<String> setUserCourses(@RequestBody String body, @PathVariable String mail)
  203. {
  204. JSONParser parser = new JSONParser();
  205. JSONArray jsonArray = new JSONArray();
  206. String sMail = "";
  207.  
  208. try
  209. {
  210. byte[] bMail = Base64.getDecoder().decode(mail);
  211. sMail = new String(bMail, "UTF-8");
  212.  
  213. jsonArray = (JSONArray) parser.parse(body); // TODO als liste ???
  214. }
  215. catch(Exception e)
  216. {
  217. e.printStackTrace();
  218. }
  219.  
  220. User user = userRepository.findByMail(sMail);
  221.  
  222. if(user != null) {
  223. try {
  224. DBCollection teachersDB = mongoTemplate.getCollection("teachers");
  225. DBCollection coursesDB = mongoTemplate.getCollection("coursesDescription");
  226.  
  227. if (teachersDB != null && coursesDB != null)
  228. {
  229. List<DBObject> courses = new ArrayList<>();
  230.  
  231. // find courses via 'kurzname' and add to list
  232. for(int i = 0; i < jsonArray.size(); ++i)
  233. {
  234. JSONObject course = (JSONObject) jsonArray.get(i);
  235.  
  236. BasicDBObject courseQuery = new BasicDBObject();
  237. courseQuery.put("kurzname", course.get("kurzname"));
  238.  
  239. DBObject tmpCourse = coursesDB.find(courseQuery).next();
  240. courses.add(tmpCourse);
  241. }
  242.  
  243. // search for teacher and update courses
  244. BasicDBObject query = new BasicDBObject();
  245. query.put("firstName", user.getFirstName());
  246. query.put("lastName", user.getLastName());
  247.  
  248. BasicDBObject update = new BasicDBObject();
  249. update.put("courses", courses);
  250.  
  251. teachersDB.update(query, update);
  252. }
  253. else
  254. {
  255. return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  256. }
  257. }
  258. catch(Exception e){
  259. e.printStackTrace();
  260. }
  261. }
  262. else
  263. return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  264.  
  265.  
  266. return new ResponseEntity<>(HttpStatus.OK);
  267. }
  268.  
  269. @GetMapping(value = "/users/courses/{mail}")
  270. public @ResponseBody List<JSONObject> getUserCourses(@PathVariable String mail) {
  271.  
  272. List<JSONObject> courseList = new ArrayList<>();
  273. String sMail = "";
  274.  
  275. try
  276. {
  277. byte[] bMail = Base64.getDecoder().decode(mail);
  278. sMail = new String(bMail, "UTF-8");
  279. }
  280. catch(UnsupportedEncodingException uee)
  281. {
  282. uee.printStackTrace();
  283. }
  284.  
  285. User user = userRepository.findByMail(sMail);
  286.  
  287. if(user != null)
  288. {
  289. try {
  290. DBCollection teachersDB = mongoTemplate.getCollection("teachers");
  291.  
  292. if (teachersDB != null)
  293. {
  294. BasicDBObject query = new BasicDBObject();
  295. query.put("firstName", user.getFirstName());
  296. query.put("lastName", user.getLastName());
  297.  
  298. DBObject teacher = teachersDB.find(query).next();
  299.  
  300. List<DBObject> tmpCourses = (List<DBObject>) teacher.get("courses");
  301.  
  302. for(DBObject tmpCourse : tmpCourses)
  303. {
  304. JSONObject course = new JSONObject();
  305. course.put("kurzname", tmpCourse.get("name"));
  306.  
  307. courseList.add(course);
  308. }
  309. }
  310. }
  311. catch (Exception e) {
  312. e.printStackTrace();
  313. }
  314. }
  315.  
  316. return courseList;
  317. }
  318.  
  319. @PostMapping(value = "/timetables/{withPrio}")
  320. public @ResponseBody List<CalculatedSchedule> setSchedule(HttpServletRequest request, @PathVariable boolean withPrio) {
  321.  
  322. Algorithm algo = new Algorithm();
  323. algo.resetData();
  324.  
  325. try {
  326. if (!mongoTemplate.collectionExists("schedules")) {
  327. mongoTemplate.createCollection("schedules");
  328. }
  329. if(!mongoTemplate.collectionExists("settings")) {
  330. mongoTemplate.createCollection("settings");
  331. }
  332. } catch (Exception e) {
  333. e.printStackTrace();
  334. }
  335.  
  336. // set student prios
  337. List<StudentSettings> s = new ArrayList<>();
  338. DBCollection settingsDB = mongoTemplate.getCollection("settings");
  339. // settingsDB.save(settings1);
  340.  
  341. // set teacher prios
  342. // Erstelle teacher obj und fülle mit daten aus DB
  343. List<Teacher> t = new ArrayList<>();
  344. DBCollection teachersDB = mongoTemplate.getCollection("teachers");
  345. DBCursor cursor = teachersDB.find();
  346. while (cursor.hasNext()) {
  347. DBObject obj = cursor.next();
  348. Teacher teacherobj = mongoTemplate.getConverter().read(Teacher.class, obj);
  349.  
  350. t.add(teacherobj);
  351.  
  352. }
  353.  
  354. cursor = settingsDB.find();
  355. while (cursor.hasNext()) {
  356. DBObject obj = cursor.next();
  357. s.add(mongoTemplate.getConverter().read(StudentSettings.class, obj));
  358. }
  359.  
  360.  
  361. System.out.println("all tachers: "+t.size());
  362. algo.setTeachers(t);
  363. algo.setRooms(getRooms(request));
  364.  
  365. if(withPrio)
  366. algo.setStudentPrios(s);
  367.  
  368. List<CalculatedSchedule> cs = algo.generateCalendar();
  369.  
  370. mongoTemplate.insert(cs, "schedules");
  371.  
  372. /*
  373. List<String[][]> bla = new ArrayList<>();
  374. for(CalculatedSchedule xxx : cs)
  375. bla.add(xxx.getSchedule());
  376. */
  377.  
  378. return cs;
  379. }
  380.  
  381. @GetMapping(value = "/users/priorities/{mail}")
  382. public @ResponseBody List<JSONObject> getUserPriorities(@PathVariable String mail)
  383. {
  384. List<JSONObject> prioList = new ArrayList<>();
  385. String sMail = "";
  386.  
  387. try
  388. {
  389. byte[] bMail = Base64.getDecoder().decode(mail);
  390. sMail = new String(bMail, "UTF-8");
  391. }
  392. catch(UnsupportedEncodingException uee)
  393. {
  394. uee.printStackTrace();
  395. }
  396.  
  397. User user = userRepository.findByMail(sMail);
  398.  
  399. if(user != null)
  400. {
  401. try {
  402. DBCollection teachersDB = mongoTemplate.getCollection("teachers");
  403.  
  404. if (teachersDB != null)
  405. {
  406. BasicDBObject query = new BasicDBObject();
  407. query.put("firstName", user.getFirstName());
  408. query.put("lastName", user.getLastName());
  409.  
  410. DBObject teacher = teachersDB.find(query).next();
  411. List<DBObject> prios = (List<DBObject>) teacher.get("prios");
  412.  
  413. //for(Prio prio : (List<Prio>) teacher.get("prios"))
  414. for(DBObject prio : prios)
  415. {
  416. String classPath = (String) prio.get("_class");
  417. String[] sClassPath = classPath.split("\\.");
  418.  
  419. String type = sClassPath[sClassPath.length-1];
  420.  
  421. JSONObject newPrio = new JSONObject();
  422. newPrio.put("type", type);
  423. newPrio.put("kurzname", prio.get("name"));
  424. newPrio.put("value", prio.get("text"));
  425.  
  426. prioList.add(newPrio);
  427. }
  428. }
  429. }
  430. catch (Exception e) {
  431. e.printStackTrace();
  432. }
  433. }
  434.  
  435. return prioList;
  436. }
  437.  
  438. @PatchMapping(value = "/users/priorities/{mail}")
  439. public ResponseEntity<String> setUserPriorities(@RequestBody String body, @PathVariable String mail) {
  440.  
  441. JSONParser parser = new JSONParser();
  442. JSONArray jsonArray = new JSONArray();
  443. String sMail = "";
  444.  
  445. try
  446. {
  447. byte[] bMail = Base64.getDecoder().decode(mail);
  448. sMail = new String(bMail, "UTF-8");
  449.  
  450. jsonArray = (JSONArray) parser.parse(body); // TODO als liste ???
  451. }
  452. catch(Exception e)
  453. {
  454. e.printStackTrace();
  455. }
  456.  
  457. List<JSONObject> prios = new ArrayList<>();
  458.  
  459. for(int i = 0; i < jsonArray.size(); ++i)
  460. {
  461. JSONObject newPrio = null;
  462.  
  463. JSONObject jPrio = (JSONObject) jsonArray.get(i);
  464. String type = (String) jPrio.get("type");
  465.  
  466. if(type.matches("SimplePrio"))
  467. {
  468. /*
  469. {"_id":null,
  470. "name":"Wöchentliche Veranstaltungen",
  471. "course":189,
  472. "isValidForAllCourses":true,
  473. "text":"Ich ziehe es vor die vierzehntägigen 4SWS meines Unterrichts in zwei wöchentliche Einzelveranstaltungen mit je 2SWS aufzuteilen.",
  474. "courses":[],
  475. "_class":"de.teamzhang.model.SimplePrio"}
  476. */
  477.  
  478. newPrio.put("_id", null);
  479. newPrio.put("name", jPrio.get("kurzname"));
  480. newPrio.put("course", 0);
  481. newPrio.put("isValidForAllCourses", true);
  482. newPrio.put("text", jPrio.get("value"));
  483. newPrio.put("courses", new String[]{});
  484. newPrio.put("_class", "de.teamzhang.model.SimplePrio");
  485. }
  486. else if(type.matches("SingleChoicePrio"))
  487. {
  488. /*
  489. {"_id":null,
  490. "option":0,
  491. "name":"Anzahl Veranstaltungen pro Tag",
  492. "course":0,
  493. "isValidForAllCourses":true,
  494. "text":"Ich bevorzuge \u0009.\u0009",
  495. "courses":[],
  496. "_class":"de.teamzhang.model.SingleChoicePrio"}
  497. */
  498.  
  499. newPrio.put("_id", null);
  500. newPrio.put("option", 0);
  501. newPrio.put("name", jPrio.get("kurzname"));
  502. newPrio.put("course", 0);
  503. newPrio.put("isValidForAllCourses", true);
  504. newPrio.put("text", true);
  505. newPrio.put("courses", new String[]{});
  506. newPrio.put("_class", "de.teamzhang.model.SimplePrio");
  507. }
  508. else if(type.matches("FreeTextInputPrio"))
  509. {
  510. newPrio.put("_id", null);
  511. newPrio.put("name", jPrio.get("kurzname"));
  512. newPrio.put("value", jPrio.get("value"));
  513. newPrio.put("_class", "de.teamzhang.model.FreeTextInputPrio");
  514. }
  515. else if(type.matches("ExcludeDayCombinationPrio"))
  516. {
  517. /*
  518. {"_id":null,
  519. "dayOne":0,
  520. "dayTwo":0,
  521. "timeOne":0,
  522. "timeTwo":0,
  523. "hasTime":false,
  524. "isExcluding":false,
  525. "name":"Tage ausschließen",
  526. "course":0,
  527. "isValidForAllCourses":true,
  528. "text":"Wenn ich am \u0009 unterrichte, möchte ich nicht am \u0009 unterrichten.\u0009",
  529. "courses":[],
  530. "_class":"de.teamzhang.model.ExcludeDayCombinationPrio"},
  531. */
  532. newPrio.put("_id", null);
  533. newPrio.put("dayOne", 0);
  534. newPrio.put("dayTwo", 0);
  535. newPrio.put("timeOne", 0);
  536. newPrio.put("timeTwo", 0);
  537. newPrio.put("hasTime", false);
  538. newPrio.put("isExcluding", false);
  539. newPrio.put("name", jPrio.get("kurzname"));
  540. newPrio.put("course", 0);
  541. newPrio.put("isValidForAllCourses", true);
  542. newPrio.put("text", jPrio.get("value"));
  543. newPrio.put("courses", new String[]{});
  544. newPrio.put("_class", "de.teamzhang.model.ExcludeDayCombinationPrio");
  545.  
  546. }
  547. else
  548. System.out.println("no known type!");
  549.  
  550. prios.add(newPrio);
  551. }
  552.  
  553. User user = userRepository.findByMail(sMail);
  554.  
  555. if(user != null) {
  556. try {
  557. DBCollection teachersDB = mongoTemplate.getCollection("teachers");
  558.  
  559. if (teachersDB != null) {
  560. BasicDBObject query = new BasicDBObject();
  561. query.put("firstName", user.getFirstName());
  562. query.put("lastName", user.getLastName());
  563.  
  564. BasicDBObject update = new BasicDBObject();
  565. update.put("prios", prios);
  566. }
  567. else
  568. return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  569. }
  570. catch(Exception e)
  571. {
  572. e.printStackTrace();
  573. }
  574. }
  575.  
  576. return new ResponseEntity<>(HttpStatus.OK);
  577. }
  578.  
  579. @PostMapping(value = "/programs/{courseName}")
  580. public ResponseEntity<String> updatePriorities(@RequestBody String body, @PathVariable String courseName)
  581. {
  582. JSONParser parser = new JSONParser();
  583. JSONArray jsonArray = new JSONArray();
  584. String course = "";
  585.  
  586. try
  587. {
  588. if (!mongoTemplate.collectionExists("priorities"))
  589. {
  590. mongoTemplate.createCollection("priorities");
  591. }
  592.  
  593. jsonArray = (JSONArray) parser.parse(body);
  594.  
  595. byte[] bMail = Base64.getDecoder().decode(courseName);
  596. course = new String(bMail, "UTF-8");
  597. }
  598. catch (Exception e) {
  599. e.printStackTrace();
  600. }
  601.  
  602. /* retrieve all prios from JSON
  603. List<BasicDBObject> prios = new ArrayList<>();
  604. for(int i = 0; i < jsonArray.size(); ++i)
  605. {
  606. JSONObject prio = (JSONObject) jsonArray.get(i);
  607. // prios.add(prio);
  608. }
  609. String prio = (String) jsonArray.si
  610. */
  611.  
  612. DBCollection priosDB = mongoTemplate.getCollection("priorities");
  613.  
  614. try {
  615. if (priosDB != null)
  616. {
  617. BasicDBObject query = new BasicDBObject();
  618. query.put("courseName", course);
  619.  
  620. DBObject entry = new BasicDBObject();
  621. entry.put("courseName", course);
  622. entry.put("prios", jsonArray);
  623.  
  624. // check if entity exists
  625. DBCursor cursor = priosDB.find(query);
  626.  
  627. if(cursor.hasNext())
  628. {
  629. priosDB.remove(query);
  630. priosDB.insert(entry);
  631. }
  632. else
  633. {
  634. priosDB.insert(entry);
  635. }
  636. }
  637. else
  638. {
  639. return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  640. }
  641. }
  642. catch (Exception e) {
  643. e.printStackTrace();
  644. }
  645.  
  646. return new ResponseEntity<>(HttpStatus.OK);
  647. }
  648.  
  649. private List<Room> getRooms(HttpServletRequest request)
  650. {
  651. List<Room> rooms = new ArrayList<>();
  652. BufferedReader br = null;
  653. String row = "";
  654. String separator = ",";
  655.  
  656. try {
  657.  
  658. br = new BufferedReader(new InputStreamReader(
  659. request.getSession().getServletContext().getResourceAsStream("/resources/data/rooms.csv")));
  660. while ((row = br.readLine()) != null) {
  661.  
  662. String[] room = row.replace("Informatik,", "Informatik").split(separator);
  663.  
  664. Room r = new Room();
  665. r.setName(room[0]);
  666. r.setType(room[3]);
  667. try {
  668. r.setSeat(Integer.parseInt(room[1]));
  669. } catch (NumberFormatException e) {
  670. r.setSeat(20);
  671. }
  672.  
  673. //System.out.println("room: "+r.getName());
  674. rooms.add(r);
  675. }
  676.  
  677. } catch (FileNotFoundException e) {
  678. e.printStackTrace();
  679. } catch (IOException e) {
  680. e.printStackTrace();
  681. } finally {
  682. if (br != null) {
  683. try {
  684. br.close();
  685. } catch (IOException e) {
  686. e.printStackTrace();
  687. }
  688. }
  689. }
  690.  
  691. return rooms;
  692. }
  693. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement