offerwall_demo_form.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Offerwall Demo</title>
</head>
<body bgcolor="#ffffff" >
<p> </p>

<table align="center" bgcolor="#004000" border="0" cellpadding="3" cellspacing="1" width="780">
    <tbody>
    <tr>
        <td> </td>
    </tr>
    <tr>
        <td bgcolor="#ffffff">
            <p align="center"> </p>

            <h1 align="center">Offerwall Demo</h1>

            <h2 align="left">Enter panelist profile:</h2>

            <form action="offerwall_demo.jsp" method="post" name="entryForm">
                <p>Birthdate:  <input maxlength="10" name="birthdate" size="10" type="text" style="color:#888;"
                                           value="yyyy-mm-dd" onfocus="inputFocus(this)" onblur="inputBlur(this)"/></p>

                <p>Gender:  <select name="gender">
                    <option>Male</option>
                    <option>Female</option>
                </select></p>

                <p>Postal Code:  <input maxlength="10" name="postalCode" size="10" type="text" /></p>

                <p>Country:  <input maxlength="2" name="country" size="2" type="text" /></p>

                <p><input name="submit" type="submit" value="Submit" /><input name="reset" type="reset" value="Reset" /></p>
            </form>

            <p> </p>

            <p> </p>
        </td>
    </tr>
    <tr>
        <td bgcolor="#004000"> </td>
    </tr>
    </tbody>
</table>

<p> </p>

<p> </p>

</body>

<script>
    function inputFocus(i){
        if(i.value==i.defaultValue){ i.value=""; i.style.color="#000"; }
    }
    function inputBlur(i){
        if(i.value==""){ i.value=i.defaultValue; i.style.color="#888"; }
    }
</script>
</html>

offerwall_demo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.researchforgood.api.RFGAPI" %>
<%@ page import="org.json.simple.JSONObject" %>
<%@ page import="org.json.simple.parser.JSONParser" %>
<%@ page import="org.json.simple.JSONArray" %>
<%@ page import="org.json.simple.parser.ParseException" %>
<%@ page import="org.bson.types.ObjectId" %>
<html>
<head>
    <title>Offerwall Demo</title>
</head>
<body>
    <h1>Offerwall Demo</h1>
    <%
        StringBuilder sb = new StringBuilder("{ command: \"offerwall/query/1\", rid: \"").append(new ObjectId()).append("\", ");

        String birthdate = request.getParameter("birthdate");
        if (birthdate == null || birthdate.isEmpty() || birthdate.equalsIgnoreCase("yyyy-mm-dd")) {
            %><p>Missing birthday</p><%
            return;
        }
        sb.append("birthday:\"").append(birthdate).append("\", ");

        String gender = request.getParameter("gender");
        sb.append("gender:\"").append(gender).append("\", ");

        String postalCode = request.getParameter("postalCode");
        if (postalCode == null || postalCode.isEmpty()) {
            %><p>Missing postal code</p><%
            return;
        }
        sb.append("postalCode:\"").append(postalCode).append("\", ");

        String country = request.getParameter("country");
        if (country == null || country.length() != 2) {
            %><p>Missing or invalid country</p><%
            return;
        }
        sb.append("country:\"").append(country).append("\" }");

        String resp = RFGAPI.sendCommand(sb.toString());
        System.out.println(resp);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = null;
        try {
            jsonObject = (JSONObject) jsonParser.parse(resp);
        } catch (ParseException e) {
            //
        }
        if (jsonObject == null) {
            %><p>Failed to parse API response</p><%
            return;
        }
        Long result = (Long) jsonObject.get("result");
        if (result != 0) {
            %><p><% out.print(jsonObject.get("message")); %></p><%
            return;
        }
        JSONObject respObj = (JSONObject) jsonObject.get("response");
        JSONArray surveys = (JSONArray) respObj.get("surveys");
        if (surveys == null || surveys.isEmpty()) {
            %><p>No matching surveys</p><%
            return;
        }

    %>
    <table border="1">
        <tr>
            <%
                for (Object key : ((JSONObject) surveys.get(0)).keySet()) {
            %>
            <th>
                <%
                    out.print(key);
                %>
            </th>
            <%
                }
            %>
        </tr>
        <%
            for(int i = 0; i < surveys.size(); i++) {
                JSONObject survey = ((JSONObject) surveys.get(i));
        %>
        <tr>
            <%
                for (Object key : survey.keySet()) {
            %>
            <td>
                <%
                    if (survey.get(key) == null) {
                        out.print("");
                    } else if (((String)key).endsWith("icon")){
                        out.print("<img src=\"" + survey.get(key) + "\"/>");
                    } else if (((String)key).endsWith("url")){
                        out.print("<a href=\"" + survey.get(key) + "\" target=\"_blank\">" + survey.get(key) + "</a>");
                    } else {
                        out.print(survey.get(key));
                    }
                %>
            </td>
            <%
                }
            %>
        </tr>
        <%
            }
        %>
    </table>
</body>
</html>

RFGAPI.java

package com.researchforgood.api;

/**
 * Created by mkappel on 8/8/2016.
 */
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class RFGAPI
{
     private static final String apiURL = "http://www.saysoforgood.com/API";
     private static final String apid = "533dc12aa46ba5da8d801f84"; // put your key here
     private static final String secretHex = "5a7540114c1009b363dc19bf75b0e7bc"; // put your secret here

     public static void main(String[] args) throws Exception {
          String command = "{ \"command\" : \"test/copy/1\" , \"data1\" : \"THIS IS A TEST\"}";
          String response = sendCommand(command);
          System.out.println(response);
     }

     public static String sendCommand(String command) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
          long time = System.currentTimeMillis()/1000;
          Mac mac = Mac.getInstance("HmacSHA1");
          mac.init(new SecretKeySpec(DatatypeConverter.parseHexBinary(secretHex),"HmacSHA1"));
          byte[] hash = mac.doFinal((time + command).getBytes(Charset.forName("UTF-8")));
          String url = apiURL + "?apid="+apid+"&time="+time+"&hash="+DatatypeConverter.printHexBinary(hash);

          HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
          con.setDoOutput(true);
          con.setRequestMethod("POST");
          con.setRequestProperty("Content-Type", "application/json");
          con.setRequestProperty("Content-Length", String.valueOf(command.length()));
          OutputStream os = con.getOutputStream();
          try {
               os.write(command.getBytes("UTF-8"));
               os.flush();
          } finally {
               os.close();
          }

          BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
          String line;
          StringBuilder buffer = new StringBuilder();
          try {
               while ((line = in.readLine()) != null) {
                    buffer.append(line);
               }
          } finally {
               in.close();
          }

          return buffer.toString();
     }
}