How to create REPOSITORY in BitBucket via calling REST API using GOLang - java

Is there any REST API from BitBucket, which can be called from a GoLang so that it will create a new REPOSITORY. I can fetch the details of existing but not able to create a new one. Remember CURL is not requirement. Kindly help, stuck from some time into it. Is there any way do it via JAVA as well? If Java can do, then I think GoLang should be able to. Suggest!

Looking through their documentation I found this endpoint which allows you to create repos using their API.
Calling a REST API endpoint can be done from any language.
Here is a nice tutorial where it explains how you can call json API endpoints using GO.

Thanks for Help guys!
Yes, I am able to resolve this issue,with a colleague pointing out the mistake.
Things required:
1. You should be having complete access for the bitBucket.
2. You should have correct URL where to connect with for the REST API. Note: REST API url is different than that of direct URL and get the versions Correct.
Go Code for same is::
import (
"encoding/json"
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url:=fmt.Sprintf("https://<Server BitBucket>/rest/api/1.0/projects/<PROJECT WHERE REPO TO BE CREATED>/repos");
jsonData := map[string]string{"name":"<REPONAME>","scmID":"git","forkable":"true"}
jsonValue,_:=json.Marshal(jsonData)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth("<USERNAME>", "<PASSWORD>")
fmt.Println("++",req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
This will give the response as 201 and yes, it will be created!!

Related

Plaid Quickstart Issues (Java)

I am trying to implement Plaid using the sample code provided on the Java Quickstart [sandbox] and am getting issues when I show the Plaid Dialog (javascript). I am able to successfully get a link_token, but I'm never able to show the dialog. It spins for a brief second, then shows me:
oauth uri does not contain a valid oauth_state_id query parameter. Request ID: DBoT92FCo8AORay
I have tried this with an empty redirectUri, as well as "http://localhost:8080/plaid_test.html", which is registered in my developer account.
I am a bit stuck and hoping someone can direct me in the right direction. I've tested with both versions 9.10.0 and the latest (11.9.0).
Curiously, I am able to get the Java Quickstart working directly, but ONLY if I leave the .env PLAID_REDIRECT_URI blank. If I put localhost in there, it fails when trying to get the link token.
Does anyone have any suggestions on how to overcome this setup issue?
Thank you!
I got this error (oauth uri does not contain a valid oauth_state_id query parameter) while creating a new test application in Plaid's Sandbox environment.
Important note: My application does not use OAuth.
The problem turned out to be, in my configuration parameters being passed to usePlaidLink, I was including a receivedRedirectUri key-value pair. Removing that key-value pair entirely resolved the issue for me.
In other words, my React component looked something like:
import { usePlaidLink } from 'react-plaid-link';
function PlaidLink(props) {
const onSuccess = React.useCallback((public_token, metadata) => {
// ...
});
const config = {
token: props.linkToken,
receivedRedirectUri: window.location.href,
onSuccess,
};
const { open, ready } = usePlaidLink(config);
// ...
}
Removing the line with the receivedRedirectUri was the solution for me, getting me past the oauth uri does not contain a valid oauth_state_id query parameter error, and getting the Plaid Link UI to appear in my app successfully.
This Plaid article, which has a number of mentions of "OAuth state ID" (as mentioned in the error message), helped point me toward this solution.
The issue may be the location you are trying to use -- unless you have manually modified the ports or other code used by the Quickstart, you should use http://localhost:3000/ as the PLAID_REDIRECT_URI (make sure to add this to your Dashboard as an allowed redirect URI). When I tried this just now on the Java quickstart (non-Docker version) it worked fine.

Get JSON with Http status codes

I'm migrating a project from PHP to Java.
I had no problem doing this, but the project contains a HTTP request which I couldn't set up yet. It has to grab a JSON from an API (Authorisation required) and then save it as a variable (which gets passed on to my parser class).
This is the code I've used in php:
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/json' . "\r\n"
. 'Authorization: Bearer ' . $token . "\r\n",
),
)));
$url is the request url and $token the authorisation for the API.
I've already tried a couple of solutions and libraries from StackOverflow, but couldn't get any of these to work in the Java Version. Also I haven't found code which includes the response code, which would actually allow the program to notify the user what went wrong.
Update: I've tried to use the libery linked in the comments, but encoding the url just doesn't work, I get a java.io.UnsupportedEncodingException:
String url = URLEncoder.encode(requestURL,"UTF-8");
I also tried:
Url url = URLEncoder.encode(requestURL,"UTF-8");
which resulted in the same error.
Documentation doesn't help to fix this. Can someone explain what I'm doing wrong or give me some example code?

Cordova passbook from restful response

I am building a cordova application using the cordova-plugin-passbook plugin, which can be seen here: https://github.com/passslot/cordova-plugin-passbook.
I am trying to consume a pkpass from our java server that is returning the file as expected if we directly hit our service from a browser, but the problem is that we need to use an auth token and go through our oAuth server first. So I must request the pass via ajax in my front end using Angular.
The data I get back is an octet-stream and somehow I need to parse it and get it to work with the plugin above. The plugin is configured to look for a url ending in ".pkpass", I am wondering if it can be configured to look for the parsed data instead of a url.
Can anyone see in the src of the plugin if there is a possible way to do that? I am not very familiar with objective c, but just trying to think of options.
Thanks
Using cordova fileTransfer plugin, I got this working:
fileTransfer.download(
uri,
fileURL,
function(entry) {
Passbook.downloadPass(fileURL);
},
function(error) {
alert('Error retrieving pass, please try again in a little while.');
},
true,
{
headers: {
"Authorization": "Bearer " + LS.get( 'user_token' )
}
}
);

play framework- how to send post request using java code in play framework

Currently I'm switching to play framework to develop but I'm new to this wonderful framework.
I just want to send a post request to remote server and get response.
If I use Jersey, it would be quite easy, just like this:
WebResource resource = client.resource("http://myfirstUrl");
resource.addFilter(new LoggingFilter());
Form form = new Form();
form.add("grant_type", "authorization_code");
form.add("client_id", "myclientId");
form.add("client_secret", "mysecret");
form.add("code", "mycode");
form.add("redirect_uri", "http://mysecondUrl");
String msg = resource.accept(MediaType.APPLICATION_JSON).post(String.class, form);
and then I can get the msg which is what I want.
But in Play framework, I cannot find any libs to send such post request. I believe this should be a very simple feature and Play should have integrated it. I've tried to search and found most use case are about the Form in view leve. Could anyone give me some help or examples? Thanks in advance!
You can use Play WS API for making asynchronous HTTP Calls within your Play application. First you should add javaWs as a dependency.
libraryDependencies ++= Seq(
javaWs
)
Then making HTTP POST Requests are as simple as;
WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
post() and other http methods returns a F.Promise<WSResponse> object which is something inherited from Play Scala to Play Java. Basically it is the underlying mechanism of asynchronous calls. You can process and get the result of your request as follows:
Promise<String> promise = WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2")
.map(
new Function<WSResponse, String>() {
public String apply(WSResponse response) {
String result = response.getBody();
return result;
}
}
);
Finally obtained promise object is a wrapper around a String object in our case. And you can get the wrapped String as:
long timeout = 1000l;// 1 sec might be too many for most cases!
String result = promise.get(timeout);
timeout is the waiting time until this asynchronous request will be considered as failed.
For much more detailed explanation and more advanced use cases checkout the documentation and javadocs.
https://www.playframework.com/documentation/2.3.x/JavaWS
https://www.playframework.com/documentation/2.3.x/api/java/index.html

soap set parameter java

I am implementing a TV listing service and I have decided to use ROVI as my data provider.
They provide me with an API that allows me to exchange data between my application and their servers by means of SOAP requests.
Since I am programming in Java, I used wsimport to generate the classes that would enable me to interact with their server.
//Connection
service = new ListingsService();
port = service.getListingsServiceSoap();
I have come across a problem which Google doesn't seem to have the answer for.
According to their API, whenever I want to make a call to a SOAP service I have to add my API Key to the end of url.
The problem is, I don't know how to do that. Using the stubs generated by wsimport, I can create a request object as it should be; however the URL is not displayed as per their specification. The url I currently get is: http://api.rovicorp.com/v9/listingsservice.asmx and what is required is: http://api.rovicorp.com/v9/listingsservice.asmx?apikey=myAPIkey. I obtained that by printing the following code:
System.out.println(port.toString());
Trying to run the following code:
GetServicesRS servicesRS = port.getServices(getServicesRQ, auth)
Yields the following error:
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden
What java method can I use to append this parameter into the SOAP request URL.
Thanks for your help.
Edit.
I am still struggling with this and haven't been lucky with responses, if anyone could point me in the direction of a framework or something that could facilitate this would be great!
Cheers
I manage to work around my problem using something called BindingProvider.
I added the following to my code:
//Connection
service = new ListingsService();
port = service.getListingsServiceSoap();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext()
.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://api.rovicorp.com/v9/listingsservice.asmx?apikey=" + APIKey);
With the aforementioned code the call to the API is successful:
GetServicesRS servicesRS = port.getServices(getServicesRQ, auth)
Hope it helps someone in the future.

Categories

Resources