Using SurveyMonkey with Codenvy

Use Codenvy Factory to instantly start working with a sample SurveyMonkey API project:


This tutorial will explain the details of integrating the SurveyMonkey API into Codenvy. SurveyMonkey API provides the ability to your application to gather details about your online SurveyMonkey surveys and their responses and respondents to enable your application to analyse the feedback of your online surveys. The explanation has been done with a very basic Java servlet project that makes use of the SurveyMonkey API to explain some basic features provided by the API.

Register With SurveyMonkey

Before proceeding to the creation of the Java project, please register at https://developer.surveymonkey.com/member/register with your email id:

surveymonkey-register

After registering, you will be able to see the API keys under your account:

surveymonkey-apikeys

You can get more information about the SurveyMonkey API at
https://developer.surveymonkey.com/. There are different subsections under the ‘API Methods’ section providing information about various methods available in the API to retrieve different types of information. Each subsection will detail the request URL required to invoke the specific API method that you can use in your integration process and the list of input parameters and the response fields. As can be seen from the documentation, SurveyMonkey uses OAuth mechanism to derive the access token for authentication to use the API. The access token is derived using the API keys and so you will need to derive an access token within your application to start using the API.
For development purposes, SurveyMonkey have provided an API Console at https://developer.surveymonkey.com/api_console which will generate an access token by authorising you as a SurveyMonkey account holder and then give you the request URLs and parameters that you can use in your application for the relevant API method:

surveymonkey-apiconsole

After generating the access token, you can then try any one of the methods that you want to use and enter the required parameters and derive the request URL that you can use in your application:

surveymonkey-apiconsolemethod

So you will need to create a SurveyMonkey account at https://www.surveymonkey.com/user/sign-up/?ut_source=account_login. This is also required for you to create your online surveys from scratch or from templates and send them out for responses which you can then analyse using the API methods. Below is an example of a template survey:

surveymonkey-account

Create a Project

Now, login to your Codenvy workspace and create a WAR project named as ‘SurveyMonkeySample’. This will have the following structure:
surveymonkey-structure

Create pom.xml File

To make use of the SurveyMonkey API through HttpClient as a servlet, please update the pom.xml to include the HttpClient and Java EE Web API jars and the servletapi jar and the google json jar into your project as Maven dependencies:

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.2.5</version>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-web-api</artifactId>
      <version>6.0</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
    </dependency>
  </dependencies>
  <repositories>
     <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Maven Repository Switchboard</name>
      <url>http://repo1.maven.org/maven2</url>
     </repository>
  </repositories>

This will include these jars in your project as follows:
surveymonkey-dependencies

Create Java Class

Now create a Java servlet class named SurveyMonkeyServlet.java that will talk to the SurveyMonkey API with the Http request URL and input parameters(obtained from the API console or documentation) to request the details of a survey using the survey Id and then get a Http response back with the response header and the response body which will be then displayed on the browser through a JSP. The response body will contain the different information about the survey. All this is done inside the method doPost() which is called by the doGet() in the sample source Java class.

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

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

        StringBuffer sb = null;
        try {
            String postURL = "https://api.surveymonkey.net/v2/surveys/get_survey_details?api_key=u366xz3zv6s9jje5mm3495fk";

            HttpPost req = new HttpPost(postURL);
            req.setHeader("Authorization", "bearer werfewhjehrjehrkjher878394783748493495898
dsfhsdjfjksdfkskjfkjksldjfsldflksdflslfk989089890890890808=");
            req.setHeader("Content-Type", "application/json");

            JSONObject surveyReq = new JSONObject();
            surveyReq.put("survey_id",  "48201465");

            StringEntity reqEntity = new StringEntity(surveyReq.toJSONString());

            req.setEntity(reqEntity);

            HttpResponse res = client.execute(req);
            HttpEntity entity = res.getEntity();
            String responseString = new BasicResponseHandler().handleResponse(res);
            if (entity != null) {
                EntityUtils.consume(entity);
            }

            sb = new StringBuffer("<br/>Simple POST request to url : "+ postURL +"<br/><br/>");
            sb.append("*** Request headers ***").append("<br/>");
            Header[] requestHeaders = req.getAllHeaders();
            for (Header header : requestHeaders) {
                sb.append(header.toString()).append("<br/>");
            }
            sb.append("***********************").append("<br/><br/>");

            sb.append("*** Response headers ***").append("<br/>");
            sb.append(res.getStatusLine()).append("<br/>");
            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                sb.append(header.toString()).append("<br/>");
            }
            sb.append("***********************").append("<br/><br/>");

            sb.append("*** Response Body ***").append("<br/>");
            sb.append(responseString).append("<br/>");

        } catch (Exception ex) {
            ex.printStackTrace();
            sb = new StringBuffer(ex.toString());
        }

        request.setAttribute("data", sb.toString());
        RequestDispatcher rd = request.getRequestDispatcher("/success.jsp");
        rd.forward(request, response);
   }

Create index.jsp File

Your Codenvy project will have an index.jsp which will invoke the Servlet class -

<%
   response.sendRedirect("/hello");
%>

Create success.jsp File

Your Codenvy project will have a success.jsp which will be invoked from the SurveyMonkeyServlet class to display the response on the browser -

<html>
  <body>
    <div>
      <p>Data : <br/><%=request.getAttribute("data") %></p>
      <br/>
    </div>
</body>
</html>

Create web.xml File

The servlet mapping ‘/hello’ is defined in the web.xml as follows –

<web-app>
  <display-name>Survey Monkey Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.SurveyMonkeyServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

Now you build and run your Codenvy project and the Http response will be displayed in the browser:

surveymonkey-output

In a similar way, you can use other available API methods and integrate the SurveyMonkey API into your application to meet your application needs.