I have a Task that is to retrieve some Information from a JIRA account through Java. I downloaded the Jira API which is working with Java, but I have no idea how to make it work. I have to pass somewhere my username and password for log in and after that to retrieve what Information I want from what project I want.
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser("admin");
// Here I am getting the error!!
User user = promise.claim();
///////////////////////////////////////
// Print the result
System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));
// Done
System.out.println("Example complete. Now exiting.");
System.exit(0);
That above code is not working, because either if I pass a wrong password and a wrong username is showing me the same result. I have to know how to connect properly to JIRA and retrive some Information in JSON from there! Thank you for your time!
Here is the error
Caused by: com.atlassian.jira.rest.client.api.RestClientException: org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 9 of
I think you don't have the necessary permission to acces Jira , you have to connect with jira with an account that have the correct permissions!
The only thing I can think of is that you are sending incorrect creds. Try using the email address instead of just "admin".
Here is some code that might help: https://github.com/somaiah/jrjc
I check for an issue, but getting user info would be similar.
You can use the below code the get the results.Remember I am using this in my gradle project where I am downloading all the dependencies of JRCJ
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* TODO: Class description
*
* on 20 Jul 2017
*/
class Jira {
private static final String JIRA_URL = "https://JIRA.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "******"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
User user = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
// Done
//System.out.println("Example complete. Now exiting.")
//System.exit(0)
}
}
Related
so I'm trying to use this library library
to access my Spotify account but i can't figure out how i can get an acces token but i can't figure out how i can get the response from the authorization URL I have trayed creating a input stream that access the url and print out the response but i dos not give the right output i have also trayed creating a server with shut receive the response but I'm getting nothing i have never used java server / networking that much so i might have made an error....
public class privat {
public privat() throws IOException {
final String clientId = "clientId ";
final String clientSecret = "clientSecret code ";
final String redirectUri = "http://localhost:8888/callback";
final Api api = Api.builder()
.clientId(clientId)
.clientSecret(clientSecret)
.redirectURI(redirectUri)
.build();
/* Set the necessary scopes that the application will need from the user */
final List<String> scopes = Arrays.asList("user-read-private", "user-read-email");
/* Set a state. This is used to prevent cross site request forgeries. */
final String state = "someExpectedStateString";
String authorizeURL = api.createAuthorizeURL(scopes, state);
System.out.println(authorizeURL);
/* Continue by sending the user to the authorizeURL, which will look something like
https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice
*/
/* Application details necessary to get an access token */
final String code = "" ;/* where to find this ?? */
/* Make a token request. Asynchronous requests are made with the .getAsync method and synchronous requests
* are made with the .get method. This holds for all type of requests. */
final SettableFuture<AuthorizationCodeCredentials> authorizationCodeCredentialsFuture = api.authorizationCodeGrant(code).build().getAsync();
/* Add callbacks to handle success and failure */
Futures.addCallback(authorizationCodeCredentialsFuture, new FutureCallback<AuthorizationCodeCredentials>() {
#Override
public void onSuccess(AuthorizationCodeCredentials authorizationCodeCredentials) {
/* The tokens were retrieved successfully! */
System.out.println("Successfully retrieved an access token! " + authorizationCodeCredentials.getAccessToken());
System.out.println("The access token expires in " + authorizationCodeCredentials.getExpiresIn() + " seconds");
System.out.println("Luckily, I can refresh it using this refresh token! " + authorizationCodeCredentials.getRefreshToken());
/* Set the access token and refresh token so that they are used whenever needed */
api.setAccessToken(authorizationCodeCredentials.getAccessToken());
api.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
}
#Override
public void onFailure(Throwable throwable) {
/* Let's say that the client id is invalid, or the code has been used more than once,
* the request will fail. Why it fails is written in the throwable's message. */
System.out.println(throwable.getMessage());
System.out.println(throwable.getStackTrace());
}
});
}
}
The code comes as a query parameter to your callback URL once the user authorises your application. You'll need to find a way to grab it from there - you could spin up a web server on localhost:8888 to get the code from there - or you could instruct the user to copy the code from the query parameters of the redirect URI once they're redirected. You can find more information about the authorisation procedure (looks like either the authorization code or implicit grant flows will work for you) on the Spotify Developer site.
I would like to list available IP VM's in the new Azure portal using Java SDK.
Couple of years back in the good old classic portal, I had followed the usual management certificate procedure to access vm's,create vm's and work with Azure Endpoints.
Fast fwd now I see that they have used a new portal and new mechanisms to interact with Java SDK. I read somewhere in the above link that with the old way with certificates, I can manage only the class portal resources.
I'm trying to code a simple program which authenticates and lists the vm's of the new portal as a start. Seems like they have complicated it a lot.
I followed the below link to "Create service principal with password"
https://azure.microsoft.com/en-us/documentation/articles/resource-group-authenticate-service-principal/
Then I went to this link
https://azure.microsoft.com/en-us/documentation/samples/resources-java-manage-resource-group/
which asked me go the "See how to create an Auth file" link in above page
(mine is not a webapp and when I try to create the AD as a native client application, it is not allowing me to save keys in configure tab, so I had to create a web app)
After doing all this, I got stuck with this below error
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
'authority' Uri should have at least one segment in the path (i.e.https://<host>/<path>/...)
java.lang.IllegalArgumentException: 'authority' Uri should have at least one segment in the path (i.e. https://<host>/<path>/...)
at com.microsoft.aad.adal4j.AuthenticationAuthority.detectAuthorityType(AuthenticationAuthority.java:190)
at com.microsoft.aad.adal4j.AuthenticationAuthority.<init>(AuthenticationAuthority.java:73)
When I checked it says that the error is because I don't have a valid client application id in your Azure Active Directory.
Is there any simple way to authenticate and start using the API's?
#Vikram, I suggest that you can try to refer to the article to create an application on AAD.
Then you can follow the code below to get the access token for authentication.
// The parameters include clientId, clientSecret, tenantId, subscriptionId and resourceGroupName.
private static final String clientId = "<client-id>";
private static final String clientSecret = "<key>";
private static final String tenantId = "<tenant-id>";
private static final String subscriptionId = "<subscription-id>";
// The function for getting the access token via Class AuthenticationResult
private static AuthenticationResult getAccessTokenFromServicePrincipalCredentials()
throws ServiceUnavailableException, MalformedURLException, ExecutionException, InterruptedException {
AuthenticationContext context;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
// TODO: add your tenant id
context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId, false, service);
// TODO: add your client id and client secret
ClientCredential cred = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken("https://management.azure.com/", cred, null);
result = future.get();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return result;
}
String accessToken = getAccessTokenFromServicePrincipalCredentials().getAccessToken();
If you want to list the VMs on new portal, you can try to use the REST API List the resources in a subscription to get all resources and filter the VMs via the resource type Microsoft.Compute/virtualMachines.
Hope it helps.
Im trying to post some status message on my facebook page, not my personal facebook profile account, but on page i created separately.
My current code looks like this:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Post;
import facebook4j.ResponseList;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class FacebookImpl {
// from https://developers.facebook.com/apps/
static String appId = "11removed";
// from https://developers.facebook.com/apps/
static String appSecret = "c0removed";
// from https://developers.facebook.com/tools/accesstoken/
static String appToken = "11removed";
// my facebook page
static String myFaceBookPage = "niremoved";
public static void main(String[] args) throws FacebookException {
// Make the configuration builder
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
// Set application id, secret key and access token
confBuilder.setOAuthAppId(appId);
confBuilder.setOAuthAppSecret(appSecret);
confBuilder.setOAuthAccessToken(appToken);
// Set permission
// https://developers.facebook.com/docs/facebook-login/permissions
confBuilder.setOAuthPermissions("manage_pages,publish_pages,publish_actions");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
// Create configuration object
Configuration configuration = confBuilder.build();
// Create FacebookFactory and Facebook instance
FacebookFactory ff = new FacebookFactory(configuration);
Facebook facebook = ff.getInstance();
// this one works fine
System.out.println(getFacebookPostes(facebook, myFaceBookPage));
// try to post status
// FacebookException{statusCode=403, errorType='OAuthException',
// errorMessage='(#200) The user hasn't authorized the application to perform this action', errorCode=200, errorSubcode=-1, version=2.4.5}
facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J.");
}
public static String getFacebookPostes(Facebook facebook, String page) throws FacebookException {
ResponseList<Post> results = facebook.getPosts(page);
// as example just to see if i get any data
return results.get(0).getMessage();
}
}
Problem is that i cant post any message on page using this code: facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J."); but i can get messages already posted (via facebook web interfaces) with method getFacebookPostes.
Can anyone help me with this one ? And please do not paste some random dev.Facebook link to look into API.
What i did:
- create app on https://developers.facebook.com/apps/ i have appid, appsecret
Thanks
I have written the code in java that creates an instance of the wrapper and verifies the user's email and password for their account, however with discontinued support for the java SoundCloud API I can't seem to find a way to get a users' likes from this point and I've looked up all the documentation and examples but none seem to work when implemented.
PS. I changed the client id, client secret, and username and password for security so ignore that in the code.
import com.soundcloud.api.ApiWrapper;
import com.soundcloud.api.Token;
import java.io.File;
/**
* Creates an API wrapper instance, obtains an access token and serializes the
* wrapper to disk. The serialized wrapper can then be used for subsequent
* access to resources without re-authenticating
*
* #see GetResource
*/
public final class CreateWrapper {
public static final File WRAPPER_SER = new File("wrapper.ser");
public static void main(String[] args) throws Exception {
final ApiWrapper soundCloud = new ApiWrapper(
"client_id", /*client id*/
"client_secret" /* client_secret */,
null /* redirect URI */,
null /* token */);
Token token;
token = soundCloud.login("username#username.com" /* login */, "password" /* password */);
System.out.println("got token from server: " + token);
// in this example the whole wrapper is serialised to disk -
// in a real application you would just save the tokens and usually have the client_id/client_secret
// hardcoded in the application, as they rarely change
soundCloud.toFile(WRAPPER_SER);
System.out.println("wrapper serialised to " + WRAPPER_SER);
}
}
Look at the developers documentation for the me endpoint
All subresources that are documented in /users are also available via /me. For example /me/tracks will return the tracks owned by the user. Additionally you can access the users dashboard activities through /me/activities and his or her connected external accounts through /me/connections.
https://developers.soundcloud.com/docs/api/reference#me
GET /users/{id}/favorites list of tracks favorited by the user
I am building a java application in order to index some json files using amazon cloudsearch. I think that I've used correct the aws documentation, but I can't make my application work.
package com.myPackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cloudsearchdomain.AmazonCloudSearchDomainClient;
import com.amazonaws.services.cloudsearchdomain.model.UploadDocumentsRequest;
import com.amazonaws.services.cloudsearchdomain.model.UploadDocumentsResult;
public class App
{
public static final String ACCESS_KEY = "myAccessKey";
public static final String SECRET_KEY = "mySecretKey";
public static final String ENDPOINT = "myDocumentEndpoint";
public static void main( String[] args ) throws FileNotFoundException
{
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonCloudSearchDomainClient domain = new AmazonCloudSearchDomainClient(credentials);
domain.setEndpoint(ENDPOINT);
File file = new File("path to my file");
InputStream docAsStream = new FileInputStream(file);
UploadDocumentsRequest req = new UploadDocumentsRequest();
req.setDocuments(docAsStream);
System.out.print(file.length());
UploadDocumentsResult result = domain.uploadDocuments(req);//here i get the exception
System.out.println(result.toString());
//
// SearchRequest searchReq = new SearchRequest().withQuery("my Search request");
// SearchResult s_res = domain.search(searchReq);
// System.out.println(s_res);
}
}
The problem is that I get the following errors:
Exception in thread "main" com.amazonaws.AmazonClientException: Unable to unmarshall error response (Unable to parse error response: '<html><body><h1>403 Forbidden</h1>Request forbidden by administrative rules.</body></html>'). Response Code: 403, Response Text: Forbidden
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1071)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.cloudsearchdomain.AmazonCloudSearchDomainClient.invoke(AmazonCloudSearchDomainClient.java:527)
at com.amazonaws.services.cloudsearchdomain.AmazonCloudSearchDomainClient.uploadDocuments(AmazonCloudSearchDomainClient.java:310)
at gvrhtyhuj.dfgbmn.App.main(App.java:31)
Caused by: com.amazonaws.AmazonClientException: Unable to parse error response: '<html><body><h1>403 Forbidden</h1>Request forbidden by administrative rules.</body></html>'
at com.amazonaws.http.JsonErrorResponseHandler.handle(JsonErrorResponseHandler.java:55)
at com.amazonaws.http.JsonErrorResponseHandler.handle(JsonErrorResponseHandler.java:29)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1045)
... 6 more
Caused by: com.amazonaws.util.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at com.amazonaws.util.json.JSONTokener.syntaxError(JSONTokener.java:422)
at com.amazonaws.util.json.JSONObject.<init>(JSONObject.java:196)
at com.amazonaws.util.json.JSONObject.<init>(JSONObject.java:323)
at com.amazonaws.http.JsonErrorResponseHandler.handle(JsonErrorResponseHandler.java:53)
This is the json file:
{"a":123,"b":"4 5 6"}
First: Please don't put your credentials in your code. It's way too easy to accidentally check credentials into version control, or otherwise post them. If you have your credentials in the default location, you can just do:
AmazonCloudSearchDomainClient client = new AmazonCloudSearchDomainClient();
And the SDK will find them.
One common cause of 403s is getting the endpoint wrong. Make sure you don't have /documents/batch on the end of your endpoint string. The SDK will add that.
One other thing to try is setting the content length:
req.setContentLength(file.length());
My code has that, and works, and is otherwise the same as yours.
You're getting a 403 Forbidden error from CloudSearch, meaning that you don't have permission to upload documents to that domain.
Are you literally using "myAccessKey" as your access key value or did you redact it when you posted this? If you never set it, then you need to set your access key; otherwise check the access policies on your CloudSearch domain through the AWS web console, since it may be configured to accept/reject submissions based on IP address or some other set of conditions.