Using CamFind with Codenvy

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


This tutorial will explain the details of integrating the CamFind API into Codenvy. CamFind API is the image recognition and reverse image search that powers the popular mobile visual search engine app, CamFind. The explanation has been done with a very basic Java servlet project that makes use of the CamFind API to explain the basic features provided by the API.

Register With Mashape

Before proceeding to the creation of the Java project, please register at https://www.mashape.com/ with your email id and this will generate keys which will be used for the integration:
mashape-signup

On registering the application, you can see your keys at the ‘Keystore’ section:
mashape-keys

To assist the integration with the different methods of CamFind API, the CamFind API has a documentation section at https://www.mashape.com/imagesearcher/camfind#!documentation which will give you information of the methods and their input parameters that are needed to get the desired output out of them and the return values. There are ‘Test Endpoint’ buttons available for each method which allows you to enter the parameters and check the output but you will need to do a free/paid subscription to the API to use these buttons as well to use the API from your application –

camfind-documentation1

camfind-documentation2

Create a Project

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

Create pom.xml File

To make use of the CamFind 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>
    <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>

Create Java Class

Now create a Java servlet class named CamFindServlet.java that will talk to the CamFind website with the Http request URL and then get a Http response back with the response header and the response body in the JSON format which will be then displayed on the browser through a JSP. 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 getURL = "https://camfind.p.mashape.com/image_responses/9JKAWHKGLjqMdDKDNIJQfg";

            HttpGet req = new HttpGet(getURL);
            req.addHeader("X-Mashape-Authorization", "kZAKbJr3u3IZ6y63AerS8SZRqr0aGB03");
            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);
   }

This method shows how to retrieve the details of a sample image token. In realtime, this image token will be returned by the method that allows you to upload the image whose details need to be retrieved. The API key currently being used in the sample class was a temporary key that only allowed access to the method for the retrieval of the image details and not to the method for the upload of the images.

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 CamFindServlet 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>CamFind Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.CamFindServlet</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 from the CamFind website with the information about the image token supplied as a parameter in the request URL will be displayed in the browser:

camfind-output

You can use this JSON format response in a way that you would like to meet the needs for your custom application.