Getting 500 error while creating vertex using Rest API - rest

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you

Related

How to call Microsoft Graph REST API with groovy-wslite

I am trying to call Microsoft Graph API on groovy script using Java libraries. However, even though partly success, I still have some serious issues using it within my current project, so I think about trying to call the the REST API using groovy-wslite.
This is my current code for getting access token:
def authorizeHost = "https://login.microsoftonline.com"
def authorizePath = "/${azureSetting.getTenantID()}/oauth2/v2.0/authorize?"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.JSON
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}
The response from the log:
AADSTS900144: The request body must contain the following parameter: 'client_id'.
How can I change the above code, so that Microsoft Graph REST API can recognize my sending content and send back the access token.
UPDATE: After trying around, I found out that the body os post method should be as below:
type "application/x-www-form-urlencoded"
urlenc client_id: azureSetting.getClientID(),
scope: "https://graph.microsoft.com/.default",
response_type: "code"
according to doc https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request your request should have Content-Type: application/x-www-form-urlencoded
you are trying to send json instead
here is your code but pointing to a test httpbin.org server and it could show what exactly you are sending to server
there is a minor change: ContentType.JSON -> ContentType.URLENC
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3', transitive=false)
import wslite.rest.*
//just for test
def azureSetting = [ getClientID:{-> "12345"} ]
def LOGGER = [info:{x-> println x}]
//redefined host and url
def authorizeHost = "HTTP://httpbin.org"
def authorizePath = "/post"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.URLENC // <-- THE ONLY CHANGE IN YOUR CODE
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}

Groovy rest client without libraries

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL
400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r
The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

Getting 403 forbidden error while accessing linkedIn 2.0 API from SharePoint 2013 web part

API: https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)
App Permission: r_basicprofile, r_emailaddress, w_share
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string requesturl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)";
HttpWebRequest webRequest = System.Net.WebRequest.Create(requesturl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Host = "api.linkedin.com";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Connection = "Keep-Alive";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//Stream dataStream = webRequest.GetRequestStream();
//String postData = String.Empty;
//byte[] postArray = Encoding.ASCII.GetBytes(postData);
//dataStream.Write(postArray, 0, postArray.Length);
//dataStream.Close();
WebResponse response = webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
If you are using V2 API and you did not taken permission to use r_basicprofile then either apply for permission to use r_basicprofile to linkedin
OR use r_liteprofile + r_emailaddress for V2
(also check r_liteprofile permission is there in your app or not )
r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

Service to Service Calls Using Client Credentials

I tried to create an alias for group in office 365 using below code but it shows some error.how to solve this. I tried to use service to service calls method. I got the token generated. How to check its valid or not? Is it possible to create alias using api for group without powershell option? if no kindly advice me to for other options..
string clientId = "************";
string clientsecret = "******";
string tenantId = "********";
//string resourceUri = "http://office.microsoft.com/outlook/";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
var authUri = "https://login.windows.net/" + tenantId + "/oauth2/authorize/";
var RESOURCE_URL = "https://graph.windows.net";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'displayName': 'mailgrouptest',
'groupTypes': ['Unified'],
'mailEnabled': true,
'mailNickname': 'mailalias1',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
When i run this code in console it shows an error like this....is the problem with token ? or tenant id?
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {``
"request-id": "*****-***-",
"date": "2016-05-25T04:53:08"
}
}
}
kindly advice me to create alias for group in api
The mailNickName of group is not able to update using the Microsoft Graph at present.
As a workaround, we can create a new group with the specific the mailNickName you wanted and use the new group. Here is the code to create a group with mailNicekName for your reference:
string clientId = "";
string clientsecret = "";
string tenant = "yourdomain.onmicrosoft.com";
var authUri = "https://login.microsoftonline.com/"+tenant+"/oauth2/token";
var RESOURCE_URL = "https://graph.microsoft.com";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'description': 'description-value',
'displayName': 'displayName-value',
'groupTypes': [
'Unified'
],
'mailEnabled': true,
'mailNickname': 'mailNickname-value',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
//var response = client.GetAsync("https://graph.microsoft.com/v1.0/groups").Result;
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups",httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
More detail about Goupr REST API, please refer to here.
For the error “InvalidAuthenticationToken” you were request the access token with incorrect resource. To use the Microsoft Graph API, we need to specify the resource with “https://graph.microsoft.com” instead of “https://graph.windows.net”.
In addition, if you want the mailNickName of group is updateable, you can try to submit the feedback from here.

How to use HttpWebRequest GET method in Twitter API [duplicate]

I am trying to execute a simple "request body search" on Elasticsearch like the following example but using .NET instead of curl
$ curl -XGET 'http://localhost:9200/twitter/tweet/_search' -d '{
"query" : {
"term" : { "user" : "kimchy" }
}
}
'
Below is my .NET code.
var uri = "http://localhost:9200/myindex/_search";
var json = "{ \"query\" : { \"term\" : { \"user\" : \"kimchy\" } } }";
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.ContentType = "text/json";
request.Method = "GET";
var responseString = string.Empty;
using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var response = (System.Net.HttpWebResponse)request.GetResponse();
using (var streamReader = new System.IO.StreamReader(response.GetResponseStream()))
{
responseString = streamReader.ReadToEnd();
}
}
However, I am getting the following error.
Cannot send a content-body with this verb-type.
...
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
...
Line 54: using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
Is there any way I can send a content-body with a GET request using standard .NET classes. Or is there a workaround?
Changing the Method to POST is a workaround.
request.Method = "POST";
MSDN states that a ProtocolViolationException will be thrown if the GetResponseStream() method is called with a GET or HEAD method.