1

I want to use Personality Insights Service of IBM. I have downloaded Hello Wold sample code and trying to integrate Personality Insights Service in it.

My code is like below.

MainActivity.java

package com.ibm.bms.samples.android.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener;
import com.ibm.watson.developer_cloud.personality_insights.v2.PersonalityInsights;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile;

import org.json.JSONObject;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

public class MainActivity extends Activity implements ResponseListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView buttonText = (TextView) findViewById(R.id.button_text);

        try {
            //initialize SDK with IBM Bluemix application ID and route
            //TODO: Please replace <APPLICATION_ROUTE> with a valid ApplicationRoute and <APPLICATION_ID> with a valid ApplicationId
            BMSClient.getInstance().initialize(this, "http://bluemixpersonality.mybluemix.net", "b8c06c80-83fa-4448-b770-3ff5b3f1fb84");
        } catch (MalformedURLException mue) {
            this.setStatus("Unable to parse Application Route URL\n Please verify you have entered your Application Route and Id correctly and rebuild the app", false);
            buttonText.setClickable(false);
        }
    }

    public void pingBluemix(View view) {

        TextView buttonText = (TextView) findViewById(R.id.button_text);
        buttonText.setClickable(false);

        TextView errorText = (TextView) findViewById(R.id.error_text);
        errorText.setText("Pinging Bluemix");

        Log.i(TAG, "Pinging Bluemix");

        // Testing the connection to Bluemix by sending a Get request to the Node.js application, using this Activity to handle the response.
        // This Node.js code was provided in the MobileFirst Services Starter boilerplate.
        // The below request uses the IBM Mobile First Core sdk to send the request using the applicationRoute that was provided when initializing the BMSClient earlier.
        new Request(BMSClient.getInstance().getBluemixAppRoute(), Request.GET).send(this.getApplicationContext(), this);
    }

    private void setStatus(final String messageText, boolean wasSuccessful) {
        final TextView errorText = (TextView) findViewById(R.id.error_text);
        final TextView topText = (TextView) findViewById(R.id.top_text);
        final TextView bottomText = (TextView) findViewById(R.id.bottom_text);
        final TextView buttonText = (TextView) findViewById(R.id.button_text);
        final String topStatus = wasSuccessful ? "Yay!" : "Bummer";
        final String bottomStatus = wasSuccessful ? "You Are Connected" : "Something Went Wrong";

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                buttonText.setClickable(true);
                errorText.setText(messageText);
                topText.setText(topStatus);
                bottomText.setText(bottomStatus);
            }
        });
    }

    // Implemented for the response listener to handle the success response when Bluemix is pinged
    @Override
    public void onSuccess(Response response) {

        Log.e("Response: ", response.getResponseText());

        String myProfile = "Call me Ishmael. Some years ago-never mind how long precisely-having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off-then, I account it high time to get to sea as soon as I can.";

        PersonalityInsights service = new PersonalityInsights();
        service.setUsernameAndPassword("{username}","{password}");

        Profile personalityProfile = service.getProfile(myProfile);
        Log.e("hahah: ", "" + personalityProfile);

        setStatus("", true);
        Log.i(TAG, "Successfully pinged Bluemix!");
    }

    // Implemented for the response listener to handle failure response when Bluemix is pinged
    @Override
    public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
        // Blah Blah Code on Failing to connect to IBM.
    }
}

build.gradle

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.ibm.bms.samples.android.helloworld"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile group: 'com.ibm.mobilefirstplatform.clientsdk.android',
            name: 'core',
            version: '1.+',
            ext: 'aar',
            transitive: true
    compile 'com.ibm.watson.developer_cloud:java-wrapper:1.0.3'
}

I have referred below link.

How to call Watson Insights Service using java

I am getting bellow error.

Error Image

Note: I have set CORRECT username & password for Personality Insights Service.

ralphearle
  • 1,696
  • 13
  • 18
Maulik Dodia
  • 1,629
  • 2
  • 21
  • 48
  • Welcome to SO. Please edit question and reduce your code to an MCVE. See http://stackoverflow.com/help/mcve – kebs Jan 19 '16 at 10:46
  • Th exception says you have not provided the correct credentials! – stevops Jan 19 '16 at 10:47
  • But I have put correct credentials. It is the credential for Personality Insights Service, isn't it?@user2642282 – Maulik Dodia Jan 19 '16 at 10:59
  • I am assuming you set the creds on this line service.setUsernameAndPassword("{username}","{password}"); with your username and password you can obtain those from VCAP_SERVICES under envioroment variables in your bluemix application – Dudi Jan 19 '16 at 11:52
  • Actually I was following this [https://www.youtube.com/watch?v=B_m3mBadUrQ] to get the service credentials. At that time I was getting INVALID CREDENTIAL error. Then I have made new App in BlueMix and follow above YOUTUBE link and got this [http://i.imgur.com/L0iyGkc.png] error. I have changed service credentials as suggested by you. But I am getting same (ABOVE) error.@Dudi – Maulik Dodia Jan 19 '16 at 13:12
  • you might need to login to your bluemix account, go to the app and restart it. In addition, have you bounded your app with the service instance? – Dudi Jan 19 '16 at 13:24
  • I have stop that App in bluemix account. But It is not getting started and YES I have uploaded started app code via Command Prompt@Dudi – Maulik Dodia Jan 19 '16 at 14:23
  • check logs to see why its not starting... I suggest you also update the question so others can help you with your current situation – Dudi Jan 19 '16 at 15:02
  • I think you did not get my point. The application which is not starting is in BlueMix, not in Android Studio. So, How can I check log there? And Thanks for your suggestion I will update my question soon. Do you know any **LINKS** that give some IDEA to get started with BlueMix with Android Application?@Dudi – Maulik Dodia Jan 20 '16 at 05:00
  • fyi, there are logs, next to enviroment variables on the Bluemix console and there is also in cmd cf logs --recent – Dudi Jan 20 '16 at 10:19
  • Yes. I have seen now. Thanks for information. But log says `[39mRetrieve the security context from the cache.`. What does it mean?@Dudi – Maulik Dodia Jan 20 '16 at 10:36
  • I have searched on Google and found that you have to pass parameters like content type, Header etc. The link is [https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/personality-insights/output.shtml]. But they do not provide information that How to add these parameters. Do you have any idea about it?@Dudi, @German Attanasio – Maulik Dodia Jan 30 '16 at 11:39

1 Answers1

1

Look like you are using the java-wrapper:1.0.3. That's pretty old, and we fixed and improved the library a lot since that release. The 401 means that you didn't provide the right credentials or the service URL is not correct. You can set the service URL by calling service.setEndPoint()

See the example below:

Update the dependency in gradle to be:

'com.ibm.watson.developer_cloud:java-sdk:5.3.0'

Then use this code:

PersonalityInsights service = new PersonalityInsights();
service.setUsernameAndPassword("<username>", "<password>");
service.setEndPoint("https://gateway.watsonplatform.net/personality-insights/api")

String text = "your text goes here...."
ProfileOptions options = new ProfileOptions.Builder()
  .text(text)
  .build();

Profile profile = service.profile(options).execute();
System.out.println(profile);

Make sure you have credentials for the Personality Insights service(tiered plan). If you need help take a look at this guide.
Finally your service credentials are not your Bluemix credentials.

German Attanasio
  • 22,217
  • 7
  • 47
  • 63
  • pls read through the comments, the guy passed the credentials error. The question was not updated to reflect it – Dudi Jan 19 '16 at 19:53
  • In any case he needs to update the library. I wrote the library and I know he will get issues when using the Profile class. – German Attanasio Jan 19 '16 at 20:19
  • I have newly created app and service in Bluemix. But not uploaded it via command prompt. Yes as @GermanAttanasio told, I have updated LIBRARY and got INVALID CREDENTIAL error. Than I used credentials which are placed in **VCAP_SERVICES** tab under **ENVIRONMENT VARIABLE** in my Bluemix application as told by Dudi earlier. I got the **RESPONSE**. I got [http://i.imgur.com/mR29kU2.png] this response which is not identical to [http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/personality-insights/api/v2/?java#profile] thread under **Example response** heading. Is it CORRECT res? – Maulik Dodia Jan 20 '16 at 07:55
  • Thanks. But I am not getting `word_count` and `word_count_message` in that response.@GermanAttanasio – Maulik Dodia Jan 21 '16 at 05:02
  • did you check if they are not at the end of the printed json – German Attanasio Jan 21 '16 at 14:43
  • I have printed it in Log and I have checked very well. There is no word count in that JSON. Instead the whole JSON is also not getting printed unlike [http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/personality-insights/api/v2/?java#profile] here under Example Response heading.@GermanAttanasio – Maulik Dodia Jan 23 '16 at 08:49
  • I think the problem was the sdk version you were using Maulik. I just checked and I'm getting word count in the json response – German Attanasio Apr 22 '18 at 20:02