1 /************************************************************************************
3 * Copyright (c) 2008 Igor Barma, Eric Brun, Alexandre Desoubeaux, Christian Martel.
5 * Ce logiciel est diffuse sous les termes et conditions de la licence CECILL.
6 * Voir le fichier joint Licence_CeCILL_V2-fr.txt pour plus de details.
8 ************************************************************************************/
9 package com.pentila.evalcomp.manager.ressource.moodle;
11 import java.math.BigInteger;
12 import java.net.MalformedURLException;
14 import java.rmi.RemoteException;
15 import java.util.ArrayList;
16 import java.util.List;
20 import com.pentila.evalcomp.domain.transit.RessourceFolder;
21 import com.pentila.evalcomp.domain.transit.RessourceItem;
22 import com.pentila.evalcomp.domain.transit.RessourceMoodleCourse;
23 import com.pentila.evalcomp.moodlews.CourseRecord;
24 import com.pentila.evalcomp.moodlews.EditUsersInput;
25 import com.pentila.evalcomp.moodlews.GetCoursesReturn;
26 import com.pentila.evalcomp.moodlews.GetUsersReturn;
27 import com.pentila.evalcomp.moodlews.LoginReturn;
28 import com.pentila.evalcomp.moodlews.MoodleWSBindingStub;
29 import com.pentila.evalcomp.moodlews.UserDatum;
30 import com.pentila.evalcomp.moodlews.UserRecord;
32 // TODO: Auto-generated Javadoc
34 * The Class DefinitionManager.
36 public class MoodleWebService {
38 org.slf4j.Logger logger = org.slf4j.LoggerFactory
39 .getLogger(MoodleWebService.class);
42 /** The moodle wsurl. */
43 private String moodleWSURL = "http://localhost:8890/moodle19/wspp/service_pp.php";
45 /** The user login. */
46 private String userLogin = "admin";
49 private String userPWD = "12345";
51 /** The moodle base url. */
52 private String moodleBaseURL = "http://193.48.120:8890/moodle19/course/view.php?id={0}";
54 /** The role teacher. */
55 private String roleTeacher = "3";
57 /** The role student. */
58 private String roleStudent = "5";
61 private static MoodleWSBindingStub stub = null;
64 private static String sesskey = "";
67 private static BigInteger client = null;
70 * Instantiates a new moodle web service.
72 public MoodleWebService() {
79 * @return true, if successful
81 private boolean moodleLogin() {
84 endPoint = new URL(moodleWSURL);
85 } catch (MalformedURLException e1) {
87 logger.debug("Error modleLogin : url = " + moodleWSURL);
93 stub = new MoodleWSBindingStub(endPoint, null);
94 } catch (Exception e) {
95 logger.debug("Error in MoodleWSBindingStub : " + e.getMessage());
99 LoginReturn loginReturn;
101 loginReturn = stub.login(userLogin, userPWD);
102 } catch (RemoteException e) {
104 logger.debug("Error on login : " + e.getMessage());
105 logger.debug("Username = " + userLogin + " PWD = " + userPWD);
109 sesskey = loginReturn.getSessionkey();
110 client = loginReturn.getClient();
117 * @return true, if successful
119 private static boolean moodleLogout() {
120 boolean logoutReturn;
122 logoutReturn = stub.logout(client, sesskey);
123 } catch (RemoteException e) {
130 * Gets the workspace.
132 * @param login the login
134 * @return the workspace
136 public RessourceItem getWorkspace(String login) {
137 // TODO Auto-generated method stub
138 RessourceFolder moodleCourses = new RessourceFolder();
139 moodleCourses.setEditable(false);
141 moodleCourses.setUrl("");
142 boolean log = moodleLogin();
144 return moodleCourses;
146 List<RessourceItem> results = new ArrayList<RessourceItem>();
148 results = _getMoodleCourses(login);
149 } catch (RemoteException e) {
150 logger.debug("Error in _getMoodleCourses = " + e.getMessage());
152 moodleCourses.setItemList(results);
154 return moodleCourses;
158 * _get moodle courses.
160 * @param login the login
162 * @return the list< ressource item>
164 * @throws RemoteException the remote exception
166 public List<RessourceItem> _getMoodleCourses(String login)
167 throws RemoteException {
169 List<RessourceItem> tcourses = new ArrayList<RessourceItem>();
171 logger.debug("Start _getMoodleCourses for " + login);
173 GetCoursesReturn myCourses = stub.get_my_courses_byusername(client,
174 sesskey, login, "fullname");
176 logger.debug("get_my_courses_byusername : " + myCourses);
177 logger.debug("Courses getCourses() is : " + myCourses.getCourses());
178 logger.debug("Courses their size is : " + myCourses.getCourses().length);
181 for (CourseRecord course : myCourses.getCourses()) {
182 RessourceMoodleCourse myTcourse = getTCourseRecordFromCourseRecord(course);
183 myTcourse.setPath(moodleBaseURL);
185 logger.debug("Course name ? : " + myTcourse.getName());
187 tcourses.add(myTcourse);
193 * Sets the permission.
196 * @param suid the suid
197 * @param role the role
199 public void setPermission(RessourceItem rd, Set<String> suid,
202 String roleId = roleTeacher;
203 if (!role.equals("")) {
204 roleId = roleStudent;
206 boolean log = moodleLogin();
208 for (String username : suid) {
210 assignRoleToUserInCourse(username, rd.getRessourceKey(),
212 } catch (RemoteException e) {
213 // TODO Auto-generated catch block
222 * Removes the permission.
225 * @param suid the suid
226 * @param role the role
228 public void removePermission(RessourceItem rd, Set<String> suid,
231 String roleId = roleTeacher;
232 if (!role.equals("")) {
233 roleId = roleStudent;
235 boolean log = moodleLogin();
237 for (String username : suid) {
239 unassignRoleToUserInCourse(username, rd.getRessourceKey(),
241 } catch (RemoteException e) {
242 // TODO Auto-generated catch block
251 * Assign role to user in course.
253 * @param username the username
254 * @param courseid the courseid
255 * @param roleid the roleid
257 * @throws RemoteException the remote exception
259 private static void assignRoleToUserInCourse(String username,
260 String courseid, String roleid) throws RemoteException {
261 UserRecord myNewUser = getUser(username);
262 if (myNewUser.getId().equals(new BigInteger("0"))) {
263 // si le user n'existe pas nous le creons
264 addUser(username, true);
265 myNewUser = getUser(username);
267 String[] userids = new String[1];
268 userids[0] = myNewUser.getUsername();
270 .assignUsers(client, sesskey, courseid, userids, "username",
275 * Unassign role to user in course.
277 * @param username the username
278 * @param courseid the courseid
279 * @param roleid the roleid
281 * @throws RemoteException the remote exception
283 private static void unassignRoleToUserInCourse(String username,
284 String courseid, String roleid) throws RemoteException {
285 UserRecord myNewUser = getUser(username);
286 if (!myNewUser.getId().equals(new BigInteger("0"))) {
287 String[] userids = new String[1];
288 userids[0] = myNewUser.getUsername();
289 stub.unassignUsers(client, sesskey, courseid, userids, "username",
297 * @param username the username
301 * @throws RemoteException the remote exception
303 private static UserRecord getUser(String username) throws RemoteException {
304 GetUsersReturn myUser = stub.get_user(client, sesskey, username,
306 UserRecord[] usersFound = myUser.getUsers();
307 for (UserRecord uf : usersFound) {
308 if (uf.getUsername().equals(username)) {
312 return usersFound[0];
318 * @param username the username
319 * @param casAuth the cas auth
321 * @throws RemoteException the remote exception
323 private static void addUser(String username, boolean casAuth)
324 throws RemoteException {
326 EditUsersInput usersToAdd = new EditUsersInput();
327 UserDatum[] usersDatumToAdd = new UserDatum[1];
328 UserRecord myNewUser = getUser(username);
329 if (myNewUser.getId().equals(new BigInteger("0"))) {
330 UserDatum myUserToAdd = getUserDatumFromUserRecord(myNewUser);
331 myUserToAdd.setAction("Add");
332 myUserToAdd.setUsername(username);
333 myUserToAdd.setDescription("");
335 myUserToAdd.setAuth("cas");
337 myUserToAdd.setAuth("manual");
340 usersDatumToAdd[0] = myUserToAdd;
341 usersToAdd.setUsers(usersDatumToAdd);
343 stub.edit_users(client, sesskey, usersToAdd);
349 * Gets the user datum from user record.
353 * @return the user datum from user record
355 private static UserDatum getUserDatumFromUserRecord(UserRecord ur) {
356 String description = "none";
357 if (ur.getDescription() != null) {
358 description = ur.getDescription();
360 UserDatum ud = new UserDatum("Update", ur.getConfirmed(), ur
361 .getPolicyagreed(), ur.getDeleted(), ur.getUsername(),
362 "manual", "", ur.getIdnumber(), ur.getFirstname(), ur
363 .getLastname(), ur.getEmail(), ur.getIcq(), ur
364 .getSkype(), ur.getYahoo(), ur.getAim(), ur.getMsn(),
365 ur.getPhone1(), ur.getPhone2(), ur.getInstitution(), ur
366 .getDepartment(), ur.getAddress(), ur.getCity(), ur
367 .getCountry(), ur.getLang(), ur.getTimezone(), ur
368 .getLastip(), description, new BigInteger("1"));
373 * Gets the t course record from course record.
377 * @return the t course record from course record
379 private RessourceMoodleCourse getTCourseRecordFromCourseRecord(
381 RessourceMoodleCourse tcr = new RessourceMoodleCourse(cr.getError(), cr
382 .getId(), cr.getCategory(), cr.getSortorder(),
383 cr.getPassword(), cr.getFullname(), cr.getShortname(), cr
384 .getIdnumber(), cr.getSummary(), cr.getFormat(), cr
385 .getShowgrades(), cr.getNewsitems(), cr.getTeacher(),
386 cr.getTeachers(), cr.getStudent(), cr.getStudents(), cr
387 .getGuest(), cr.getStartdate(), cr.getEnrolperiod(), cr
388 .getNumsections(), cr.getMarker(), cr.getMaxbytes(), cr
389 .getVisible(), cr.getHiddensections(), cr
390 .getGroupmode(), cr.getGroupmodeforce(), cr.getLang(),
391 cr.getTheme(), cr.getCost(), cr.getTimecreated(), cr
392 .getTimemodified(), cr.getMetacourse());
397 * Gets the moodle wsurl.
399 * @return the moodle wsurl
401 public String getMoodleWSURL() {
406 * Sets the moodle wsurl.
408 * @param moodleWSURL the new moodle wsurl
410 public void setMoodleWSURL(String moodleWSURL) {
411 this.moodleWSURL = moodleWSURL;
415 * Gets the user login.
417 * @return the user login
419 public String getUserLogin() {
424 * Sets the user login.
426 * @param userLogin the new user login
428 public void setUserLogin(String userLogin) {
429 this.userLogin = userLogin;
435 * @return the user pwd
437 public String getUserPWD() {
444 * @param userPWD the new user pwd
446 public void setUserPWD(String userPWD) {
447 this.userPWD = userPWD;
451 * Gets the moodle base url.
453 * @return the moodle base url
455 public String getMoodleBaseURL() {
456 return moodleBaseURL;
460 * Sets the moodle base url.
462 * @param moodleBaseURL the new moodle base url
464 public void setMoodleBaseURL(String moodleBaseURL) {
465 this.moodleBaseURL = moodleBaseURL;
469 * Gets the role teacher.
471 * @return the role teacher
473 public String getRoleTeacher() {
478 * Sets the role teacher.
480 * @param roleTeacher the new role teacher
482 public void setRoleTeacher(String roleTeacher) {
483 this.roleTeacher = roleTeacher;
487 * Gets the role student.
489 * @return the role student
491 public String getRoleStudent() {
496 * Sets the role student.
498 * @param roleStudent the new role student
500 public void setRoleStudent(String roleStudent) {
501 this.roleStudent = roleStudent;
505 * Return the url to the moodle ressource.
507 * @param pluginKey the plugin key
508 * @param ressourceKey the ressource key
509 * @param mode the mode
511 * @return the ressource url
513 public String getRessourceUrl(String pluginKey, String ressourceKey,
516 if (mode.equals("")) {
517 // acces utilisateur simple
518 url = getMoodleBaseURL() + "/course/view.php?id=" + ressourceKey;
520 // acces teacher donc visualisation des resultats
521 boolean log = moodleLogin();
524 UserRecord myUser = getUser(mode);
525 url = getMoodleBaseURL()
526 + "/course/user.php?mode=complete&id="
527 + ressourceKey + "&user="
528 + myUser.getId().toString();
529 } catch (RemoteException e) {
530 // On retourne l'acces vers le cours
531 url = getMoodleBaseURL() + "/course/view.php?id="
536 url = getMoodleBaseURL() + "/course/view.php?id="
543 /****** METHODES ISSUES DES TESTS DE COMMUNICATION AVEC MOODLE *****/
545 * public static void main(String[] args) throws RemoteException,
546 * MalformedURLException {
550 * //modifyCourseTest(); //listUsersTest(); //UserRecord myUser =
551 * getUserTest("stagiaire1"); //delUserTest(myUser);
552 * //addUserTest("stagiaire1", true); // 5 --> student // 3 --> teacher
553 * //assignRoleToUserInCourseTest("stagiaire1", "7", "5");
554 * //assignRoleToUserInCourseTest("stagiaire1", "7", "3");
555 * unassignRoleToUserInCourseTest("stagiaire1", "7", "5");
561 * private static boolean moodleLogin() { URL endPoint; try { endPoint = new
562 * URL("http://localhost:8890/moodle19/wspp/service_pp.php"); } catch
563 * (MalformedURLException e1) { return false; }
565 * try { stub = new MoodleWSBindingStub(endPoint, null); } catch (AxisFault
566 * e) { e.printStackTrace(); }
568 * LoginReturn loginReturn; try { loginReturn = stub.login("admin",
569 * "12345"); } catch (RemoteException e) { return false; } sesskey =
570 * loginReturn.getSessionkey(); client = loginReturn.getClient(); return
573 * private static boolean moodleLogout() { boolean logoutReturn; try {
574 * logoutReturn = stub.logout(client, sesskey); } catch (RemoteException e)
575 * { return false; } return logoutReturn; }
577 * private static void assignRoleToUserInCourseTest(String username, String
578 * courseid, String roleid) throws RemoteException { UserRecord myNewUser =
579 * getUserTest(username); if (!myNewUser.getId().equals(new
580 * BigInteger("0"))) { String[] userids = new String[1]; userids[0] =
581 * myNewUser.getUsername(); AssignUsersReturn ret = stub.assignUsers(client,
582 * sesskey, courseid, userids, "username", roleid);
583 * System.out.println(ret.getUsers().length); } }
585 * private static void unassignRoleToUserInCourseTest(String username,
586 * String courseid, String roleid) throws RemoteException { UserRecord
587 * myNewUser = getUserTest(username); if (!myNewUser.getId().equals(new
588 * BigInteger("0"))) { String[] userids = new String[1]; userids[0] =
589 * myNewUser.getUsername(); UnassignUsersReturn ret =
590 * stub.unassignUsers(client, sesskey, courseid, userids, "username",
591 * roleid); System.out.println(ret.getUsers().length); } }
593 * private static void listUsersTest() throws RemoteException {
595 * GetUsersReturn myUser = stub.get_user(client, sesskey, null, null);
596 * UserRecord[] usersFound = myUser.getUsers();
597 * System.out.println("------"); for (UserRecord uf: usersFound) {
598 * System.out.println(uf.getUsername()); System.out.println(uf.getId()); }
599 * System.out.println("------");
603 * private static UserRecord getUserTest(String username) throws
606 * GetUsersReturn myUser = stub.get_user(client, sesskey, username,
607 * "username"); UserRecord[] usersFound = myUser.getUsers(); for (UserRecord
608 * uf: usersFound) { if (uf.getUsername().equals(username)) { return uf; } }
609 * return usersFound[0]; }
611 * private static void delUserTest(UserRecord userRecord) throws
614 * EditUsersInput usersToDelete = new EditUsersInput(); UserDatum[]
615 * usersDatumToDelete = new UserDatum[1]; UserDatum myUserToDelete =
616 * getUserDatumFromUserRecord(userRecord);
617 * myUserToDelete.setAction("Delete"); usersDatumToDelete[0] =
618 * myUserToDelete; usersToDelete.setUsers(usersDatumToDelete);
620 * stub.edit_users(client, sesskey, usersToDelete);
624 * private static void addUserTest(String username, boolean casAuth) throws
627 * EditUsersInput usersToAdd = new EditUsersInput(); UserDatum[]
628 * usersDatumToAdd = new UserDatum[1]; UserRecord myNewUser =
629 * getUserTest(username); if (myNewUser.getId().equals(new BigInteger("0")))
630 * { UserDatum myUserToAdd = getUserDatumFromUserRecord(myNewUser);
631 * myUserToAdd.setAction("Add"); myUserToAdd.setUsername(username);
632 * myUserToAdd.setDescription(""); if (casAuth) {
633 * myUserToAdd.setAuth("cas"); } else { myUserToAdd.setAuth("manual"); }
635 * usersDatumToAdd[0] = myUserToAdd; usersToAdd.setUsers(usersDatumToAdd);
637 * stub.edit_users(client, sesskey, usersToAdd); }
642 * private static void modifyCourseTest() throws RemoteException {
644 * CourseRecord myCourse = null;
646 * GetCategoriesReturn myCategories = stub.get_categories(client, sesskey);
648 * for (CategoryRecord cat: myCategories.getCategories()) {
649 * System.out.println("Dans la categorie: " + cat.getName());
650 * GetCoursesReturn myCourses = stub.get_courses_bycategory(client, sesskey,
651 * cat.getId()); for (CourseRecord course: myCourses.getCourses()) {
652 * System.out.println("Le cours " + course.getFullname() + "(" +
653 * course.getId() + ")");
657 * UserRecord[] te=stub.get_teachers(client, sesskey, "" + course.getId(),
658 * "id").getUsers(); for (int i=0; i< te.length;i++) System.out.println (
659 * te[i].getError()+"\t"+te[i].getId()+ "\t"+te[i].getUsername()+
660 * "\t"+te[i].getFirstname()+ "\t"+te[i].getLastname()+
661 * "\t"+te[i].getEmail() ); } }
663 * EditCoursesInput editedCourses = new EditCoursesInput();
665 * CourseDatum cD = getCourseDatumFromCourseRecord(myCourse);
667 * cD.setFullname("Ohh ca marche"); cD.setSummary("super la description!!");
668 * System.out.println(cD.getIdnumber()); System.out.println(cD.getId());
670 * System.out.println(cD.getFullname());
672 * //Set<CourseDatum> coursesDatumSet = new HashSet<CourseDatum>();
673 * //coursesDatumSet.add(cD);
675 * CourseDatum[] coursesDatumArray = new CourseDatum[1];//(CourseDatum[])
676 * coursesDatumSet.toArray(); coursesDatumArray[0] = cD;
677 * editedCourses.setCourses(coursesDatumArray); EditCoursesOutput
678 * returnCourses = stub.edit_courses(client, sesskey, editedCourses);
679 * System.out.println(returnCourses.getCourses().length);
681 * CourseRecord returnedCourse = ((CourseRecord)
682 * returnCourses.getCourses()[0]); System.out.println( returnedCourse );
683 * System.out.println( returnedCourse.getFullname() ); System.out.println(
684 * returnedCourse.getError() );
688 * private static CourseDatum getCourseDatumFromCourseRecord(CourseRecord
689 * cr) { CourseDatum tcr = new CourseDatum( "Update", cr.getId(),
690 * cr.getCategory(), cr.getSortorder(), cr.getPassword(), cr.getFullname(),
691 * cr.getShortname(), cr.getIdnumber(), cr.getSummary(), cr.getFormat(),
692 * cr.getShowgrades(), cr.getNewsitems(), cr.getTeacher(), cr.getTeachers(),
693 * cr.getStudent(), cr.getStudents(), cr.getGuest(), cr.getStartdate(),
694 * cr.getEnrolperiod(), cr.getNumsections(), cr.getMarker(),
695 * cr.getMaxbytes(), cr.getVisible(), cr.getHiddensections(),
696 * cr.getGroupmode(), cr.getGroupmodeforce(), cr.getLang(), cr.getTheme(),
697 * cr.getCost(), cr.getTimecreated(), cr.getTimemodified(),
698 * cr.getMetacourse() ); return tcr; }
700 * private static UserDatum getUserDatumFromUserRecord(UserRecord ur) {
701 * String description = "none"; if (ur.getDescription() != null) {
702 * description = ur.getDescription(); } UserDatum ud = new UserDatum(
703 * "Update", ur.getConfirmed(), ur.getPolicyagreed(), ur.getDeleted(),
704 * ur.getUsername(), "manual", "", ur.getIdnumber(), ur.getFirstname(),
705 * ur.getLastname(), ur.getEmail(), ur.getIcq(), ur.getSkype(),
706 * ur.getYahoo(), ur.getAim(), ur.getMsn(), ur.getPhone1(), ur.getPhone2(),
707 * ur.getInstitution(), ur.getDepartment(), ur.getAddress(), ur.getCity(),
708 * ur.getCountry(), ur.getLang(), ur.getTimezone(), ur.getLastip(),
709 * description, new BigInteger("1")); return ud; }