Using Alchemy with Codenvy

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


This tutorial will explain the details of integrating the Alchemy API into Codenvy. Alchemy API utilizes statistical natural language processing technology and machine learning algorithms to analyze your content, extracting semantic meta-data: information about people, places, companies, topics, languages, and more and this analytic information can then be used in your application. The explanation has been done with a very basic Java servlet project that makes use of the Alchemy API to explain some basic features provided by the API.

Register With Alchemy

Before proceeding to the creation of the Java project, please register at http://www.alchemyapi.com/api/register.html with your email id to generate the API key which will be used for the integration:

alchemy_signup

On registering, you will receive an email that will contain the api key.

You can get more information about the Alchemy API at
http://www.alchemyapi.com/api/. There are different subsections providing information about various types of text analysis methodologies. 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.

You can also try a demo at http://www.alchemyapi.com/products/demo/. This demo will allow you to input sample URLs or text and then view the output in various formats.

alchemy_demo

Create a Project

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

Create pom.xml File

To make use of the Alchemy 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 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>
  </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:
alchemy_dependencies

Create Java Class

Now create a Java servlet class named AlchemyServlet.java that will talk to the Alchemy API with the Http request URL(obtained from the API documentation) to request a URL analysis of the supplied URL in an encoded form 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 analysed URL. All this is done inside the method doGet() in the sample source Java class.

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        StringBuffer sb = null;
        try {
            String analyseURL = "http://blog.programmableweb.com/2011/09/16/new-api-billionaire-text-extractor-alchemy/";
            String encodedAnalyseURL = URLEncoder.encode(analyseURL,"UTF-8");
            String getURL = "http://access.alchemyapi.com/calls/url/URLGetRankedNamedEntities?apikey=dgdgdghghghdgwehdgehwg2432434433443&&outputMode=json&url=" + encodedAnalyseURL;
            HttpGet req = new HttpGet(getURL);
            req.addHeader("X-Originating-Ip", "80.254.147.148");
            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 GET request to url : "+ getURL +"<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) {
            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 AlchemyServlet 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>Alchemy Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.AlchemyServlet</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:

alchemy_output

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