Error while running documentum code - documentum

I am getting an error while running the documentum code at:
config.setString("primary_host", docbroker);
in the below code:
IDfClient client = DfClient.getLocalClient();
// getting the config object of local client
IDfTypedObject config = client.getClientConfig();
config.setString("primary_host", docbroker);
IDfLoginInfo li = new DfLoginInfo();
and the error I was getting is below:
Error:
java.lang.IllegalStateException: Reference count is already zero
at com.documentum.fc.impl.util.ReferenceCountManager.decrement(ReferenceCountManager.java:47)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.decrementReferenceCount(DocbrokerMapUnion.java:43)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.removeEntry(DocbrokerMapUnion.java:37)
at com.documentum.fc.client.impl.docbroker.DocbrokerMap.removeEntries(DocbrokerMap.java:176)
at com.documentum.fc.client.impl.docbroker.DocbrokerClient$PreferencesObserver.update(DocbrokerClient.java:251)
at com.documentum.fc.common.impl.preferences.TypedPreferences.notifyObservers(TypedPreferences.java:559)
at com.documentum.fc.common.impl.preferences.TypedPreferences.setString(TypedPreferences.java:168)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.connectToDocumentum(FetchDocumentumStats.java:357)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.run(FetchDocumentumStats.java:92)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please can anyone help me. I am new to documentum.

From my experience, it is best to use the IDfClientX interface and work your way from there. Perhaps this example will help you:
// This is just an example. You might want to encapsulate this functionality in a class of your own
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
public class Main {
public static void main(String[] args) throws DfException {
IDfClientX clientX = new DfClientX();
IDfClient client = clientX.getLocalClient();
IDfTypedObject clientConfig = client.getClientConfig();
IDfLoginInfo loginInfo = clientX.getLoginInfo();
IDfSessionManager sessionManager = client.newSessionManager();
IDfSession session = connect(clientConfig, loginInfo, sessionManager, "<your host here>", 1489, "<your docbase here>", "<your username here>", "<your password here>");
// Do something with session
}
public static IDfSession connect(IDfTypedObject clientConfig, IDfLoginInfo loginInfo, IDfSessionManager sessionManager, String host, int port, String docbase, String user, String password) throws DfException {
clientConfig.setString("primary_host", host);
clientConfig.setInt("primary_port", port);
loginInfo.setUser(user);
loginInfo.setPassword(password);
sessionManager.clearIdentities();
sessionManager.setIdentity(docbase, loginInfo);
return sessionManager.getSession(docbase);
}
}

Related

Exception occurs while performing update operation using the java code in bigquery

I am using the jobs.query API to update the bigquery table records using java.
While running this as a part of stability tests for a longer time, we get an exception. Excpetion occurs almost after 5 hours, 11 hours...
The problem is, exception returns blank error message, blank cause, and blank stack trace. So, in this case, I am not able to find the actual cause of the error.
Request your response on this.
Thanks in advance!
package app;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.QueryRequest;
import com.google.api.services.bigquery.model.QueryResponse;
public class WhereCLause {
//Create Entry Point: Main function
public static void main(String[] args) throws IOException, ParseException {
String projectId = "projectId";
// Create a new Bigquery client authorized via Application Credentials.
Bigquery bigquery = createAuthorizedClient();
String query = "UPDATE datasetId.tableName SET Name = 'RefUpdate' WHERE ID = 001";
System.out.println(query);
executeQuery(query, bigquery, projectId);
}
public static Bigquery createAuthorizedClient() throws IOException {
String jsonFilePath="file.json";
// Create the credential
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
InputStream credentialStream = new FileInputStream(new File(jsonFilePath));
GoogleCredential credential = GoogleCredential.fromStream(credentialStream, transport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(BigqueryScopes.all());
}
return new Bigquery.Builder(transport, jsonFactory, credential).setApplicationName("BigqueryApplication").build();
}
private static void executeQuery(String querySql, Bigquery bigquery, String projectId) throws IOException {
QueryResponse query = bigquery.jobs().query(projectId, new QueryRequest().setQuery(querySql).setUseLegacySql(true)).execute();
System.out.println(query.getNumDmlAffectedRows());
System.err.println(query.getErrors());
}
}

peer not authenticated - Rally javatoolkit error

I have been using the rally javatoolkit for a while to add testcases, test results etc without any error. But all of a sudden it started throwing error as
" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated" . I have referred the pages "rally rest api java toolkit sslpeerunverifiedexception : peer not authenticated" , rally rest api java toolkit sslpeerunverifiedexception : peer not authenticated but they didn't help me. Can someone help me with what I am doing wrong. Also If i need to download a certificate please help me for windows system. Thanks in advance. my code is as below:
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.client.HttpClient;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.response.GetResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.scheme.Scheme;
public class ConnnectionTestWithHTTPClient {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String applicationName = "Connnection Test With HTTPClient";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
//restApi.setProxy(new URI("http://myproxy.mycompany.com"), "MyProxyUsername", "MyProxyPassword"); //SET PROXY SETTINS HERE
HttpClient client = restApi.getClient();
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(X509Certificate[] certificate, String authType)
throws CertificateException {
//trust all certs
return true;
}
}, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, sf));
String workspaceRef = "/workspace/12345"; //USE VALID WORKSPACE OID
GetRequest getRequest = new GetRequest(workspaceRef);
GetResponse getResponse = restApi.get(getRequest);
System.out.println(getResponse.getObject());
} catch (Exception e) {
System.out.println(e);
} finally {
restApi.close();
}
}
}
Also adding to the issue, i found a different error when I changed the port from 443 to 8443. i get "java.io.IOException: HTTP/1.1 522 Origin Connection Time-out" when i use 8443.
For some reason when I uncomment the line //restApi.setProxy(new URI("http://myproxy.mycompany.com"), "MyProxyUsername", "MyProxyPassword"); with correct inputs, the error goes off.
For all those who need the inputs, please put in the following:
restApi.setProxy(new URI("http://rally1.rallydev.com"), "xyz#abc.com", "rallypassword");
so the working code is as below:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.client.HttpClient;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.response.GetResponse;
public class ConnnectionTestWithHTTPClient {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_apikey";
String applicationName = "Connnection Test With HTTPClient";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
restApi.setProxy(new URI("http://rally1.rallydev.com"), "abc#abc.com", "rallypassword"); //YOUR PROXY SETTINGS HERE
HttpClient client = restApi.getClient();
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(X509Certificate[] certificate, String authType)
throws CertificateException {
//trust all certs
return true;
}
}, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, sf));
String workspaceRef = "/workspace/1234";
GetRequest getRequest = new GetRequest(workspaceRef);
GetResponse getResponse = restApi.get(getRequest);
System.out.println(getResponse.getObject());
} catch (Exception e) {
System.out.println(e);
} finally {
restApi.close();
}
}
}

GDK Authentication mirror.accounts.insert.execute()

This is the test code for authentication and insert Account :
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Lists;
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.Mirror.Accounts.Insert;
import com.google.api.services.mirror.model.Account;
import com.google.api.services.mirror.model.AuthToken;
public class InsertAccountWithJava {
private static final String SERVICE_ACCOUNT_EMAIL ="540223414844-tqpuqtbv07klpuuk3q04qha0g88094uu#developer.gserviceaccount.com";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH ="C:/Users/Yuan/Desktop/eyenotes-db176c40f51f.p12";
private static final String ACCOUNT_TYPE = "com.eyenotes";
private static final Collection<String> MIRROR_ACCOUNT_SCOPES =Arrays.asList("https://www.googleapis.com/auth/glass.thirdpartyauth");
private static String userToken = "6164da1732ea09b4";
private static String accountName="zhongmei";
private static String authTokenType ="eyenotes";
private static String authToken="myauthtoken";
public static void main(String[] args) {
try {
Mirror mirror = getMirrorService();
createAccount(mirror, userToken, accountName, authTokenType, authToken);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public static Mirror getMirrorService() throws GeneralSecurityException, IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(MIRROR_ACCOUNT_SCOPES)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Mirror service = new Mirror.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
public static void createAccount(Mirror mirror, String userToken, String accountName,
String authTokenType, String authToken) {
try {
Account account = new Account();
List<AuthToken> authTokens = Lists.newArrayList();
AuthToken authToken1 = new AuthToken().setType(authTokenType).setAuthToken(authToken);
authTokens.add(authToken1);
account.setAuthTokens(authTokens);
account.setPassword("zmyl123456");
Insert insert = mirror.accounts().insert(userToken, ACCOUNT_TYPE, accountName, account);
insert.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
============================================================================
I got the exception below:
============================================================================
Fabruary 06, 2015 1:42:21 pm com.google.api.client.googleapis.services.AbstractGoogleClient <init>
warning: Application name is not set. Call Builder#setApplicationName.
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
}, {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
}
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:1049)
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 com.ccfsz.service.InsertAccountWithJava.createAccount(InsertAccountWithJava.java:81)
at com.ccfsz.service.InsertAccountWithJava.main(InsertAccountWithJava.java:30)
=====================================================================================
Parameters explaination:
SERVICE_ACCOUNT_EMAIL:Generated when i create new Client ID in developer console.
SERVICE_ACCOUNT_PKCS12_FILE_PATH:Generated when i create new Client ID in developer console.
ACCOUNT_TYPE:I provided to google when submit my application.
userToken:I got from the authentication url provided to google.
accountName,authTokenType and authToken is arbitrary String.
2.Before i execute the code above ,do i need to do anything else?
3.I can get google authorization page through (https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/glass.timeline+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile&access_type=offline&approval_prompt=force&include_granted_scopes=true&client_id=540223414844-jjhqevuu0rhmoa3u6gkd05g7v29i89kk.apps.googleusercontent.com&redirect_uri=http://www.eyenotes.com/glass/login.php) using web application .how can i get this page and get permission using service account.
4.Who can give me any hint ? Sometimes,after execute test code above,i got nothing.in this case,according to their source code , this means i got a Http response code between 200 and 300, but i never get Accounts on my glass device which accountType equals "com.eyenotes".sometimes it return 400 with the excepiton above.
who have any idea,please tell me.I am very appreciate.
The userToken may not be the same every single time. Instead of hard-coding it to a String, I would get the token sent to your sign-in page during the authentication process.
Also, the error says you will need to call setApplicationName(String) on your Mirror object in the following code:
Mirror service = new Mirror.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
Refer to line 38 here.

Using OAuth retrieve access token without redirecting to a webpage

I had written a java program which uses client id and client secret for authentication. When i run my program it gives an url and when i go to that url it gives me access token. How can i programatically get the access token without using a browser?
My code:
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.User;
import com.google.api.services.admin.directory.model.Users;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class DirectoryCommandLine {
private static String CLIENT_ID = "YOUR_CLIENT_ID";
private static String CLIENT_SECRET = "YOUR_CLIENT_SECRET";
private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
.setAccessType("online")
.setApprovalPrompt("auto").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);
System.out.println("Enter authorization code:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
// Create a new authorized API client
Directory service = new Directory.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("DirectoryCommandLine")
.build();
List<User> allUsers = new ArrayList<User>();
Directory.Users.List request = service.users().list().setCustomer("my_customer");
// Get all users
do {
try {
Users currentPage = request.execute();
allUsers.addAll(currentPage.getUsers());
request.setPageToken(currentPage.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0 );
// Print all users
for (User currentUser : allUsers) {
System.out.println(currentUser.getPrimaryEmail());
}
}
}
You do need to use a browser to get user's authorization, but you only have to do it exactly once if you store your refresh token securely.
What's your scenario? You can use embedded browser in mobile, and get the authorization code automatically.

getting an error while acessing google calendar API. Null pointer exception

I get a error message below .. when I run the code for hitting google Calendar API.There is a client_secrets.json file that has the credentials (client ID and redirectID) . I unzipped and ran the package google gave, it successfully runs and I could see that by a "Success,Add code here"message. after which it throws me a nullpointer exception for which I'm not sure what has gone wrong.please help. Downloaded the sample project from here https://developers.google.com/api-client-library/java/apis/calendar/v3
May 01, 2014 12:59:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Aishwarya Anand\.store\calendar_sample
May 01, 2014 12:59:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Aishwarya Anand\.store\calendar_sample
Success! Now add code here.
inserting event ...
Aish Event from the new Google API
2014-05-01T16:59:42.545Z
2014-05-01T17:59:42.545Z
java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
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 com.google.api.services.samples.calendar.cmdline.CalendarSample.insertEventTest(CalendarSample.java:170)
at com.google.api.services.samples.calendar.cmdline.CalendarSample.main(CalendarSample.java:116)
Class here,
package com.google.api.services.samples.calendar.cmdline;
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.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Date;
import java.util.TimeZone;
public class CalendarSample {
/**
* Be sure to specify the name of your application. If the application name is {#code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "Caritas-CalendarAPI/1.0";
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/calendar_sample");
/**
* Global instance of the {#link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
#SuppressWarnings("unused")
private static Calendar client;
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
// Set up authorization code flow.
// Ask for only the permissions you need. Asking for more permissions will
// reduce the number of users who finish the process for giving you access
// to their accounts. It will also increase the amount of effort you will
// have to spend explaining to users what you are doing with their data.
// Here we are listing all of the available scopes. You should remove scopes
// that you are not actually using.
Set<String> scopes = new HashSet<String>();
scopes.add(CalendarScopes.CALENDAR);
scopes.add(CalendarScopes.CALENDAR_READONLY);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, scopes)
.setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args) {
try {
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// initialize the data store factory
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up global Calendar instance
client = new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
System.out.println("Success! Now add code here.");
insertEventTest();
//getEventList();
//getEventTest();
//sertEventTest();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
private static void getEventList() throws IOException {
String pageToken = null;
do {
Events events = client.events().list("primary").setPageToken(pageToken).execute();
List<Event> items = events.getItems();
for (Event event : items) {
System.out.println(" id: " + event.getId() + "; summary: " + event.getSummary());
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
}
private static void getEventTest() throws IOException {
String eventId = "idkoi3c55lvegs2ev333u28grk5c";
Event event = client.events().get("primary", eventId).execute();
System.out.println(event.getSummary());
}
private static void insertEventTest() throws IOException {
System.out.println("inserting event ...");
Event event = new Event();
event.setSummary("Aish Event from the new Google API");
event.setLocation("Somewhere");
System.out.println(event.getSummary());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
event.setStart(new EventDateTime().setDateTime(start));
System.out.println(start.toStringRfc3339());
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
event.setEnd(new EventDateTime().setDateTime(end));
System.out.println(end.toStringRfc3339());
Event createdEvent = client.events().insert("primary", event).execute();
System.out.println("event id" + createdEvent.getId());
}
}