Indico API Wrapper For Java Returning Key Not Found - rest

I'm attempting to use indico's sentiment analysis api, I've debugged and inspected the "indico" object, and confirmed the correct api key is stored within it. I am also able to make calls to the API using curl from terminal, so I don't believe its my network settings (unless its something java specific?).
The code:
public double querySentiment(String qsent) throws UnsupportedOperationException, IOException, IndicoException{
double response = 0;
indico = new Indico(apikey);
IndicoResult single = indico.sentiment.predict(qsent);
log.inf("QUERY SEND SUCCESSFUL");
response = single.getSentiment();
log.inf("QUERY RECEIVE SUCCESSFUL");
return response;
}
The exception:
java.lang.IllegalArgumentException: API key not found. To use our API, sign up for a free account and api key at http://indico.io/register.

Wrong code snippet is given on indico API site. You have to pass key in params as well while making an indico object. Below code will work.
HashMap<String,String> params = new HashMap<String,String>();
params.add("api_key",apikey);
indico = new Indico(apikey,params);

Related

How to post grade on an assignment using canvas LMS API and UnityWeb Request or similar?

I am working on a gamification project whose goal is to build a WebGL game with Unity and post the final score as a grade on an assignment using the canvas LMS API. I need to know two things: how to authenticate using a bearer token for now (I know how to create the token already and I will need to use auth 2.0 later) and how to post a grade on an assignment using UnityWeb Request or similar. I have tried using restsharp, the vs code recognized it, but Unity did not. Also tried making a connection with node.js, Unity and node.js connected successfully, but the node wrappers I was using did not work.
In the worst cenario I would like to be able to post a comment on the assignment (I would pass the final grade as a string).
This is what I've tried with httpWebRequest:
string api_token = "bearer token here";
//initializing HttpWebRequest object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("domain here");
IWebProxy theProxy = request.Proxy;
if (theProxy != null)
{
theProxy.Credentials = CredentialCache.DefaultCredentials;
}
CookieContainer cookies = new CookieContainer();
request.UseDefaultCredentials = true;
request.CookieContainer = cookies;
request.ContentType = "application/json";
request.CookieContainer = cookies;
// write the "Authorization" header
request.Headers.Add("Authorization", "Basic " + api_token);
request.Method = "POST";
// get the response
//WebResponse response = request.GetResponse();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
Debug.Log(reader.ReadToEnd());
}
I need the node wrappers to do authentication and the post request.
The node wrappers: c10. I've tried with this one a lot and
node-canvas-api
I can access the api and post using postman.
I found out I can use code snippets on postman to retrieve the request in a certain language. With this, I didn't need the python APIs anymore as I was able to get the code directly. I still don't know why Unity did not recognize restSharp, but python solved my problem.
As it was hard for me to find how to post grades and comments on Canvas lms I will leave the PATH here for anyone who has the same problem:
PUT /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id
the query params are:
comment[text_comment] and submission[posted_grade].

Groovy Rest/HTTP Request Native for use with Script Runner

I am trying to build a simple Http Get request that requires me to submit an api key as authentication (api key as unsername and blank password). I have seen some solutions using the groovyx.net.http.HTTPBuilder library. However, the piece of code will need to be deployed in an evironment that does not allow for libraries. So I tried the following where is the url of the website i am trying to reach:
// GET
def get = new URL("<url>").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
println(get.getInputStream().getText());
}
As expected this returns error 400 since I do not include any authentication with the api key, so I tried the following where is the api key:
def get = new URL("<url>");
def authString = "<api_key>:".getBytes().encodeBase64().toString();
def conn = get.openConnection();
conn.setRequestProperty("Authorization", "Basic ${authString}");
def getRC = conn.getResponseCode();
println(getRC);
println(conn.getInputStream().getText());
But I still get the 400 error. I tried picking up the request through Fiddler but it doesn't seem to be tracking it (executing Groovy code through GroovyConsole).
The second approach works. My mistake was to not substitute spaces in the URL with % signs.

Websphere Commerce Custom REST service for Login using social sign in not generating valid WC Tokens and CTXMGMT table not getting updated

In the current website, social login is implemented using the mapping in struts and it will call the custom controller command "XYZThirdPartyLoginCmdImpl" which will authenticate the details passed and it will call the out of the box "LogonCmd" for login.
For creating a REST service for the above functinality, created a custom REST handler " XYZThirdPartyLoginHandler" and from there called the existing command "XYZThirdPartyLoginCmdImpl" using the method executeControllerCommandWithContext. Once the response is generated, WCToken and WCTrustedToken is generated by the below code.
ActivityToken token = getActivityToken();
String identitySignature = token.getSignature();
String identityId = token.getActivityGUID().getGUID().toString();
Map<String, Object> identityTokenInfo = new HashMap();
identityTokenInfo.put(MemberFacadeConstants.EC_USERID, new String[] { userId.toString() } );
identityTokenInfo.put(MemberFacadeConstants.ACTIVITY_TOKEN_ID, new String[] { identityId } );
identityTokenInfo.put(MemberFacadeConstants.ACTIVITY_TOKEN_SIGNATURE, new String[] { identitySignature } );
Map<String, String> commerceTokens = CommerceTokenHelper.generateCommerceTokens(identityTokenInfo);
String wcToken = commerceTokens.get(CommerceTokenHelper.WC_TOKEN);
String wcTrustedToken = commerceTokens.get(CommerceTokenHelper.WC_TRUSTED_TOKEN);
The tokens generated using this is not valid. If we try to invoke any other rest service using this token it shows invalid user session error. "XYZThirdPartyLoginCmdImpl" authentication is success as the userId returned is correct. After executing this the user context is not getting created in CTXMGMT table.
Please guide on how to generate the valid tokens in REST flow in this use case.
If you are on v9, you might want to investigate the oauth_validate REST call (/wcs/resources/store//loginidentity/oauth_validate). See the KC article for more information: [https://www.ibm.com/support/knowledgecenter/SSZLC2_9.0.0/com.ibm.commerce.integration.doc/tasks/tcv_sociallogin.htm][1]. This calls some different commands (OAuthTokenValidationCmdImpl and OpenUserRegisterCmd) than what you might be using, but it allows you to pass in a 3rd party token, and it generates the right tokens.

Auto-generating a WebRequest

I am trying to consume a binary stream from a ServiceStack service, as described here:
How to consume a file with a ServiceStack client
I realize that I must use a custom WebClient, since I want direct access to the response stream. However, I would still like to avoid making this client by hand. Instead, I'd like to write something like,
var webClient = new JsonServiceClient(baseUrl)
.ConfigureWebClient(new MyRequestDto { Foo = "bar" }));
This way, I wouldn't have to assemble the URL and query string by hand; and when I change my request DTO, I wouldn't have to remember to change my custom WebClient setup code, either.
Is there a way to accomplish this, somehow ? I've looked at ServiceClientBase.PrepareWebRequest(...), and it does a whole lot of useful stuff that I don't feel like copy/pasting into my own code. I'd love to inherit ServiceClientBase and call that method directly, but it's private, so I can't. Anyone got any other ideas ?
All of ServiceStack's C# Service Clients have both a Global and a Local Request Filter allowing you to initialise the Request and Global and Local Response Filters allowing fine-grained access to the returned HttpWebResponse.
Initializing the WebRequest of all ServiceClients using a Global Request Filter:
ServiceClientBase.HttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq);
Using the Local Request Filter:
var client = new JsonServiceClient(baseUrl) {
LocalHttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq)
};
Although if you just want the binary response All Service Clients allow you to specify either a string, byte[], Stream or HttpWebResponse as your Generic Response type and it will return what was requested. See the Service Client wiki page for more examples of these.
Here's how you can retrieve binary responses:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
var dto = responseBytes.FromUtf8Bytes().FromJson<PocoResponse>();
Or with a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or from the underlying HttpWebResponse:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var dto = sr.ReadToEnd().FromJson<PocoResponse>();
}
You can change Open Source Software, you don't have to work around it
ServiceStack is Open Source software, there's no need to look for hacks or try to work around something that's not accessible or not available, make a pull-request to change what you want and if it's a valid request for a common use-case it will likely be accepted. Otherwise feel free to take a fork of the Source code and customize it as you wish.

QBO Payment Query returns 'unauthorized'

When I perform a search by LastUpdatedTime I get "401 Unauthorized Error". Query by CustomerId works fine
Here is my code:
var pq = new PaymentQuery()
{
LastUpdatedTime = new DateTime(2012,12,21),
};
pq.SpecifyOperatorOption(Intuit.Ipp.Data.Qbo.FilterProperty.LastUpdatedTime, FilterOperatorType.AFTER);
var list = pq.ExecuteQuery<Payment>(commonService.ServiceContext);
Application throws Intuit.Ipp.Exception.InvalidTokenException in ExecuteQuery
The SDK does not encode the datetime correctly, so you will need to use DevDefined and deserialize the response with the SDK. Code sample: https://gist.github.com/IntuitDeveloperRelations/6024616
What does the full error look like?
Are you able to do other calls fine with this company using the token sets & realm ID that you have in place?