while accessing profile data from google plus getting following exception my code is below - google-api

Exception in thread "main"
com.google.api.client.googleapis.json.GoogleJsonResponseException: 404
Not Found Not Found at
com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at
com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at
com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
at
com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1045)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at
com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at googleplusdemo2.MyClass.main(MyClass.java:107)
public class MyClass {
// List the scopes your app requires:
private static List<String> SCOPE = Arrays.asList(
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/plus.profiles.read",
"https://www.googleapis.com/auth/plus.circles.write",
"https://www.googleapis.com/auth/plus.stream.write",
"https://www.googleapis.com/auth/plus.stream.read");
// The following redirect URI causes Google to return a code to the user's
// browser that they then manually provide to your app to complete the
// OAuth flow.
private static final String REDIRECT_URI = "http://some url";
static String CLIENT_ID="myclient id";
static String CLIENT_SECRET="myclient secret";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
new JacksonFactory(),
CLIENT_ID, // This comes from your Developers Console project
CLIENT_SECRET, // This, as well
SCOPE)
.setApprovalPrompt("force")
.setAccessType("offline").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then " +
"type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
// End of command line prompt for the authorization code.
GoogleTokenResponse tokenResponse = flow.newTokenRequest(code)
.setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.addRefreshListener(new CredentialRefreshListener() {
#Override
public void onTokenResponse(Credential credential, TokenResponse tokenResponse) {
// Handle success.
System.out.println("Credential was refreshed successfully.");
}
#Override
public void onTokenErrorResponse(Credential credential,
TokenErrorResponse tokenErrorResponse) {
// Handle error.
System.err.println("Credential was not refreshed successfully. "
+ "Redirect to error page or login screen.");
}
})
.build();
// Set authorized credentials.
credential.setFromTokenResponse(tokenResponse);
credential.refreshToken();
// Create a new authorized API client
PlusDomains plusDomains = new PlusDomains.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName("TESTMK3").build();
Person mePerson = plusDomains.people().get("me").execute();
mePerson.getGender();
System.out.println("ID:\t" + mePerson.getId());
System.out.println("Display Name:\t" + mePerson.getDisplayName());
System.out.println("Image URL:\t" + mePerson.getImage().getUrl());
System.out.println("Profile URL:\t" + mePerson.getUrl());
}
}

Related

WS Webservice template UnsupportedCallbackException

I am facing an issue with invoking webService template with ws security using keystores and interceptors, it returns
org.apache.wss4j.common.ext.WSSecurityException: Callback supplied no password for: 1
javax.security.auth.callback.UnsupportedCallbackException
where 1 is the key store alias..
bellow is the code I am using followed with the exception
public class SOAPConnector extends WebServiceGatewaySupport {
public Object callWebService() throws Exception {
KeyStore encryptionKeyStore = KeyStore.getInstance("JKS");
InputStream fis = new FileInputStream("C:\\Ahmed\\keyStore\\eip_stg_server_message_signature.jks");
encryptionKeyStore.load(fis, "changeit".toCharArray());
KeyStore signitureKeyStore = KeyStore.getInstance("JCEKS");
InputStream fis2 = new FileInputStream("C:\\Ahmed\\keyStore\\keystore2022_testing.jks");
signitureKeyStore.load(fis2, "changeit".toCharArray());
fis.close();
fis2.close();
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
Properties cryptoFactoryBeanConfig = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "changeit");
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "C:\\Ahmed\\keyStore\\keystore2022_testing.jks");
cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean.afterPropertiesSet();
CryptoFactoryBean cryptoFactoryBean2 = new CryptoFactoryBean();
Properties cryptoFactoryBeanConfig2 = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "changeit");
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "C:\\Ahmed\\keyStore\\eip_stg_server_message_signature.jks");
cryptoFactoryBean2.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean2.afterPropertiesSet();
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Signature Encrypt Timestamp");
interceptor.setSecurementPassword("changeit");
interceptor.setSecurementSignatureUser("1");
interceptor.setSecurementSignatureKeyIdentifier("DirectReference");
interceptor.setSecurementEncryptionKeyIdentifier("DirectReference");
interceptor.setSecurementSignatureCrypto(cryptoFactoryBean.getObject());
interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean2.getObject());
interceptor.setSecurementEncryptionUser("eip stg server message signature (device ca - 2)");
//timeStamp
interceptor.setTimestampPrecisionInMilliseconds(false);
interceptor.setFutureTimeToLive(10000);
interceptor.setSecurementTimeToLive(10000);
interceptor.setValidationActions("Signature Encrypt Timestamp");
interceptor.setValidationTimeToLive(10000);
interceptor.setValidationSignatureCrypto(cryptoFactoryBean2.getObject());
interceptor.setValidationDecryptionCrypto(cryptoFactoryBean.getObject());
KeyStoreCallbackHandler ks = new KeyStoreCallbackHandler();
ks.setPrivateKeyPassword("changeit");
ks.setKeyStore(signitureKeyStore);
interceptor.setValidationCallbackHandler(ks);
WebServiceTemplate template = getWebServiceTemplate();
template.setInterceptors(new ClientInterceptor[]{interceptor});
String requestXml = "xml request";
StreamSource source = new StreamSource(new StringReader(requestXml));
StreamResult result = new StreamResult(System.out);
String uri = "url";
SoapActionCallback requestCallback = new SoapActionCallback("action_name");
try {
template.sendSourceAndReceiveToResult(uri, source, requestCallback, result);
}
catch (SoapFaultException sfe) {
throw new Exception("SoapFaultException", sfe);
}
catch (WebServiceTransportException wste) {
throw new Exception("WebServiceTransportException", wste);
}
return null;
}
it returns UnsupportedCallbackException
following is error details
Original Exception was org.apache.wss4j.common.ext.WSSecurityException: Callback supplied no password for: 1
Original Exception was javax.security.auth.callback.UnsupportedCallbackException
<?xml version="1.0" encoding="UTF-8"?><soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><faultcode>soapenv:Client</faultcode><faultstring xml:lang="en">Callback supplied no password for: 1; nested exception is org.apache.wss4j.common.ext.WSSecurityException: Callback supplied no password for: 1
Original Exception was org.apache.wss4j.common.ext.WSSecurityException: Callback supplied no password for: 1
Original Exception was javax.security.auth.callback.UnsupportedCallbackException</faultstring></soapenv:Fault>null
org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error
Process finished with exit code 0
I'm not sure what I am missing here
can any one relate please?
PS. I am using the same key stores with soap ui and it works fine

EWS modern authentication using oauth2.0 : The remote server returned an error: (401)Unauthorized

I am trying to do modern authentication for outlook mailbox(which is used to send mail from applications) using microsoft graph access token.
I am succssfully getting the access token from the below code:
public class AuthTokenAccess {
public AuthTokenAccess() {}
public static String getAccessToken(String tenantId, String clientId, String clientSecret, String scope)
{
String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenantId);
String postBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&resource=%s&scope=%s",
clientId, clientSecret, "https://management.azure.com/", scope);
String accessToken = null;
try{
HttpURLConnection conn = (HttpURLConnection) new URL(endpoint).openConnection();
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.getOutputStream().write(postBody.getBytes());
conn.connect();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(conn.getInputStream());
//String accessToken = null;
while (parser.nextToken() != JsonToken.END_OBJECT) {
String name = parser.getCurrentName();
if ("access_token".equals(name)) {
parser.nextToken();
accessToken = parser.getText();
}
}
}catch(Exception e) {
}
return accessToken;
}
after getting the access token I am sending this to ExchangeService:
public ExchangeService getExchangeServiceObj(String emailId, String token, String emailServerURI) throws URISyntaxException {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
if(service != null) {
service.getHttpHeaders().put("Authorization", "Bearer " + token);
service.getHttpHeaders().put("X-AnchorMailbox", emailId);
service.setUrl(new URI(emailServerURI)); //https://outlook.office365.com/EWS/Exchange.asmx
}
LOGGER.debug("getExchangeServiceObj() {}.", "ends");
return service;
}
Here, I am getting the ExchangeService object but when I am trying send mail microsoft.exchange.webservices.data.core.service.item.EmailMessage.sendAndSaveCopy() throws Exception
public void sendMail(String toMail, String ccMail, String subject, String body, String pathOfFileToAttach) {
ExchangeService emailService = getExchangeServiceObj(
ResourceUtils.getPropertyValue("email_user"),
token,
ResourceUtils.getPropertyValue("ews_server"));
if(!StringUtils.hasText(toMail)) {
toMail = ccMail;
}
EmailMessage emessage = new EmailMessage(emailService);
emessage.setSubject(subject);
String strBodyMessage = body;
strBodyMessage = strBodyMessage + "<br /><br />";
LOGGER.info("Body: {} ", body);
MessageBody msg = new MessageBody(BodyType.HTML, strBodyMessage);
emessage.setBody(msg);
emessage.sendAndSaveCopy();
LOGGER.info("Email send {}", "sucessfully");
} catch(Exception e) {
LOGGER.error(Constants.ERROR_STACK_TRACE, e);
throw new CommonException(e);
}
}
Tried with below scopes:
"https://outlook.office.com/EWS.AccessAsUser.All",
"https://graph.microsoft.com/.default"
Below is the access token I am getting using the above code:
{"aud": "https://management.azure.com/",
"iss": "https://sts.windows.net/3863b7d0-213d-40f3-a4d0-6cd90452245a/",
"iat": 1628068305,
"nbf": 1628068305,
"exp": 1628072205,
"aio": "E2ZgYEjcvsaipUV1wxwxrne/9F4XAAA=",
"appid": "055eb578-4716-4901-861b-92f2469dac9c",
"appidacr": "1",
"idp": "https://sts.windows.net/3863b7d0-213d-40f3-a4d0-6cd90452245a/",
"oid": "33688cee-e16e-4d11-8ae0-a804805ea007",
"rh": "0.AUYA0LdjOD0h80Ck0GzZBFIkWni1XgUWRwFJhhuS8kadrJxGAAA.",
"sub": "33688cee-e16e-4d11-8ae0-a804805ea007",
"tid": "3863b7d0-213d-40f3-a4d0-6cd90452245a",
"uti": "nZUVod_e3EuO_T-Ter-_AQ",
"ver": "1.0",
"xms_tcdt": 1626687774
}
as you could see scope is not included in the token. Do I need to pass any other thing while getting the token.
Azure active directory set up:
registered application
2.Create client secret
3.Added redirect URL
added permission
Can someone please help me here, where I am doing mistake or is other any other way to make it work. Thank you
I can see a few issue here first your using the client credentials flow which requires that you assign Application Permission and you only have Delegate permission, with EWS the only Application permission that will work is full_access_as_app see https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth (app-only section)
String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenantId);
String postBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&resource=%s&scope=%s",
clientId, clientSecret, "https://management.azure.com/", scope);
Your mixing V1 and V2 authentication (see https://nicolgit.github.io/AzureAD-Endopoint-V1-vs-V2-comparison/) here which won't work (scope will just be ignored) for the v1 endpoint eg what you have in https://login.microsoftonline.com/%s/oauth2/token is the V1 auth endpoint so your request shouldn't include the scope just the resource and that resource should be https://outlook.office.com

unable to call a REST webservice..Full authentication required

I am currently working on spring application and REST webservices.
I have created a REST webservice in one application and want to access that service from other applications.
Below is the error its showing when trying to access the webservice.
RestClientException : org.springframework.web.client.HttpClientErrorException: 401 Full authentication is required to access this resource
Below is my webservice code:
#RequestMapping(value = MyRequestMapping.GET_ACC_DATA, method = RequestMethod.GET)
#ResponseBody
public MyResponseDTO getSigDataValues(#PathVariable final String acc, final HttpServletResponse response) throws Exception {
MyResponseDTO responseDTO = null;
try {
//logic goes here
//responseDTO = ..
} catch (Exception e) {
LOG.error("Exception" + e);
}
return responseDTO;
}
I am calling above webservice from another application.In the below mentioned method I am calling the webservice and its throwing me the exception org.springframework.web.client.HttpClientErrorException.
public MyResponseDTO getAccData(String acc){
try{
list= (List<String>)restTemplate.postForObject(MyDataURL.GET_ACC_DATA.value(), MyResponseDTO.class, acc);
}
catch (final RestClientException e)
{
LOG.info("RestClientException :" + e);
}
Please suggest, what am I missing.
You would need to authenticate against the REST service. One of the most common ways is Basic Authentication. If this is what the service is using you would need to create an AUTHORIZATION header with Base 64 encoded usernamen + password.
RestTemplate allow to set customer headers before the request gets sent.
The process of creating the Authorization header is relatively straightforward for Basic Authentication, so it can pretty much be done manually with a few lines of code:
private HttpHeaders createHeaders(String username, String password) {
return new HttpHeaders() {
private static final long serialVersionUID = -1704024310885506847L;
{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
}
};
}
Then, sending a request becomes just as simple:
ResponseEntity<Dados> response = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET,
new HttpEntity<Dados>(createHeaders(usuario, senha)), Dados.class);

sheets api error access denied exception desp Requested client not authorized

Hi I am using Google apis.. I have successfully able to access google drive and google calendar but when i try to access google spreadsheet i am getting following exception.
Exception in thread "main" com.google.gdata.util.AuthenticationException: Failed to refresh access token: 403 Forbidden
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
Caused by: com.google.api.client.auth.oauth2.TokenResponseException: 403 Forbidden
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
My code is as follows
private static Credential authorize() throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
String SERVICE_ACCOUNT_EMAIL = "xxx#developer.gserviceaccount.com";
List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds/");
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File("xxx.p12"))
.setServiceAccountUser("xx#zzz.com")
.build();
return credential;
}
public static void main(String[] args) throws Exception {
Credential credential = authorize();
SpreadsheetService service = new SpreadsheetService("new data service ");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
service.setOAuth2Credentials(credential);
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
Thanks
I was only passing the spreadsheet scope, I have to pass both drive and sheet scope. Now I am able to read spreadsheets from drive.. Here is the corrected code.
String SERVICE_ACCOUNT_EMAIL = "xxxx#developer.gserviceaccount.com";
ArrayList<String> scopes = new ArrayList<String>();
scopes.add(0, DriveScopes.DRIVE);
scopes.add(1, "https://spreadsheets.google.com/feeds");
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File("xx.p12"))
.setServiceAccountUser("yyy#example.com")
.build();

How do I control Token Response Expiry time for google API access

I have problem extending the standard one hour for validity of google access token.
One part of my code is getting authorization from the user, using the GoogleAuthorizationCodeFlow as per Google recommendation. This works fine and gives me a TokenResponse that I persist to be used in an other part of the application where the user is not connected.
As per Google documentation, I thought that the "offline" access type in the flow would enable the TokenResponse to be usable as longer as the user doesnt revoke it. But apparently when I use this TokenReponse just after the user authorization, it works fine but when I use it after more than one hour, I get an "invalid credentials" sent back by Google.
Here is the code which creates the TokenResponse once the user has authorized it :
private HttpTransport HTTP_TRANSPORT;
private JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static GoogleAuthorizationCodeFlow flow;
#PostConstruct
public void init() {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
logger.info(String.format("Raised Exception while getting GoogleNetHttpTransport : %s", e.getMessage()));
e.printStackTrace();
}
flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, APP_ID, APP_SECRET,
Collections.singleton(CalendarScopes.CALENDAR_READONLY)).setAccessType("offline").build();
}
#RequestMapping(value = Uris.GOOGLERD)
public ModelAndView googleCallBack(HttpServletRequest request, #RequestParam(value = "state", required = false) String state,
#RequestParam(value = "code", required = false) String code,
#RequestParam(value = "error", required = false) String error, Model model) {
DynSubscriber dynSubscriber = (DynSubscriber) request.getSession().getAttribute("dynSubscriber");
ModelAndView toReturn = new ModelAndView("confirmation");
toReturn.addObject("buttonLabel", "Accueil");
try {
AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code);
TokenResponse tr = tokenRequest.setRedirectUri(request.getRequestURL().toString()).execute();
// Json Conversion of Token Response for future use
StringWriter jsonTrWriter = new StringWriter();
JsonGenerator generator = JSON_FACTORY.createJsonGenerator(jsonTrWriter);
generator.serialize(tr);
generator.flush();
generator.close();
//Persists google access info
dynSubOp.setSPConnexionInfo(dynSubscriber, jsonTrWriter.toString(), DynServiceProviderType.GOOGLECAL);
toReturn.addObject("message","Agenda Google autorisé");
} catch (IOException | DynServicesException e) {
logger.error(String.format("Exception raised in googleCallBack for subscriber %s : %s", dynSubscriber.buildFullName(), e.getMessage()),e);
toReturn.addObject("message", "Problème lors du processus d'autorisation google");
}
return toReturn;
}
}
And here is the offline code which uses this TokenReponse :
private com.google.api.services.calendar.Calendar calendarConnection;
public DynGoogleCalendarRetriever(String subid, String connectionInformation)
throws CalendarConnectionNotAuthorizedException {
TokenResponse tr;
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
tr = JSON_FACTORY.fromString(connectionInformation, TokenResponse.class);
Credential c = new GoogleCredential().setFromTokenResponse(tr);
calendarConnection = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, c)
.build();
} catch (IOException | GeneralSecurityException e) {
logger.error(String.format("Failure creating the credentials for subscriber id %s", subid), e);
throw new CalendarConnectionNotAuthorizedException(String.format(
"Failure creating the credentials for subscriber id %s", subid), e);
}
}
Looks like this was already answered in this other SO question.
To get the refresh token that enables what I want, I need to build the flow with a approval_prompt=force parameter (builder.setApprovalPrompt("force"))
As per the comment, this requires the offline access which is done in the flow initialization.
A complement however : the offline code in my question doesn't work as such although I copied and pasted it from google documentation (probably an older version). The Credential needs to use its Builder object.
Here is the fully functionnal offline code :
TokenResponse tr;
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
tr = JSON_FACTORY.fromString(connectionInformation, TokenResponse.class);
Credential c = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
.setClientSecrets(APP_ID, APP_SECRET).build().setFromTokenResponse(tr);
calendarConnection = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, c)
.build();
} catch (IOException | GeneralSecurityException e) {
logger.error(String.format("Failure creating the credentials for subscriber id %s", subid), e);
throw new CalendarConnectionNotAuthorizedException(String.format(
"Failure creating the credentials for subscriber id %s", subid), e);
}

Resources