Contents


Overview

Skill Level: Any Skill Level

Beginner

Create your AccountsFirst, you have to sign up for a Bluemix Account (https://console.ng.bluemix.net/)Then, create your account at DevOps Services (https://hub.jazz.net/) using the same e-mail Create your Java Application Using a BoilerplateNow, log in to Bluemix and click on “Catalog"Choose the boilerplate “Java DB Starter"Provide a unique application nameClick on “Create" and wait for the staging […]

Ingredients

Eclipse IDE

Java

Bluemix Account

DevOps Services Account

 

Step-by-step

  1. Create your Accounts

    UPDATE October 2016 – This tutorial is outdated. So I've wrote another one here, which is better and more accurate.

    https://developer.ibm.com/recipes/tutorials/bluemix-watson-apis-quickstart-using-java-sdk-version-2016/

    🙂

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    First, you have to sign up for a Bluemix Account (https://console.ng.bluemix.net/)

    Then, create your account at DevOps Services (https://hub.jazz.net/) using the same e-mail

     

  2. Create your Java Application Using a Boilerplate

    Now, log in to Bluemix and click on “Catalog”

    Choose the boilerplate “Java DB Starter”

    Provide a unique application name

    Click on “Create” and wait for the staging process

    After one minute or two, you'll see this message.

    Now, go back to your Bluemix dashboard

    Your Bluemix application has been created. Congratulations!

    Click on the Bluemix Application and click on “Add GIT” (top right corner)

    Ensure the checkbox is ON and click on “Continue”

     

    After 1 minute, you'll see this message

    Click on “Close” and copy your GIT link

     

  3. Open your project in Eclipse

    Now, it's time to open your Eclipse IDE.

    Click on “Workbench” and then “Window”->”Open Perspective”->”Other”

    Select “GIT” and click on “OK”

    Click on “Clone a GIT Repository” and provide the URI generated in the previous step of this tutorial.

    Don't forget to check “Import all existing Eclipse projects after clone finishes”.

    You'll get a window like this

     

     

  4. Add Watson Java SDK dependencies

    In Eclipse IDE, switch the perspective from GIT to Java EE

    You'll see your project like this

    Locate in your project the file “pom.xml” and double click it.

    Locate the tab “Dependencies” and click on it.

    Add the Watson Java SDK dependency

    Do the same for Apache Commons IO

    Click on the “Save Button” (top left corner)

    If this is the first time you're using Maven, it will take some minutes while Maven downloads all the dependencies in the local repository. Otherwise, it will just take some seconds.

     

  5. Running Watson Locally

    In your Bluemix Application, locate the application “environment variables” (left)

    Copy the contents of the VCAP_SERVICES credentials (in JSON format) and save in a local file (let's say /home/leoks/vcap.txt for example). We're going to use this file later.

    Now, back to Eclipse IDE.

    The boilerplate generates some Java classes by default. Let's modify the existent /JavaDBApp/src/main/java/example/servlet/SimpleServlet.java class a little bit.

    Change the existent class so it will look like this (use Eclipse CTRL+SHIFT+O to resolve the imports)

    package example.servlet;

    import java.io.File;
    import java.io.IOException;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.io.FileUtils;

    import com.ibm.watson.developer_cloud.speech_to_text.v1.SpeechToText;
    import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
    import com.ibm.watson.developer_cloud.util.CredentialUtils;

    @WebServlet("/SimpleServlet")
    public class SimpleServlet extends HttpServlet {

    private SpeechToText s2t = new SpeechToText();

    @Override
    public void init() throws ServletException {
    super.init();
    String vcap = System.getProperty("VCAP_SERVICES");
    if (vcap == null){
    try {
    vcap = FileUtils.readFileToString(new File("/home/leoks/vcap.txt"));
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    CredentialUtils.setServices(vcap);
    s2t.setApiKey(CredentialUtils.getAPIKey("speech_to_text"));
    }

    public static void main(String[] args) throws ServletException{
    SimpleServlet ss = new SimpleServlet();
    ss.init();
    SpeechResults results = ss.s2t.recognize(new File("/home/leoks/sample.flac"));
    System.out.println(results.getResults().get(0).toString());
    }

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    response.getWriter().print("Hello World!");
    }

    }

    You can get this audio sample from https://ibm.box.com/shared/static/p8d80dqg0mi0un69d3bpywszspm38svz.flac

    For more information about Speech To Text and supported audio formats, please check this link: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/speech-to-text/

    The expected result is

     {
    "final": true,
    "alternatives": [
    {
    "transcript": "learning to use Watson ",
    "confidence": 0.998
    }
    ]}

    Now, let's change the Servlet and deploy your application, so we can test Speech to Text online

  6. Add the Watson service to your application

    Click on “Add a Service or API”

    Choose a Watson API, for example, Speech to Text

    Click on the service

    Then click on “create” and allow Bluemix to re-stage the application.

    You can add up to 4 different services using the Bluemix Trial. If you need more, please contact Bluemix Support (https://support.ibmcloud.com/ics/support/mylogin.asp?login=bluemix)

     

     

  7. Putting All Together: running Watson from a Bluemix Application

    Change your servlet's GET method to this

     @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String audioUrl = request.getParameter("audioUrl");
    try{
    URL url = new URL(audioUrl);
    File tmp = File.createTempFile("myTmp", ".flac");
    tmp.deleteOnExit();

    IOUtils.copy(url.openStream(), new FileOutputStream(tmp));

    SpeechResults results = s2t.recognize(tmp);

    response.setContentType("application/json");
    response.getWriter().write(results.getResults().get(0).toString());

    }catch(Exception e){
    response.setContentType("text/html");
    e.printStackTrace(response.getWriter());
    }
    }

    Right click on your Eclipse project, choose “Team->Commit”

    Add a commit message (e.g. “First commit”) and click on “Commit and Push”, then “OK”.

    This will send the code to GIT at JazzHub, which in turn will trigger a new deployment process. You can monitor the process accessing DevOps Service URL (for this project, the link is https://hub.jazz.net/pipeline/leoks/myOwnUniqueAppName). You can reach your project's pipeline from the Dashboard clicking on “Edit Code” (top right) and then “Build and Deploy” (top right).

    So let's try our application

    http://myownuniqueappname.mybluemix.net/SimpleServlet?audioUrl=https%3A%2F%2Fibm.box.com%2Fshared%2Fstatic%2Fp8d80dqg0mi0un69d3bpywszspm38svz.flac

    (use an encoder service such as http://meyerweb.com/eric/tools/dencoder/ to generate the encoded URL, so you can add as a parameter for the http request)

    And that's it!

    :

     

9 Comments on "Bluemix Watson APIs Quickstart using Java SDK"

  1. “Java DB Starter” is NOT anymore in the Catalog Boilerplates.
    The closer one I could find was “Java Cloudant Web Starter” but that did not come with a pom.xml.
    Now even if I create a pom.xml on the eclipse project it does not get the api described here: “Watson Java SDK dependency” and “Apache Commons IO”

  2. SameenaTaskin September 28, 2016

    I am having the same issue. As “java DB web” not available so I chose “Java Cloudant ” as well as “Java Workload”, but the pom.xml is file is missing. How do we proceed. Please help

Join The Discussion