I am trying to fetch contacts of gmail using
Google Contacts API
and
Oauth 2.0 API.
I am totally new to this concept. I was trying the same code given in the this link to fetch all the contacts but somehow it won't work.
My code
ContactsService service = new ContactsService("<var>Contacts
Fetcher</var>"); // Exception on this line
public ContactsService authenticateId()
{
try
{
service.setUserCredentials("example#gmail.com", "123456");
}
catch(Exception e)
{
e.printStackTrace();
}
return service;
}
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.copyOf([Ljava/lang/Object;)Lcom/google/common/collect/ImmutableSet;
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableTypes(AltFormat.java:399)
at com.google.gdata.wireformats.AltFormat$Builder.setAcceptableXmlTypes(AltFormat.java:387)
at com.google.gdata.wireformats.AltFormat.<clinit>(AltFormat.java:49)
at com.google.gdata.client.Service.<clinit>(Service.java:558)
at javamails.ContactsFetcher.<init>(ContactsFetcher.java:25)
at javamails.ContactsFetcher.main(ContactsFetcher.java:68)
I tried to read the references and documentation given by the google but it seems not much helpful for me. If anyone has a simple example or another api to fetch the gmail contacts please let me know.
Make sure to include the required dependencies of the libraries you use at runtime. It seems you forgot to include the Guava library. Therefor the com.google.common.collect.ImmutableSet.copyOf method (that is defined in that library) cannot be found.
If you tell us more about how you compile and run your code, we could tell you what setting to change.
Related
I'm trying to implement a custom keycloack Authenticator SPI for authentication purposes against an external Identity provider. The users already exist on the keycloak store, I only need connection to the custom SPI to authenticate them.
I'm following section 8.3 of the official guide https://www.keycloak.org/docs/latest/server_development/index.html#_auth_spi_walkthrough, which is very similar to what I need.
The problem I'm running into is that after the authentication flow runs into the "action" method of the custom Authenticator, an exception is thrown from the AuthenticationProcessor Class, which after inspection, comes from following check:
// org.keycloak.authentication.AuthenticationProcessor - line 876
if (authenticationSession.getAuthenticatedUser() == null) {
throw new AuthenticationFlowException(AuthenticationFlowError.UNKNOWN_USER);
}
after seeing this problem, my idea for trying solving it, was getting the user (already verified against the externl Identity Provider) from the keycloak store, and pushing it into the AuthenticationSession, like this:
// Connect against external Service Provider
// and asume "USER_ID" represents an already validated User
// AuthenticationFlowContext = afc is given as parameter
UserFederationManager ufm = afc.getSession().users(); // <-- PROBLEM
UserModel userFound = ufm.getUserById("USER_ID", afc.getRealm());
if (userFound != null) {
// get reference to the authSession
AuthenticationSessionModel asm = afc.getAuthenticationSession();
// set authenticated user on the session
asm.setAuthenticatedUser(userFound );
return true;
}
return false;
The problem with the above code, is that a Java NoSuchMethodExceptionError is thrown regarding the users() method of the org.keaycloak.models.KeycloackSession class. Like this:
11:26:32,628 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-14) Uncaught server error: java.lang.NoSuchMethodError: org.keycloak.models.KeycloakSession.users()Lorg/keycloak/models/UserFederationManager;
Any suggestion that you could make to help me solve this would be greatly appreciated!
It seems the problem was that I was using an org.keycloak.models.UserFederationManager instance, instead of an org.keycloak.models.UserProvider instance. The UserFederationManager implements the UserProvider, and it seems the more general type works better than the more specific type under the injection mechanism this keycloak is using
// UserFederationManager ufm = afc.getSession().users(); // <-- PROBLEM
// UserProvider ufm = afc.getSession().users(); // <-- WORKS
Even though it works now, both of your suggestions are valid because my build version is indeed diferent that the one on the runtime, I'll solve that to avoid further Bugs.
Thanks your input Guys!
As Henry stated, it's likely to be a version conflict. I had a similar problem which was solved with this thread's help. It suggests you downgrade some dependencies version, but in my case, we solved it changing back our server to Tomcat.
Well, I'm trying to get all users from Openfire server using Smack, unfortunately I don't know how - I'm using Smack 4.2.2.
UserSearchManager usm= new UserSearchManager(connection);
DomainBareJid domainJid =
JidCreate.domainBareFrom(connection.getServiceName());
Form searchForm = usm.getSearchForm(domainJid);
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", "*");
ReportedData data = usm.getSearchResults(answerForm, domainJid);
if (data.getRows() != null) {
for (ReportedData.Row row: data.getRows()) {
for (String jid:row.getValues("jid")) {
System.out.println(jid);
}
}
}
This code doesn't work because of:
java.lang.IllegalArgumentException: Must have a local (user) JID set. Either you didn't configure one or you where not connected at least once
You can't get all users through XEP-0055: Jabber Search, just can be used with a filter you sure that the users don't have it (like a special character). Only way I know is to use Rest API Plugin of openfire. You can read more about this plugin from the link. Good luck.
Error is obvious. Either you did not connect at least once (or got disconnected and did not reconnect) or your username is wrong.
Maybe you are trying to connect without local jid. Please check this explanation of XMPP address formats:
https://xmpp.org/rfcs/rfc6122.html#addressing-localpart
hope you have solved the problem. I got my code working with this little change
DomainBareJid domainJid =
JidCreate.domainBareFrom("search." + connection.getServiceName());
in your openfire go to Plugins and select available-plugins > then choose rest Api > then you can use following url to Get All users in Group:
http://localhost:9090/plugins/restapi/v1/users
Note: All Rest EndPoints you can find in following link:
https://www.igniterealtime.org/projects/openfire/plugins/1.2.1/restAPI/readme.html
While trying to develop an application that interacts with some cloud services I found the Dropbox API for Java to be especially confusing.
Specifically how to find the HTTP errors. For instance, with the Google Drive API if a request fails an IOException will be thrown however you can parse that IOException into a GoogleJsonResponseException which you can then extract the status code.
try {
File f =drive.files().create(fileMetadata).setFields("id").execute();
return f.getId();
} catch (IOException e) {
if (e instanceof GoogleJsonResponseException){
int statusCode = ((GoogleJsonResponseException) e).getStatusCode();
errorHandler(statusCode);
} else {
e.printStackTrace();
}
}
So is there something like this in the java dropbox API (Specifically 3.0.5).
I have been looking around and it seems like no but I wanted to make sure before I go down the rabbit hole of extremely specialized and complex coding like mentioned here. If it is could someone please give me an example of how I could properly handle these exceptions.
[Cross-linking for reference: https://www.dropboxforum.com/t5/API-support/How-to-get-error-responses-java-api/m-p/258338#M14989 ]
The Dropbox Java SDK automatically parses out the structured error data from the HTTPS response into native classes, and you can use as much or little of that specificity as you want. The structured error responses (generally JSON in the response body) offer much more granularity than just status codes.
For example, here's the code sample that is now missing from StackOverflow documentation from my post that you linked to:
try {
SharedLinkMetadata sharedLinkMetadata = client.sharing().createSharedLinkWithSettings("/test.txt");
System.out.println(sharedLinkMetadata.getUrl());
} catch (CreateSharedLinkWithSettingsErrorException ex) {
System.out.println(ex);
} catch (DbxException ex) {
System.out.println(ex);
}
And here's an example that shows how to check for a particular error case (i.e., a "path" error in that example).
That's the recommended way of handling these exceptions. I don't believe the SDK offers a way to retrieve the original unparsed error response. (If you don't want to use the SDK though, you can call the HTTPS endpoints yourself directly.)
I'm (new at this) developing a macro plugin that builds on data that an existing plugin provides via its REST API. They would run on the same instance of Confluence, version 5.9.
I cannot use the Java API of the plugin, since it only provides access to a very limited amount of classes, so I decided on using Rest.
Given that the user has already authenticated with Confluence, is there any way to communicate my current user credentials from my plugins Java Rest client to the other one, preferably not using Basic Authentication?
So far, I've tried:
Shared Access Layer - this apparently used to work with the method Request#addTrustedTokenAuthentication() but is deprecated in SAL 3.0.5,
see SAL Documentation (outdated?), and SAL Version Matrix
ApplicationLink - would allow me to link to another application, but apparently it's not possible to link back to the same Confluence instance
SAL TrustedRequestFactory- comments on this atlassian answer indicate there might be a way using this, but I can't seem to figure it out (yet).
I've also tried reading up on atlassian documentation and posted a similar question on atlassian answers here. I don't mean to double post, but unfortunately, looking at other questions on that platform, few seem to get answered in a timely fashion so I thought I'd try my luck here.
Seems like this isn't a very common problem, but I thought I'd post how we eventually solved this, just in case it's needed again:
#Component
public class RestClient {
#ComponentImport
private TrustedTokenFactory tokenFactory;
// [...]
public String doRequest(HttpClient client, String url) throws Exception {
TrustedTokenAuthenticator auth =
new TrustedTokenAuthenticator(tokenFactory);
HttpMethod method = auth.makeMethod(client, url);
try {
// add request headers, etc...
int statusCode = client.executeMethod(method);
// be sure to use response data here, catch exceptions...
} finally {
method.releaseConnection();
}
}
}
Im working on oauth 1 Sparklr and Tonr sample apps and I'm trying to create a two-legged call. Hipoteticly the only thing you're supposed to do is change the Consumer Details Service from (Im ommiting the igoogle consumer info to simplify):
<oauth:consumer-details-service id="consumerDetails">
<oauth:consumer name="Tonr.com" key="tonr-consumer-key" secret="SHHHHH!!!!!!!!!!"
resourceName="Your Photos" resourceDescription="Your photos that you have uploaded to sparklr.com."/>
</oauth:consumer-details-service>
to:
<oauth:consumer-details-service id="consumerDetails">
<oauth:consumer name="Tonr.com" key="tonr-consumer-key" secret="SHHHHH!!!!!!!!!!"
resourceName="Your Photos" resourceDescription="Your photos that you have uploaded to sparklr.com."
requiredToObtainAuthenticatedToken="false" authorities="ROLE_CONSUMER"/>
</oauth:consumer-details-service>
That's adding requiredToObtainAuthenticatedToken and authorities which will cause the consumer to be trusted and therefore all the validation process is skipped.
However I still get the login and confirmation screen from the Sparklr app. The current state of the official documentation is pretty precarious considering that the project is being absorbed by Spring so its filled up with broken links and ambiguous instructions. As far as I've understood, no changes are required on the client code so I'm basically running out of ideas. I have found people actually claiming that Spring-Oauth clients doesn't support 2-legged access (which I found hard to believe)
The only way I have found to do it was by creating my own ConsumerSupport:
private OAuthConsumerSupport createConsumerSupport() {
CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();
consumerSupport.setStreamHandlerFactory(new DefaultOAuthURLStreamHandlerFactory());
consumerSupport.setProtectedResourceDetailsService(new ProtectedResourceDetailsService() {
public ProtectedResourceDetails loadProtectedResourceDetailsById(
String id) throws IllegalArgumentException {
SignatureSecret secret = new SharedConsumerSecret(
CONSUMER_SECRET);
BaseProtectedResourceDetails result = new BaseProtectedResourceDetails();
result.setConsumerKey(CONSUMER_KEY);
result.setSharedSecret(secret);
result.setSignatureMethod(SIGNATURE_METHOD);
result.setUse10a(true);
result.setRequestTokenURL(SERVER_URL_OAUTH_REQUEST);
result.setAccessTokenURL(SERVER_URL_OAUTH_ACCESS);
return result;
}
});
return consumerSupport;
}
and then reading the protected resource:
consumerSupport.readProtectedResource(url, accessToken, "GET");
Has someone actually managed to make this work without boiler-plate code?