Using PagerDuty with Codenvy

Use Codenvy Factory to instantly start working with the sample below PagerDuty API projects:


This tutorial will explain the details of integrating the PagerDuty API into Codenvy. PagerDuty is an alert and incident management and tracking tool and the PagerDuty API allows you to create events that generate alerts and incidents and gives you the ability to manage the alerts and incidents from your application. This example has been done with 2 very basic Java servlet projects that make use of the PagerDuty API to explain some basic features provided by the API.

Register With PagerDuty

Before proceeding with the Java project, please register at https://signup.pagerduty.com/accounts/new with your email id to generate the domain url of your PagerDuty account:

pagerduty-register

After registering, you can then login to your account dashboard using your domain url https://.pagerduty.com/. You can generate and view your API key at https://.pagerduty.com/api_keys:

pagerduty-apikey

You can get more information about the PagerDuty API at
http://developer.pagerduty.com/. There are different subsections providing information about various types of methods available within the API such as creating events and generating incidents from the events and triggering alerts. 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.

To generate an event using the API, you will need to create a service at https://.pagerduty.com/services/new:

pagerduty-service

After creating the service, it will be assigned a service key which can be seen at https://.pagerduty.com/services and will be used in the event creation via the API:

pagerduty-servicekey

The first factory workspace source code is to explain the process of creating an event using the PagerDuty API through your service.

Create the first Project

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

Create pom.xml File

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


      javax.servlet
      servlet-api
      2.5

      org.apache.httpcomponents
      httpclient
      4.2.5

      javax
      javaee-web-api
      6.0

      com.googlecode.json-simple
      json-simple
      1.1.1

        false

      central
      Maven Repository Switchboard

http://repo1.maven.org/maven2

  

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

Create Java Class

Now create a Java servlet class named PagerDutyServlet.java that will talk to the PagerDuty API with the Http request URL(obtained from the API documentation) to create an event using the service key that will trigger an incident 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 contains the incident number. All this is done inside the method doPost() which is invoked by the method 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://events.pagerduty.com/generic/2010-04-15/create_event.json";
            HttpPost req = new HttpPost(postURL);
            req.setHeader("Content-Type", "application/json");

            JSONObject triggerObject = new JSONObject();
            triggerObject.put("service_key",  "aedwdhkwejdhwekjh8294378348988");
            triggerObject.put("event_type",  "trigger");
            triggerObject.put("description",  "Test Event");

            StringEntity reqEntity = new StringEntity(triggerObject.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("
Simple POST request to url : "+ postURL +"

");
            sb.append("*** Request headers ***").append("
");
            Header[] requestHeaders = req.getAllHeaders();
            for (Header header : requestHeaders) {
                sb.append(header.toString()).append("
");
            }
            sb.append("***********************").append("

");

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

");

            sb.append("*** Response Body ***").append("
");
            sb.append(responseString).append("
");

        } 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 PagerDutyServlet class to display the response on the browser -

</pre>
<div>Data :
<%=request.getAttribute("data") %></div>
<pre>

Create web.xml File

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


  Pager Duty Servlet App

    hello
    com.codenvy.PagerDutyServlet

    hello
    /hello

Build and Run Your first Project

Now you build and run your Codenvy project and the Http response will be displayed in the browser: pagerduty-outputt At the same time, an alert email is sent to your email address informing about the triggered incident. The second factory workspace source code is to explain the process of retrieving the details of all incidents using the PagerDuty API.

Create the second Project

Login to your Codenvy workspace and create a WAR project named as ‘PagerDutySample1’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java Class

Now create a Java servlet class named PagerDutyServlet.java that will talk to the PagerDutyAPI with the Http request URL(obtained from the API documentation) to request details of all the incidents in your account 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. All this is done inside the doGet() method in the sample source Java class:

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

        StringBuffer sb = null;
        try {
            String getURL = "https://dasn82.pagerduty.com/api/v1/incidents";
            HttpGet req = new HttpGet(getURL);
            req.addHeader("Content-type", "application/json");
            req.addHeader("Authorization", "Token token=AVN9xTJW7d4SYBkxWEQX");
            HttpResponse res = client.execute(req);
            HttpEntity entity = res.getEntity();
            String responseString = new BasicResponseHandler().handleResponse(res);
            if (entity != null) {
                EntityUtils.consume(entity);
            }

            sb = new StringBuffer("
Simple GET request to url : "+ getURL +"

");
            sb.append("*** Request headers ***").append("
");

            Header[] requestHeaders = req.getAllHeaders();
            for (Header header : requestHeaders) {
                sb.append(header.toString()).append("
");
            }

            sb.append("***********************").append("

");
            sb.append("*** Response headers ***").append("
");
            sb.append(res.getStatusLine()).append("
");

            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                sb.append(header.toString()).append("
");
            }
            sb.append("***********************").append("

");
            sb.append("*** Response Body ***").append("
");
            sb.append(responseString).append("
");
        } catch (Exception ex) {
            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 PagerDutyServlet class to display the response on the browser -

</pre>
<div>Data :
<%=request.getAttribute("data") %></div>
<pre>

The web.xml will be same as the first project.

Build and Run Your second Project

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

pagerduty-output1

In a similar way, you can use other available API methods and integrate the PagerDuty API into your application to meet your application needs with regards to incident tracking and management.