Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
Anuj07
Employee
Employee

In the Part 3 of this blog series you send gamification relevant events to HCP gamification service and verified game mechanics assigning points to the user using gamification workbench. Now it’s time to show the user’s achievement in user profile page.

You will retrieve user’s achievement (Experience Points) using gamification service API and you will create a section in the Profile Page to show this achievement.


1. Retrieve user’s achievement:


1. Replace the code in the file GamificationProxy.java located at package com.sap.gamification.plugins.servlet with code GamificationProxy.txt.zip provided as the additional file to this blog. Unzip the file and copy-and-paste the contents to the file GamificationProxy.java.

The class GamificationProxy

The class GamificationProxy has method named getPlayerProfileData() which uses Technical Endpoint to get user achievement by invoking the method getScoresForPlayer(). The HTTP POST request looks like the following:

https://<gamification service host>/gamification/api/tech/JsonRPC?json={"method":"getScoresForPlayer",params":["JIRA_USER@mail.com"]}&app=JIRA

Query parameter

Value

json

method getScoresForPlayer() and parameters (retrieves sum of Experience Points)

app

JIRA (name of the app which contains the game mechanics as defined in the gamification workbench)


Test the class GamificationProxy:

The class GamificationProxy defines a method main() to test gamification service API.

public static void main(String arg []) throws Exception{

    // arg[0] - player Id

EnvironmentUtility.readEnvironmentValues();

GamificationProxy gamificationProxy= new GamificationProxy();

String playerProfileData = gamificationProxy.getPlayerProfileData(arg[0]);

System.out.print(playerProfileData);

}

Run the class GamificationProxy to retrieve sum of Experience Points. Provide environment values and runtime arguments as described below:

1.1. Right click on the node GamificationProxy.java select Run As ->Run configurations. Set environment variables host, user_name and user_password as shown below.

     

Note:

Here host is the host of gamification service (example gamification- p123456789012trial.hanatrial .ondemand.com). You can get this from the Gamification Workbench URL as shown in the screenshot below

The environment variable user_name and user_ password are username and password for HANA Cloud platform respectively.

1.2. If you are developing behind corporate firewall, you need to set two additional environment variables http_proxy_host, http_proxy_port. Set these as shown in the screenshot below

1.3. Set the arguments JIRA_USER@mail.com in the same run configuration as shown in the screenshot below. JIRA_USER@mail.com is the email id  of the player.

1.4. Click on button Run to execute the class GamificationProxy. As a result following output will be displayed in console. Note that there is one entry in results. This entry is with pointName as Experience Points and amount (sum of Experience Points) is 6.

{"result":[{"displayName":"JIRA_USER","image":null,"scorer":"JIRA_USER@mail.com","pointName":"Experience Points","amount":6.0,"rank":0}],"error":null,"type":null}


Create a REST service in JIRA server for gamification data


This service is for retrieving gamification data like Experience points and in the next blog posts you will be using this to retrieve notifications and user achievements like badges, level, leaderboard etc.                         

1. Open the file jira-gamification-plugin/src/main/resources/atlassian-plugin.xml as shown in the screenshot below

2.  Add the following servlet module fragment to the atlassian-plugin element of file atlassian-plugin.xml.

<servlet name="User Achievements Servlet"  i18n-name-key="user-achievements-servlet.name"

            key="user-achievements-servlet"class="com.sap.gamification.plugins.servlet.UserAchievementsServlet">

            <description key="user-achievements-servlet.description">

              The User Achievements Servlet Plugin

            </description>

            <url-pattern>/gamification/*</url-pattern>

</servlet>

The file atlassian-plugin.xml should look like:

The class UserAchievementsServlet:

This receives and responds to requests (like get user profile data) from the browser profile page (described below).


3. Create a class UserAchievementsServlet in the package com.sap.gamification.plugins.servlet. Right click on the folder of the project named jira -Gamification-plugin and select New > Class. Enter Package as com.sap.gamification.plugins.servlet and Class name as UserAchievementsServlet.

Click on button Finish.Substitute the generated code with the following code

package com.sap.gamification.plugins.servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.sap.gamification.plugins.GamificationProxy;

/**

* This receives and responds to requests (like get user profile data) from the

* browser profile page

* */

public class UserAchievementsServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private static final Logger log = LoggerFactory  .getLogger(UserAchievementsServlet.class);

private GamificationProxy gamificationProxy;

    @Override

      public void init() throws ServletException {

              gamificationProxy = new GamificationProxy();

    }

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

              String playerName = request.getRemoteUser();

              if (playerName == null) {

                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);

                    return;

            }

            if (request.getPathInfo().equalsIgnoreCase("/profiledata")) {

                    String playerProfileDataResp = null;

                    try {

                            playerProfileDataResp = gamificationProxy.getPlayerProfileData(playerName);

                        } catch (Exception e) {

                            log.error(" Error during accessing player profile data", e.getMessage());

                        }

                    log.info("Player's Profile data response" + playerProfileDataResp);

                    response.getWriter().println(playerProfileDataResp);

            }

    }


}

2. Show user’s achievement in the Profile Page:


1. Add the following web-panel module fragment to the atlassian-plugin element of file atlassian-plugin.xml.

<web-panel name="gamification-profile-panel" key="gamification-profile-panel" location="webpanels.user.profile.summary.custom" weight="150">

<description key="gamification-profile-panel.description">

The GamificationPanel Plugin

</description>

<resource name="view" type="velocity" location="templates/gamificationProfilePanel.vm" />

</web-panel>

The file atlassian-plugin.xml should look like:

The Web Panel gamification-profile-panel

Web Panel allows JIRA plugins to define panels, or sections, on an HTML page.

In current case it is used to create a new panel to show user’s achievement. The location“webpanels.user.profile.summary.custom” is specified which means this will be inserted into user Profile Page.

2. Create a folder with name templates in folder /src/main/resources as shown in the screenshot below

3. Create a file with name gamificationProfilePanel.vm in folder /src/main/resources/templates with the following content.


<html>

<body>

<h2>Reputation</h2><br>

<p id="exPoints"></p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>

_getProfileData ();

function _getProfileData (){

      jQuery.get("/jira/plugins/servlet/gamification/profiledata", <!-- call for UserAchievementsServlet->

                  function(response, status){

                            if(status==="success"){

                                var data= JSON.parse(response);

                                var resultArray = data.result;

                                resultArray = jQuery.grep(resultArray, function(item) {

                                                    return ( item.pointName === "Experience Points" );

                                                    });

                              resultArray.forEach((function(item) {jQuery("#exPoints").append(

                              item.pointName + ": " + item.amount)}))

                          }                   

                });

  }

       

</script>

</body>

</html>

The file gamificationProfilePanel.vm is used to render the panel which will show user’s achievement in the user profile page. The file gamificationProfilePanel.vm has a function _getProfileData which calls REST Service to get user profile data.

4. Open a command prompt and run the following set of commands to set environment variables.

set user_name=<HANA Cloud Platform user name>

set user_password=<HANA Cloud Platform password>

set host = < gamification service host>

If you are running this application behind the firewall you also need to set http_proxy_host and http_proxy_port by using following commands if not then please ignore these.

set http_proxy_host= <Http proxy name>

set http_proxy_port=<Http port number>

5. Change directory to the folder jira-gamification-plugin and run the following command

atlas-run

6. Once JIRA has started successfully, open the URL printed in the message.

7. Log in with username JIRA_USER@mail.com and switch to the profile page as shown below in the screenshot.

Experience points will be visible in the section Reputation of the user profile page


Let’s validate users achievements are reflected in the profile page.


Create a new issue (in the same way as you created in Step 9-10 of Test integration with JIRA section of previous blog) and refresh the profile page.Verify that the value of Experience Points is advancing.Congratulation :smile: you are done with Part 4. In the next blog post you will show notifications in JIRA when Experience Points are assigned to a user.