Moodle and Java | Retrieving users’ data from Moodle using External Java Application

Retrieving users’ data from Moodle using External Java Application

We can write a basic REST moodle client code using Java to fetch users’ records from moodle. Before writing the code, you need to perform below steps in Moodle which are required in order to fetch the data:

1. Create external web service for your applicatiWe can write a basic REST moodle client code using Java to fetch users’ records from moodle. on in Moodle using following path:

Site Administration -> Plugins -> Web services -> External services

2. Create token for your newly created custom web service.

3. Under Manage Protocol tab, enable Rest Protocol as the application will be fetching data using Rest Protocol.

4. After that, click on ‘Functions’ link on External services page beside your web service and add method ‘core_user_get_users’ method.

5. Make sure to provide all necessary permissions to the user who will be accessing this web service through java application.

6. After performing above steps, open your java application, create a file and paste below code:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * REST MOODLE Client
 * It's very basic. You'll have to write the JavaObject2POST code.
 *
 */
public class RestJsonMoodleClient {

/**
* Do a REST call to Moodle. Result are displayed in the console log.
* @param args the command line arguments
*/
public static void main(String[] args) throws ProtocolException, IOException 
{

/// NEED TO BE CHANGED
String token = "Your token";
String domainName = "http://localhost/moodle"; // Your Moodle domain

/// REST RETURNED VALUES FORMAT
String restformat = "xml"; //Also possible in Moodle 2.2 and later: 'json'
       
//Setting it to 'json' will fail all calls on earlier Moodle version
        
if (restformat.equals("json")) 
{
   restformat = "&moodlewsrestformat=" + restformat;
} 

else 
{
    restformat = "";
}
        
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
String functionName = "core_user_get_users";
        
String urlParameters = "criteria[0][key]=id&criteria[0][value]=2";        
              
/// REST CALL

// Send request

String serverurl = domainName + "/webservice/rest/server.php" + "?wstoken=" + token + "&wsfunction=" + functionName;
        
HttpURLConnection con = (HttpURLConnection) new URL(serverurl).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
con.setDoOutput(true);
con.setUseCaches (false);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream (
con.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();

//Get Response

InputStream is =con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) 
   {
       response.append(line);
       response.append('\r');
   }
        rd.close();
        System.out.println(response.toString());
    }
}

Be careful while providing token value, domain name and method name as they should be correct.

Above piece of code will fetch all fields of a user based on its id from Moodle database.

Output :

<?xml version="1.0" encoding="UTF-8" ?>
<RESPONSE>
<SINGLE
<KEY name="users"><MULTIPLE>
<SINGLE>
<KEY name="id"><VALUE>2</VALUE>
</KEY>
<KEY name="username"><VALUE>admin</VALUE>
</KEY>
<KEY name="firstname"><VALUE>Admin</VALUE>
</KEY>
<KEY name="lastname"><VALUE>User</VALUE>
</KEY>
<KEY name="fullname"><VALUE>Admin User</VALUE>
</KEY<
<KEY name="email"><VALUE>nitin.pant@1234.com</VALUE>
</KEY>
<KEY name="address"><VALUE null="null"/>
</KEY>
<KEY name="phone1"><VALUE null="null"/>
</KEY>
<KEY name="phone2"><VALUE null="null"/>
</KEY>
<KEY name="icq"><VALUE null="null"/>
</KEY>
<KEY name="skype"><VALUE null="null"/>
</KEY>
<KEY name="yahoo"><VALUE null="null"/>
</KEY>
<KEY name="aim"><VALUE null="null"/>
</KEY>
<KEY name="msn"><VALUE null="null"/>
</KEY>
<KEY name="department"><VALUE></VALUE>
</KEY>
<KEY name="institution"><VALUE null="null"/>
</KEY>
<KEY name="idnumber"><VALUE null="null"/>
</KEY>
<KEY name="interests"><VALUE null="null"/>
</KEY>
<KEY name="firstaccess">VALUE>1454058425</VALUE>
</KEY>
<KEY name="lastaccess"><VALUE>1461847753</VALUE>
</KEY>
<KEY name="auth"><VALUE null="null"/>
</KEY>
<KEY name="confirmed"><VALUE null="null"/>
</KEY>
<KEY name="lang"><VALUE null="null"/>
</KEY>
<KEY name="calendartype"><VALUE null="null"/>
</KEY>
<KEY name="theme"><VALUE null="null"/>
</KEY>
<KEY name="timezone"><VALUE null="null"/>
</KEY>
<KEY name="mailformat"><VALUE null="null"/>
</KEY>
<KEY name="description"><VALUE></VALUE>
</KEY>
<KEY name="descriptionformat"><VALUE>1</VALUE>
</KEY>
<KEY name="city"><VALUE>Chandigarh</VALUE>
</KEY>
<KEY name="url"><VALUE null="null"/>
</KEY>
<KEY name="country"><VALUE>IN</VALUE>
</KEY>
</RESPONSE>

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

One comment

  1. this is a very good example
    can you provide the implementation for ‘core_user_create_users’ function to create new user in moodle from an external java application?
    i have tried it but get errors like ‘Invalid Parameter Values’ .

Leave a Reply

Your email address will not be published. Required fields are marked *