Can any body share me java code to make a one Rest api call to IBM BPM Cloud - rest

Can any body share a java client code which makes a Rest calls to IBM Cloud BPM. Basically I want to know how to authenticate IBM Cloud BPM.
I tried the following code but it is not working
String user_info_url="https://ustrial01.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/user/current?includeInternalMemberships=true&parts=all";
logger.info("user_info_url :" + user_info_url);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(user_info_url);
String authData = "rajesh.kohir123#gmail.com" + ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode(authData .getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
HttpResponse cgResponse = client.execute(get);
if(cgResponse.getStatusLine().getStatusCode() != 200) {
logger.info("IBM Rest call failed");
}
if(cgResponse.getStatusLine().getStatusCode() == 200) {
logger.info("IBM Rest call Succeded");
String content = EntityUtils.toString(cgResponse.getEntity());
logger.info(content);
}
Any help is greatly appreciated

I ran your code and just made the changes in URL. It worked. I hope this helps you.
Following is the URL I used to execute an exposed service :
https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings
I used the following code to add the parameters :
String parameters = "{'name':'pramod'}";
URIBuilder builder = new URIBuilder("https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings");
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action", "start"));
nameValuePairs.add(new BasicNameValuePair("params", parameters));
nameValuePairs.add(new BasicNameValuePair("createTask", "false"));
nameValuePairs.add(new BasicNameValuePair("parts", "all"));
builder.setParameters(nameValuePairs);
HttpGet get = new HttpGet(builder.build());

Download the download.zip form the post.
Look at the SampleBPDProcessTests.java - Line no 103
JSONObject results = bpmClient.runBPD(BPD_ID, PROCESS_APP_ID, bpdArgs);
The actual Java Code for Rest call is available as part of "bpm-rest-client.jar"
Try this concept.

Sample Java code to start a process:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://ustrial03.bpm.ibmcloud.com:443/bpm/dev/rest/bpm/wle/v1/process?
processAppId=3u092jr02j-djaodaj.u092302c166c1&bpdId=25.jklaklaa-539a-4150-
b63e-9ef94e96e521&action=start")
.put(null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive")
.addHeader("Authorization", "Basic YXJrYX24223232hQGRlbG9pdHRlLmNvbTpkZWZjb240QA==")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "f46c1525-7a75-954c-9265-bb2b21a57f16")
.build();
Response response = client.newCall(request).execute();
A full explanation of REST integration with BPM Cloud can be found in my answer at:
How to run IBM BPM Rest api call from Post man client

Related

How to make a GET Request using okhttp

I am new to Android Development and I would like to know how to perform a GET request using okhttp. I have referred http://square.github.io/okhttp/, but they only have examples of POST request. I have tried this -
okHttpClientLogin = new OkHttpClient();
requestBodyLogin = new FormBody.Builder()
.addEncoded("name", name_input) // params
.addEncoded("keys", keys_input) //params
.build();
requestLogin = new Request.Builder()
.addHeader("Authorization", token_type + " " +access_token)
.url(LOGIN_URL)
.get()
.build();
and got an Error :
{"status":{"status":206,"msg":"No record found"},"user":null}
I know why this error is coming, because the params have not been entered. I also tried passing requestBodyLogin inside .get() but it's not allowing.
Since OkHTTP 2.4, there's the function addQueryParameter. You can either use a HttpUrl, a String or a java.net.URL as url.
Basically, just create a new HttpUrl.Builder() and use the function addQueryParameter.
Example taken from the javadocs:
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
http://square.github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html
http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-

Unity: Use HTTP PUT in Unity3D

I'm quite new to Unity and facing some problems about RESTFul in Unity.
I want to update some data on the server by using HTTP PUT, but as what I received when search the web, the WWWW class in Unity doesn't support HTTP PUT. I also tried some HttpWebRequest example related to HTTP PUT but always received error code 400: Bad Request.
How can I solve this problem?
Do I have to list out all the key-value pairs when updating or just need to list the pairs I want to change the value ?
If you're not looking for a 3rd party plugin and assuming your server supports it then one method you could look at using is the "X-HTTP-Method-Override" HTTP header. Your client sends the data to the server via POST, but the server handles this as the value in the X-HTTP-Method-Override header (such as PUT).
I've used this before to great effect where our server supported it. An example of using this in Unity3d would be along the lines of:
string url = "http://yourserver.com/endpoint";
byte[] body = Encoding.UTF8.GetBytes(json);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add( "Content-Type", "application/json" );
headers.Add( "X-HTTP-Method-Override", "PUT" );
WWW www = new WWW(url, body, headers);
I recommend looking at BestHTTP package instead of default WWW class. It's cheap (almost all Unity3d assets are, compared to typical middleware prices in game industry) and it's pretty decent, judging by personal experience.
Alternatively, you can use standard .NET sockets.
I made it worked by the following codes using HttpWebRequest
void updatePlayer(){
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourAPIUrl");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{" +
"'ID': '100'," +
"'ClubName': 'DEF'," +
"'Number': 102," +
"'Name': 'AnNT'," +
"'Position': 'GK'," +
"'DateOfBirth': '2010-06-15T00:00:00'," +
"'PlaceOfBirth': 'Hanoi'," +
"'Weight': 55," +
"'Height': 1.55," +
"'Description': 'des'," +
"'ImageLink': 'annt.png'," +
"'Status': false," +
"'Age': '12'" +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
Debug.Log(responseText);
}
}

Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.
The old HttpClient code looks something like this:
PostMethod postMethod = null;
int responseCode = 0;
try{
HttpClient httpClient = new HttpClient();
postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
...
postMethod.addParameter(paramName, request);
responseCode = httpClient.executeMethod(postMethod);
...
}
And here are my HttpComponents replacements:
HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
HttpClient httpClient = new DefaultHttpClient();
postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
...
BasicHttpParams params = new BasicHttpParams();
params.setParameter(paramName, request);
postMethod.setParams(params);
httpResponse = httpClient.execute(postMethod);
responseCode = httpResponse.getStatusLine().getStatusCode();
...
}
The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:
ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
throw new IOException("Could not construct ServletRequestContext object");
It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?
Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.
To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.
To send a form entity, for example:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);

Cannot access google trends using HttpClient

I'm kind of newbie to this...Basicly I need to run a script to download .csv files from google trends. I wrote the following code according to this reference , the code is like:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("Email", "myEmail"));
nameValuePairs
.add(new BasicNameValuePair("Passwd", "myPasswd"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "xapi"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (line.startsWith("SID=")) {
String key = line.substring(4);
// Do something with the key
} catch (Exception e) {
}
I got the information about SID, LSID, Auth, but don't know how to use these information. I guess I should add these cookies in my following request, but don't know exactly how. I wrote another piece of code to connect to the certain URL, but I keep getting this message "You must be signed in to export data from Google Trends." The code is here if it helps:
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("Authorization", "SID"+key);
conn.addRequestProperty("Email", "myEmail");
conn.addRequestProperty("Passwd", "myPasswd");
conn.setReadTimeout(5000);
conn.connect();
I searched around and found few useful information, anyone could help?
Does it have to be in Java? In python, it's as simple as this:
from pyGTrends import pyGTrends
connector = pyGTrends('google username','google password')
connector.download_report(('keyword1', 'keyword2'))
print connector.csv()
You'll need the google trends api library.
If it has to be Java, you may want to look at the HttpClient examples from Apache. "Form based logon" and "client authentication" may both be relevant.
I have just coded this:
https://github.com/elibus/j-google-trends-api
It is an unofficial Java implementation of Google Trends API. You could use it to easily access Google Trends or you might want to have a look at the code to see it works.
Anyway the authentication flow works as follows (all the steps are required):
Fetch https://accounts.google.com/ServiceLoginAuth and parse the GALX id
Post username/password + GALX
Get http://www.google.com
Then you can access Google Trend with relaxed QoS policies for authenticated users.

How to call a GwtServiceImpl Servlet from external application?

I have developed a Gwt application and need now to call its remote service implementation
from another java application. Is there a method that given a List of Java Objects can transform them in a format suitable for invoking the get service servlet?something like:
myObject = .......
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/ppp//org.yournamehere.Main/gwtservice");
String serialized = <somelibrary.serialize>(myObject);
StringEntity input = new StringEntity(serialize);
input.setContentType("text/x-gwt-rpc; charset=UTF-8");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Although, I haven't tried it the following link seems to be what you are looking for
http://googlewebtoolkit.blogspot.com/2010/07/gwtrpccommlayer-extending-gwt-rpc-to-do.html