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: 
4,615
In attempt to attract the 9 million happy Java developers to the Dirigible community, we have introduced Java as runtime language. Yes, finally we can run our Java code in the cloud the way we like it, with Dirigible.
To explore the new "Java Services" features, we’ll create a simple "gamification" project. It will contain only one service and a couple of helper classes. We’ll take advantage of Java by using some of the most popular classes and capabilities in the language, such as Collections, Comparable, and of course Generics. The service will be responsible for calculating and distributing the results of the gamification. We’ll deliver the scores in two manners – displaying them to the user, or sending them via e-mail.
Following the already known development process, we’ll go to the Trial instance http://trial.dirigible.io (or your own Dirigible).
  • We start by creating a new project named gamification. If you have troubles creating a new project, please
    refer to the previous posts:
NOTE: Since we’ll create a very simple application, let's differ from the already known vertical application development scenario. Instead of first creating a domain model and then exposing it through RESTful services, we’ll jump one step ahead and create a Java service.
  • From the main menu, select New -> Scripting Service -> Java Service.
  • Name it EmployeeScore. This will be the main entity.
  • Replace the generated file content with the following code:
package gamification;
public class EmployeeScore implements Comparable<EmployeeScore> {
    private String name;
    private int score;
    public EmployeeScore(String name, int score) {
        this.name = name;
        this.score = score;
    }
    @Override
    public int compareTo(EmployeeScore o) {
        // Descending order
        int result = (int) (o.score - this.score);
        if (result == 0) {
            result = o.name.compareTo(this.name);
        }
        return result;
    }
    @Override
    public String toString() {
        return name + " - " + score + " point(s)";
    }
}
 
  • Create another Java service.
  • Name it Scores. This will be a helper class that will provide you with sample data.
  • Replace the generated file content with the following code:
package gamification;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Scores {
    private static final int MAX_SCORE = 100;
    private static final Random RANDOM = new Random();
    public static List<EmployeeScore> calculate(List<String> employees) {
        List<EmployeeScore> result = new ArrayList<EmployeeScore>();
        for (String name : employees) {
            result.add(new EmployeeScore(name, getRandomScore()));
        }
        return result;
    }
    private static int getRandomScore() {
        return RANDOM.nextInt(MAX_SCORE);
    }
}
  • Generate one more Java service.
  • Name it just Service. This will be the service to process the incoming requests.
  • Again, replace the generated file content with the following code:


package gamification;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sap.dirigible.runtime.mail.MailSender;
public class Service {

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);

    private static final String FROM = "dirigible@sap.com";
    private static final String TITLE = "Gamification Scores";

    public void service(HttpServletRequest request, HttpServletResponse response, Map<String, Object> scope) throws Exception {
        List<EmployeeScore> scores = Scores.calculate(getEmployees());
        Collections.sort(scores);
        String body = getBody(scores);
        String sendTo = request.getParameter("sendTo");

        if(isValidEmailAddress(sendTo)) {
            MailSender mailSender = (MailSender) scope.get("mail");
            mailSender.sendMail(FROM, sendTo, TITLE, body);
            response.getWriter().println("Email sent to \"" + sendTo + "\"");
        } else {
            response.getWriter().println(body);
        }
    }

    private static List<String> getEmployees() {
        return Arrays.asList(new String[] { "Yordan", "Nedelcho", "Martin", "Peter", "John" });
    }
    private static String getBody(List<EmployeeScore> employeeScores) {
        StringBuilder result = new StringBuilder();
        for(EmployeeScore employeeScore : employeeScores) {
            result.append(employeeScore.toString() + "\n");
        }
        return result.toString();
    }
    private static boolean isValidEmailAddress(final String email) {
        boolean isValid = false;
        if(email != null) {
            Matcher matcher = pattern.matcher(email);
            isValid = matcher.matches();
        }
        return isValid;
    }
}
  • Good! We are ready with this simple application. Let’s now test it!
    • To display the scores: open the Preview tab, and from the Workspace Explorer, click on Service.
    • To send the results to your e-mail:  in the URL bar, append "?sendTo=<your_e-mail>"
Enjoy!

References:

3 Comments