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
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have started updating with Google Analytics Reports v4 API. I have no prior knowledge. I am trying to generate a simple graph.
I have used the given sample code given in google analytics document. But I am not getting the report at all, but a message
Received verification code. You may now close this window...
No idea why such message displaying. It looks like there is no data available. So far I have done the below things to run the project.
Create the project.
Crate the service.
Create the View with email address retrieved from service's JSON file.
Create client_secrets.json and add it to my src\ folder.
Get the view id and use it in my code.
I do not know which direction to go from here. There are many things to look after and the documentation is really healthy. This is difficult for a beginner like me to decide to choose the right parts.
Also, I have the below questions to know answer.
Is it possible to run it on local server such as Tomcat?
Is google analytics free? Can I use it using my gmail email address?
Is it important to have domain and hosting to get the report in browser?
Am I need to give valid return URL while setting the client settings?
Why am I need to give View ID? If it is to give manually then how do I generate the report dynamically?
Here is my environment and Java code. Please review and help me to find the solution.
I am looking forward to a smooth and clean guidelines.
Environment
Eclipse Java EE with Tomcat 9.0.30 server.
Java used as programming language.
Code
package com.garinst;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting;
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader;
import com.google.api.services.analyticsreporting.v4.model.DateRange;
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues;
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest;
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse;
import com.google.api.services.analyticsreporting.v4.model.Metric;
import com.google.api.services.analyticsreporting.v4.model.Dimension;
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.api.services.analyticsreporting.v4.model.Report;
import com.google.api.services.analyticsreporting.v4.model.ReportRequest;
import com.google.api.services.analyticsreporting.v4.model.ReportRow;
/**
* A simple example of how to access the Google Analytics API.
*/
public class HelloAnalytics {
// Path to client_secrets.json file downloaded from the Developer's Console.
// The path is relative to HelloAnalytics.java.
private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";
// Replace with your view ID.
private static final String VIEW_ID = "96519128";
// The directory where the user's credentials will be stored.
/*
* private static final File DATA_STORE_DIR = new File(
* System.getProperty("user.home"), ".store/hello_analytics");
*/
private static final File DATA_STORE_DIR = new File("hello_analytics");
private static final String APPLICATION_NAME = "Hello Analytics Reporting";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static NetHttpTransport httpTransport;
private static FileDataStoreFactory dataStoreFactory;
public static void main(String[] args) {
try {
AnalyticsReporting service = initializeAnalyticsReporting();
GetReportsResponse response = getReport(service);
printResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initializes an authorized Analytics Reporting service object.
*
* #return The analytics reporting service object.
* #throws IOException
* #throws GeneralSecurityException
*/
private static AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// Load client secrets.
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(HelloAnalytics.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));
// Set up authorization code flow for all authorization scopes.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
clientSecrets, AnalyticsReportingScopes.all()).setDataStoreFactory(dataStoreFactory).build();
// Authorize.
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
// Construct the Analytics Reporting service object.
return new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
/**
* Query the Analytics Reporting API V4. Constructs a request for the sessions
* for the past seven days. Returns the API response.
*
* #param service
* #return GetReportResponse
* #throws IOException
*/
private static GetReportsResponse getReport(AnalyticsReporting service) throws IOException {
// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate("7DaysAgo");
dateRange.setEndDate("today");
// Create the Metrics object.
Metric sessions = new Metric().setExpression("ga:sessions").setAlias("sessions");
// Create the Dimensions object.
Dimension browser = new Dimension().setName("ga:browser");
// Create the ReportRequest object.
ReportRequest request = new ReportRequest().setViewId(VIEW_ID).setDateRanges(Arrays.asList(dateRange))
.setDimensions(Arrays.asList(browser)).setMetrics(Arrays.asList(sessions));
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);
// Call the batchGet method.
GetReportsResponse response = service.reports().batchGet(getReport).execute();
// Return the response.
return response;
}
/**
* Parses and prints the Analytics Reporting API V4 response.
*
* #param response the Analytics Reporting API V4 response.
*/
private static void printResponse(GetReportsResponse response) {
for (Report report : response.getReports()) {
ColumnHeader header = report.getColumnHeader();
List<String> dimensionHeaders = header.getDimensions();
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
List<ReportRow> rows = report.getData().getRows();
if (rows == null) {
System.out.println("No data found for " + VIEW_ID);
return;
}
for (ReportRow row : rows) {
List<String> dimensions = row.getDimensions();
List<DateRangeValues> metrics = row.getMetrics();
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
}
for (int j = 0; j < metrics.size(); j++) {
System.out.print("Date Range (" + j + "): ");
DateRangeValues values = metrics.get(j);
for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
}
}
}
}
}
}
Maven Dependencies
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.30.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client-gson -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
<version>1.30.7</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analyticsreporting</artifactId>
<version>v4-rev20190904-1.30.1</version>
</dependency>
</dependencies>
Received verification code. You may now close this window...
This is the first step in the Oauth2 flow once the user has autorized your access to their google analytics data this code is returned to your application which is then exchanged for an access token. You may want to look into Oauth2 or you could just do what it says and close the window.
Is google analytics free? Can I use it using my gmail email address?
Yes the Google analytics api is free to use. Users login to your application with the user they have set up in their google analytics account
Is it important to have domain and hosting to get the report in browser?
You will need to host your application some place that users can access it. Remember google analytics returns data as Json it will be up to you to build your reports and display it to your users.
Am I need to give valid return URL while setting the client settings?
You will need a valid redirect uri if you are going to host this on the web in order for the authorization process to complete.
Why am I need to give View ID? If it is to give manually then how do I generate the
report dynamically?
Users can have more then one google analytics account each account can have more then one web properly and each web property can have more then one view. Your users need to be able to decide which view they want to see data for.
Note
This system is for requesting data from google analytics the raw data it is returned as json. It is not returned as reports you will need to create your graphics yourself. Oauth2 login is for multi user system anyone can log in to your application its not going to just show your personal data.
comment question
Is there any possibility to get the dynamic result such as user will login and get his own data?
Thats how oauth2 works. The user logs in your application has access to their data
How is it possible to display the JSON data in graphical reports as available in google analytics?
You will either need to create a library for graphics or find one already created for you by a third party and plug in the data you get back from Google analytics. APIs just return json data they dont have any control over how you the developer display it.
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.
Using CuratorFramework, could someone explain how I can:
Create a new path
Set data for this path
Get this path
Using username foo and password bar? Those that don't know this user/pass would not be able to do anything.
I don't care about SSL or passwords being sent via plaintext for the purpose of this question.
ACL in Apache Curator are for access control. Therefore, ZooKeeper do not provide any authentication mechanism like, clients who don't have correct password cannot connect to ZooKeeper or cannot create ZNodes. What it can do is, preventing unauthorized clients from accessing particular Znode/ZNodes. In order to do that, you have to setup CuratorFramework instance as I have described below. Remember, this will guarantee that, a ZNode create with a given ACL, can be again accessed by the same client or by a client presenting the same authentication information.
First you should build the CuratorFramework instane as follows. Here, the connectString means a comma separated list of ip and port combinations of the zookeeper servers in your ensemble.
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(connectString)
.retryPolicy(new ExponentialBackoffRetry(retryInitialWaitMs, maxRetryCount))
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs);
/*
* If authorization information is available, those will be added to the client. NOTE: These auth info are
* for access control, therefore no authentication will happen when the client is being started. These
* info will only be required whenever a client is accessing an already create ZNode. For another client of
* another node to make use of a ZNode created by this node, it should also provide the same auth info.
*/
if (zkUsername != null && zkPassword != null) {
String authenticationString = zkUsername + ":" + zkPassword;
builder.authorization("digest", authenticationString.getBytes())
.aclProvider(new ACLProvider() {
#Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
#Override
public List<ACL> getAclForPath(String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
CuratorFramework client = builder.build();
Now you have to start it.
client.start();
Creating a path.
client.create().withMode(CreateMode.PERSISTENT).forPath("/your/ZNode/path");
Here, the CreateMode specify what type of a node you want to create. Available types are PERSISTENT,EPHEMERAL,EPHEMERAL_SEQUENTIAL,PERSISTENT_SEQUENTIAL,CONTAINER. Java Docs
If you are not sure whether the path up to /your/ZNode already exists, you can create them as well.
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/your/ZNode/path");
Set Data
You can either set data when you are creating the ZNode or later. If you are setting data at the creation time, pass the data as a byte array as the second parameter to the forPath() method.
client.create().withMode(CreateMode.PERSISTENT).forPath("/your/ZNode/path","your data as String".getBytes());
If you are doing it later, (data should be given as a byte array)
client.setData().forPath("/your/ZNode/path",data);
Finally
I don't understand what you mean by get this path. Apache Curator is a java client (more than that with Curator Recipes) which use Apache Zookeeper in the background and hides edge cases and complexities of Zookeeper. In Zookeeper, they use the concept of ZNodes to store data. You can consider it as the Linux directory structure. All ZNodePaths should start with / (root) and you can go on specifying directory like ZNodePaths as you like. Ex: /someName/another/test/sample.
As shown in the above diagram, ZNode are organized in a tree structure. Every ZNode can store up to 1MB of data. Therefore, if you want to retrieve data stored in a ZNode, you need to know the path to that ZNode. (Just like you should know the table and column of a database in order to retrive data).
If you want to retrive data in a given path,
client.getData().forPath("/path/to/ZNode");
That's all you have to know when you want to work with Curator.
One more thing
ACL in Apache Curator are for access control. That is, if you set ACLProvider as follows,
new ACLProvider() {
#Override
public List<ACL> getDefaultAcl () {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
#Override
public List<ACL> getAclForPath (String path){
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
}
only the client with the credentials identical to the creator will be given access to the corresponding ZNode later on. Autherization details are set as follows (See the client building example). There are other modes of ACL availble, like OPEN_ACL_UNSAFE which do not do any access control if you set it as the ACLProvider.
authorization("digest", authorizationString.getBytes())
they will be used later to control access to a given ZNode.
In short, if you want to prevent others from interfering your ZNodes, you can set the ACLProvider to return CREATOR_ALL_ACL and set the authorization to digest as shown above. Only the CuratorFramework instances using the same authorization string ("username:password") will be able to access those ZNodes. But it will not prevent others from creating ZNodes in paths which are not interfering with yours.
Hope you found what you want :-)
It wasn't part of the original question, but I thought I would share a solution I came up with in which the credentials used determine the access level.
I didn't have much luck finding any examples and kept ending up on this page so maybe it will help someone else. I dug through the source code of Curator Framework and luckily the org.apache.curator.framework.recipes.leader.TestLeaderAcls class was there to point me in the right direction.
So in this example:
One generic client used across multiple apps which only needs to read data from ZK.
Another admin client has the ability to read, delete, and update nodes in ZK.
Read-only or admin access is determined by the credentials used.
FULL-CONTROL ADMIN CLIENT
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
public class AdminClient {
protected static CuratorFramework client = null;
public void initializeClient() throws NoSuchAlgorithmException {
String zkConnectString = "127.0.0.1:2181";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
final List<ACL> acls = new ArrayList<>();
//full-control ACL
String zkUsername = "adminuser";
String zkPassword = "adminpass";
String fullControlAuth = zkUsername + ":" + zkPassword;
String fullControlDigest = DigestAuthenticationProvider.generateDigest(fullControlAuth);
ACL fullControlAcl = new ACL(ZooDefs.Perms.ALL, new Id("digest", fullControlDigest));
acls.add(fullControlAcl);
//read-only ACL
String zkReadOnlyUsername = "readuser";
String zkReadOnlyPassword = "readpass";
String readOnlyAuth = zkReadOnlyUsername + ":" + zkReadOnlyPassword;
String readOnlyDigest = DigestAuthenticationProvider.generateDigest(readOnlyAuth);
ACL readOnlyAcl = new ACL(ZooDefs.Perms.READ, new Id("digest", readOnlyDigest));
acls.add(readOnlyAcl);
//create the client with full-control access
client = CuratorFrameworkFactory.builder()
.connectString(zkConnectString)
.retryPolicy(retryPolicy)
.authorization("digest", fullControlAuth.getBytes())
.aclProvider(new ACLProvider() {
#Override
public List<ACL> getDefaultAcl() {
return acls;
}
#Override
public List<ACL> getAclForPath(String string) {
return acls;
}
})
.build();
client.start();
//Now create, read, delete ZK nodes
}
}
READ-ONLY CLIENT
import java.security.NoSuchAlgorithmException;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class ReadOnlyClient {
protected static CuratorFramework client = null;
public void initializeClient() throws NoSuchAlgorithmException {
String zkConnectString = "127.0.0.1:2181";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
String zkReadOnlyUsername = "readuser";
String zkReadOnlyPassword = "readpass";
String readOnlyAuth = zkReadOnlyUsername + ":" + zkReadOnlyPassword;
client = CuratorFrameworkFactory.builder()
.connectString(zkConnectString)
.retryPolicy(retryPolicy)
.authorization("digest", readOnlyAuth.getBytes())
.build();
client.start();
//Now read ZK nodes
}
}
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)
}
}
I have the following Google Cloud Endpoints API, and I want it accesible only for authenticated users with certain role.
Few lines of code says much more than a thousand words:
import com.google.appengine.api.users.User;
#Api(
name = "heroesApi",
version = "v1",
clientIds = {...},
scopes = {...},
audiences = {...},
namespace = #ApiNamespace(
ownerDomain = "my.domain.com",
ownerName = "my.domain.com",
packagePath=""
)
)
public class HeroesApi {
// THIS IS THE FUNCTION THAT I DON´T KNOW WHERE TO PUT
/**
* Validates that the user is logged in with a specific role
* #param user
* #throws UnauthorizedException
* #throws ForbiddenException
*/
private void validateUser(User user) throws UnauthorizedException, ForbiddenException {
IUserController userController = ControllerFactory.get.userController();
if (user == null) {
throw new ForbiddenException("You must be logged in, my friend.");
} else if (!userController.isLoggedAsSuperHero(user)) {
throw new UnauthorizedException("You must be logged in as a Superhero.");
}
}
// API METHODS
#ApiMethod(path = "something", httpMethod = ApiMethod.HttpMethod.PUT)
public DoneTask doSomething(Some thing, User superhero) throws UnauthorizedException, ForbiddenException {
// this is what I want to avoid on each function
this.validateUser(superhero);
// Now I'll do something special
IUserController userController = ControllerFactory.get.userController();
return userController.doSome(thing);
}
// MORE GORGEOUS METHODS JUST FOR SUPERHEROES, SO I HAVE TO PERFORM THE VALIDATION...
}
I have though about adding a filter through the web.xml file for all request to /api/heroesApi/*, but the problem there is how to catch the Google Appengine Api User.
Isn´t there something provided by Google to do this?
Any suggestion to avoid the repeated call to validateUser(User) is welcome
Google Cloud Endpoints doesn't supper roles by default , so your application have to build role concept, and you have to write filter and get current user and check against the roles maintained in your end
To get current user in the filter, try this
https://cloud.google.com/appengine/docs/java/oauth/
I haven't tested this , but am sure you can get the current user using the UserService Api in appengine as long as your system uses google account as authentication.