Getting 404 Not Found when doing a jira search for project - jira

I am trying to learn RESTFul web services using Jersey
I have written some java code to return the json for a JIRA search for a project ID, the code is based on that created by Bernd Hort (BP206 at connect2014)
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter("username", "password");
client.addFilter(authFilter);
WebResource service = client.resource(getBaseURI());
String searchquery = "search?jql=id=" + id + "&maxResults=5000";
System.out.println("Query=" + searchquery);
String json = service.path(searchquery).accept(
MediaType.APPLICATION_JSON).get(String.class);
I have tested the search using both Postman and putting it into the browser url and it returns data.
http://myserver:8080/rest/api/2/search?jql=id=12408&maxResults=5000
when I try it in my java code I get the following error;
com.sun.jersey.api.client.UniformInterfaceException: GET http://myserver:8080/rest/api/2/search%3Fjql=id=12408&maxResults=5000 returned a response status of 404 Not Found
it seems to be changing the '?' to '%3f' which the search doesn't like

You're specifying that query as part of the path, so it's being escaped as such:
String json = service.path(searchquery).accept(
MediaType.APPLICATION_JSON).get(String.class);
You want to make it a query parameter:
String json = service.path("search")
.queryParam("jql", "id=" + id)
.queryParam("maxResults", "5000)
.accept(MediaType.APPLICATION_JSON).get(String.class);

Related

Need suggestion on with MS Graph Rest API url

I kinda need to suggestion on picking the accurate MSGraph url between below 2 urls.
https://graph.microsoft.com/v1.0/users/{EmailAddress}.
https://graph.windows.net/{TenantID}/users?$filter=userPrincipalName%20eq%20'{EmailAddress}'&api-version=1.6
More details on my situation:
I need to resolve the UserName and ObjectID from MS Graph Rest api using EmailAddress. I have 100s of EmailAddress that I need to resolve UserName and ObjectID for. I was using below which is working fine for most of the time. But lastnight i realized it is not returning valid response for 2 users.
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://graph.microsoft.com/")
};
string URI = $"/v1.0/users/{EmailAddress}";
Then I realized, below rest API url is retuning accurate response for the missing users as comared to above url
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://graph.windows.net/")
};
string URI = $"/{TenantID}/users?$filter=userPrincipalName%20eq%20'{EmailAddress}'&api-version=1.6";

Is there a way to parse xml in docusign?

Is there a way to parse xml in docusign? And if so, how does this work? I do not find any user guide or something like this.
Thank you for your support
I would recommend that you use the REST API. the SOAP API is very old and not actively being worked on.
To retrieve values from a DocuSign "form" (we call it an envelope) you can use the following code example:
Here is a C# snippet, you get back at the end JSON with all the form data.
// Step 1: Obtain your OAuth token
var accessToken = RequestItemsService.User.AccessToken; // Represents your {ACCESS_TOKEN}
var accountId = RequestItemsService.Session.AccountId; // Represents your {ACCOUNT_ID}
var envelopeId = RequestItemsService.EnvelopeId;
// Step 2: Construct your API headers
var config = new Configuration(new ApiClient(basePath));
config.AddDefaultHeader("Authorization", "Bearer " + accessToken);
// Step 3: Call the eSignature REST API
EnvelopesApi envelopesApi = new EnvelopesApi(config);
EnvelopeFormData results = envelopesApi.GetFormData(accountId, envelopeId);

Is it possible to query a Neo4J db using Cypher, via the REST API, and return the URI of a node?

Background:
I am using a locally run Neo4J instance, (at localhost:7474), and accessing it through a Java adaptor which uses Cypher via the REST API (with Jersey), and makes data accessible to my Grails app running on the same server.
Question:
Is it possible to query a Neo4J db using Cypher, via the REST API, and return the URI of a node? Right now, I can check Neo4J server status, create nodes, populate node properties, query, and create relationships.
My problem is that my "add relationship" and traversal code requires a node URIs as input. I can query for nodes and obtain the correct JSON describing the results, but I cannot seem to get the URI locations.
Here is a simplified version of my getUserByEmail code:
public URI getUserByEmail( String email )
{
System.out.println( "GETTING USER BY EMAIL [" + email + "]..." );
String queryStr = "MATCH (user) WHERE user.nodetype=\'user\' and user.email=\'" + email + "\' RETURN user";
WebResource webResource = client.resource( ROOT_URI + "/transaction/commit" );
String payload = "{\"statements\" : [ {\"statement\" : \"" + queryStr + "\"} ]}";
ClientResponse response = webResource
.accept( MediaType.APPLICATION_JSON )
.type( MediaType.APPLICATION_JSON )
.entity( payload )
.post( ClientResponse.class );
String responseStr = response.getEntity( String.class );
URI responseLocation = response.getLocation();
System.out.println( "RESPONSE STRING: " + responseStr );
System.out.println( "GOT USER AT: [" + responseLocation + "]" );
return responseLocation;
}
The JSON results come back fine and reflect what is in the graph db. The location, however, is always null.
The "add relationship" code that I am using works, as long as I have the URI to the start node. The code I have is based on the addRelationship() code that lives here:
https://github.com/neo4j/neo4j/blob/2.1.6/community/server-examples/src/main/java/org/neo4j/examples/server/CreateSimpleGraph.java
In your JSON results, the self property value for each "user" will be its URI.
In this example, the response has 2 "n" nodes, and the self property value of each is its URI.
Here is an example of how to get the transactional endpoint (which is normally less verbose than the legacy endpoint) to also return the self property.
You can in your case create the node uri yourself by just appending the node internal id to the following url :
http://localhost:7474/db/data/node/your-123-id
maybe you want to set the scheme, host and database port in a configuration file to not do hardcode changes when changing the database location.

Asana API Key Basic authentication 401

i am getting a 401 response from Asana with my request.
var url = "https://app.asana.com/api/1.0/users/me";
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(APIKey);
APIKey = Convert.ToBase64String(encodedByte);
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(url);
wrGETURL.Headers.Add("Authorization: Basic " + APIKey);
string result;
using (StreamReader reader = new StreamReader(wrGETURL.GetResponse().GetResponseStream()))
{
result = reader.ReadToEnd();
}
return result;
The way HTTP basic auth works, you encode the username and password together as base64, separated by a colon. In the Asana API the key is the username and there is no password.
From the docs at https://asana.com/developers/documentation/getting-started/authentication#sts=API%20Keys :
Note: Most utilities and libraries that allow you to specify a username and password will handle proper encoding of the header for you. However, if you need to set the Authorization header manually, the header value is constructed by adding a colon (:) to the API key, then base64-encoding that string. You can read more on basic authentication if you need further details.
So, you should probably do:
byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(APIKey + ":")

QuickBooks Online querying with filter returns 401 everytime

I've had success creating objects with POST and Content-Type application/xml
I've also had success querying using Content-Type application/x-www-form-urlencoded with a blank request body which returns all of the object type depending on which URI I specify.
I can also get the same to work with something like PageNum=1&ResultsPerPage=1 in the request body and I have figured out how to incorporate that into the signature so I get a valid response.
However no matter how I format it, I cannot get anything other than a 401 response when I try to use a filter (something basic like Filter=FAMILYNAME :EQUALS: Doe). I've read over the OAuth Core 1.0 Revision A specifications on how all parameter names and values are escaped using the [RFC3986] percent-encoding. However I feel like I'm missing a step or formatting incorrectly. I've seen inconsistent information in my searching through Intuit's forums on what exactly is the proper format.
Any help on this would be greatly appreciated. I've been struggling with this for a good week now.
The response I get when trying to use a filter is:
HTTP Status 401 - message=Exception authenticating OAuth; errorCode=003200; statusCode=401
----Update----
I'm am seeing the same error when I try to use filters with the New IPP Developer Tools - IPP API Explorer. I'm using the IDS V2 QBO API Explorer. I'm able to use that tool to do a retrieve all Post and the response shows all of my customers, but when I try to use a filter I get :
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.
Any Ideas? If I'm getting the same error from the API Explorer tool, it makes me think the problem is something else entirely.
----Final Update----
I have finally had success with filters and I believe I have figure out what my problem was. I was always suspicious that I was able to get queries with pagination like "PageNum=1&ResultsPerPage=1" to work, but could not get something like "Filter=FAMILYNAME :EQUALS: Doe". I suspected there problem was with the white space in the filter format. What threw me off tracking this down earlier was that I could not get the filters to work in the IDS V2 QBO API Explorer. That made me suspect there was something else going on. I decided to ignore the API Explorer all together and focus on why I could get it to work the one way but no the other.
I believe my problem came down to improper encoding of the Filter's value in the signature. That explains the 401 invalid signature errors I was getting.
"Filter=Name :EQUALS: Doe" becomes "Filter=Name%20%3AEQUALS%20%3ADoe" after normalization.
Percent-Encoding that should give "Filter%3DName%2520%253AEQUALS%2520%253ADoe".
In essence you have to "double" encode the blank space and the colons, but not the equal sign. I tried many permutations of doing the encoding, but believe my mistake was that I was either not "double" encoding, or when I was double encoding I was including the '=' sign. Either way breaks your signature. Thanks for everyone's input.
I believe my problem came down to improper encoding of the Filter's value in the signature. That explains the 401 invalid signature errors I was getting.
I used an online tool to take me through the steps in properly signing an Oauth request. While going through those steps I realized my problem was with the steps where you normalize the request parameters and then percent-encode them. I was including the '=' of the filter in the normalization step, which breaks your signature. The tool I used can be found at:
http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/
Thanks for everyone's input.
Do you get a 401 with the same request in the API Explorer?
http://ippblog.intuit.com/blog/2013/01/new-ipp-developer-tool-api-explorer.html
Also, are you using the static base URL or retrieving it at runtime?
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0400_QuickBooks_Online/0100_Calling_Data_Services/0010_Getting_the_Base_URL
If you are using the static base URL, try switching to the runtime base URL to see if you still get the error.
peterl answered one of my questions on here that may also answer yours. I had been trying to put the Filters in the body when they should have gone into the header. Here was peterl's code sample for getting all unpaid invoices (open balance greater than 0.00) for a particular customer.
http://pastebin.com/raw.php?i=7VUB6whp
public List<Intuit.Ipp.Data.Qbo.Invoice> GetQboUnpaidInvoices(DataServices dataServices, int startPage, int resultsPerPage, IdType CustomerId)
{
StringBuilder requestXML = new StringBuilder();
StringBuilder responseXML = new StringBuilder();
var requestBody = String.Format("PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}", startPage, resultsPerPage, CustomerId.Value);
HttpWebRequest httpWebRequest = WebRequest.Create(dataServices.ServiceContext.BaseUrl + "invoices/v2/" + dataServices.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, requestBody));
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
Intuit.Ipp.Data.Qbo.SearchResults searchResults = (Intuit.Ipp.Data.Qbo.SearchResults)dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(new StreamReader(data).ReadToEnd());
return ((Intuit.Ipp.Data.Qbo.Invoices)searchResults.CdmCollections).Invoice.ToList();
}
}
protected string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string requestBody)
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
consumerContext.UseHeaderForOAuthParameters = true;
//URIs not used - we already have Oauth tokens
OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
"https://www.example.com",
"https://www.example.com");
oSession.AccessToken = new TokenBase
{
Token = accessToken,
ConsumerKey = consumerKey,
TokenSecret = accessTokenSecret
};
IConsumerRequest consumerRequest = oSession.Request();
consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
if (webRequest.Headers.Count > 0)
{
ConsumerRequestExtensions.AlterContext(consumerRequest, context => context.Headers = webRequest.Headers);
if (webRequest.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded")
{
Dictionary<string, string> formParameters = new Dictionary<string, string>();
foreach (string formParameter in requestBody.Split('&'))
{
formParameters.Add(formParameter.Split('=')[0], formParameter.Split('=')[1]);
}
consumerRequest = consumerRequest.WithFormParameters(formParameters);
}
}
consumerRequest = consumerRequest.SignWithToken();
return consumerRequest.Context.GenerateOAuthParametersForHeader();
}
You can also see my original Question Here on StackOverflow: Query for All Invoices With Open Balances using QuickBooks Online (QBO) Intuit Partner Platform (IPP) DevKit.

Resources