Tech Rocks

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more... contact@tech-rocks.org

Showing posts with label google apps. Show all posts
Showing posts with label google apps. Show all posts

Saturday, March 1, 2014

Google Sites API in java

import com.google.gdata.client.http.HttpGDataRequest;
import com.google.gdata.client.sites.SitesService;
import com.google.gdata.data.Link;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.OutOfLineContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.XhtmlTextConstruct;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.data.sites.ActivityFeed;
import com.google.gdata.data.sites.AnnouncementEntry;
import com.google.gdata.data.sites.AnnouncementsPageEntry;
import com.google.gdata.data.sites.AttachmentEntry;
import com.google.gdata.data.sites.BaseActivityEntry;
import com.google.gdata.data.sites.BaseContentEntry;
import com.google.gdata.data.sites.BasePageEntry;
import com.google.gdata.data.sites.CommentEntry;
import com.google.gdata.data.sites.ContentFeed;
import com.google.gdata.data.sites.FileCabinetPageEntry;
import com.google.gdata.data.sites.ListItemEntry;
import com.google.gdata.data.sites.ListPageEntry;
import com.google.gdata.data.sites.RevisionFeed;
import com.google.gdata.data.sites.SiteFeed;
import com.google.gdata.data.sites.SiteEntry;
import com.google.gdata.data.sites.SitesLink;
import com.google.gdata.data.sites.Theme;
import com.google.gdata.data.sites.WebAttachmentEntry;
import com.google.gdata.data.sites.WebPageEntry;
import com.google.gdata.data.spreadsheet.Column;
import com.google.gdata.data.spreadsheet.Field;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;
import com.google.gdata.util.XmlParser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.activation.MimetypesFileTypeMap;

/**
* Wrapper class for lower level Sites API calls.
*
*
*/
public class SitesHelper {

private String domain;
private String siteName;

public SitesService service;
public MimetypesFileTypeMap mediaTypes;

public static final String[] KINDS = {
"announcement", "announcementspage", "attachment", "comment",
"filecabinet", "listitem", "listpage", "webpage", "webattachment"
};

/**
* Constructor
*
* @param applicationName The name of the application.
* @param domain The Site's Google Apps domain or "site".
* @param siteName The webspace name of the Site.
*/
public SitesHelper(String applicationName, String domain, String siteName) {
this(applicationName, domain, siteName, false);
}

/**
* Constructor
*
* @param applicationName The name of the application.
* @param domain The Site's Google Apps domain or "site".
* @param siteName The webspace name of the Site.
* @param logging Whether to enable HTTP requests to stdout
*/
public SitesHelper(String applicationName, String domain, String siteName,
boolean logging) {
if (logging) {
turnOnLogging(false);
}

this.domain = domain;
this.siteName = siteName;
this.service = new SitesService(applicationName);

registerMediaTypes();
}

private void registerMediaTypes() {
// Common MIME types used for uploading attachments.
mediaTypes = new MimetypesFileTypeMap();
mediaTypes.addMimeTypes("application/msword doc");
mediaTypes.addMimeTypes("application/vnd.ms-excel xls");
mediaTypes.addMimeTypes("application/pdf pdf");
mediaTypes.addMimeTypes("text/richtext rtx");
mediaTypes.addMimeTypes("text/csv csv");
mediaTypes.addMimeTypes("text/tab-separated-values tsv tab");
mediaTypes.addMimeTypes("application/x-vnd.oasis.opendocument.spreadsheet ods");
mediaTypes.addMimeTypes("application/vnd.oasis.opendocument.text odt");
mediaTypes.addMimeTypes("application/vnd.ms-powerpoint ppt pps pot");
mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument."
+ "wordprocessingml.document docx");
mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument."
+ "spreadsheetml.sheet xlsx");
mediaTypes.addMimeTypes("audio/mpeg mp3 mpeg3");
mediaTypes.addMimeTypes("image/png png");
mediaTypes.addMimeTypes("application/zip zip");
mediaTypes.addMimeTypes("application/x-tar tar");
mediaTypes.addMimeTypes("video/quicktime qt mov moov");
mediaTypes.addMimeTypes("video/mpeg mpeg mpg mpe mpv vbs mpegv");
mediaTypes.addMimeTypes("video/msvideo avi");
}

/**
* Authenticates the user using ClientLogin
*
* @param username User's email address.
* @param password User's password.
*/
public void login(String username, String password) throws AuthenticationException {
service.setUserCredentials(username, password);
}

/**
* Authenticates the user using AuthSub
*
* @param authSubToken A valid AuthSub session token.
*/
public void login(String authSubToken) {
service.setAuthSubToken(authSubToken);
}

/**
* Logs HTTP requests and XML to stdout.
*/
private void turnOnLogging(boolean logXML) {
// Create a log handler which prints all log events to the console
ConsoleHandler logHandler = new ConsoleHandler();
logHandler.setLevel(Level.ALL);

// Configure the logging mechanisms
Logger httpLogger =
Logger.getLogger(HttpGDataRequest.class.getName());
httpLogger.setLevel(Level.ALL);
httpLogger.addHandler(logHandler);

if (logXML) {
Logger xmlLogger = Logger.getLogger(XmlParser.class.getName());
xmlLogger.setLevel(Level.ALL);
xmlLogger.addHandler(logHandler);
}
}

/**
* Returns an entry's numeric ID.
*/
private String getEntryId(BaseContentEntry<?> entry) {
String selfLink = entry.getSelfLink().getHref();
return selfLink.substring(selfLink.lastIndexOf("/") + 1);
}

/**
* Returns an entry's numeric ID.
*/
private String getEntryId(String selfLink) {
return selfLink.substring(selfLink.lastIndexOf("/") + 1);
}

public String getContentFeedUrl() {
return "https://sites.google.com/feeds/content/" + domain + "/" + siteName + "/";
}

public String getRevisionFeedUrl() {
return "https://sites.google.com/feeds/revision/" + domain + "/" + siteName + "/";
}

public String getActivityFeedUrl() {
return "https://sites.google.com/feeds/activity/" + domain + "/" + siteName + "/";
}

public String getSiteFeedUrl() {
return "https://sites.google.com/feeds/site/" + domain + "/";
}

public String getAclFeedUrl(String siteName) {
return "https://sites.google.com/feeds/acl/site/" + domain + "/" + siteName + "/";
}

/**
* Fetches and displays the user's site feed.
*/
public void getSiteFeed() throws IOException, ServiceException {
SiteFeed siteFeed = service.getFeed(
new URL(getSiteFeedUrl()), SiteFeed.class);
for (SiteEntry entry : siteFeed.getEntries()){
System.out.println("title: " + entry.getTitle().getPlainText());
System.out.println("site name: " + entry.getSiteName().getValue());
System.out.println("theme: " + entry.getTheme().getValue());
System.out.println("");
}
}

/**
* Fetches and displays a Site's acl feed.
*/
public void getAclFeed(String siteName) throws IOException, ServiceException {
AclFeed aclFeed = service.getFeed(
new URL(getAclFeedUrl(siteName)), AclFeed.class);
for (AclEntry entry : aclFeed.getEntries()) {
System.out.println(entry.getScope().getValue() + " (" +
entry.getScope().getType() + ") : " + entry.getRole().getValue());
}
}

/**
* Fetches and displays the Site's activity feed.
*/
public void getActivityFeed() throws IOException, ServiceException {
ActivityFeed activityFeed = service.getFeed(
new URL(getActivityFeedUrl()), ActivityFeed.class);
for (BaseActivityEntry<?> entry : activityFeed.getEntries()){
System.out.println(entry.getSummary().getPlainText());
}
}

/**
* Fetches and displays the revisions feed for an entry.
*/
public void getRevisionFeed(String contentEntryId) throws IOException, ServiceException {
URL url = new URL(getRevisionFeedUrl() + contentEntryId);
RevisionFeed revisionFeed = service.getFeed(url, RevisionFeed.class);
for (BaseContentEntry<?> entry : revisionFeed.getEntries()) {
System.out.println(entry.getTitle().getPlainText());
System.out.println(" updated: " + entry.getUpdated().toUiString() + " by " +
entry.getAuthors().get(0).getEmail());
System.out.println(" revision #: " + entry.getRevision().getValue());
}
}

/**
* Fetches and displays entries from the content feed.
*
* @param kind An entry kind to fetch. For example, "webpage". If null, the
* entire content feed is returned.
*/
public void listSiteContents(String kind) throws IOException, ServiceException {
String url = kind.equals("all") ? getContentFeedUrl() : getContentFeedUrl() + "?kind=" + kind;
ContentFeed contentFeed = service.getFeed(new URL(url), ContentFeed.class);

for (WebPageEntry entry : contentFeed.getEntries(WebPageEntry.class)) {
System.out.println("WebPageEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
System.out.println(" authors: " + entry.getAuthors().get(0).getEmail());
System.out.println(" content: " + getContentBlob(entry));
System.out.println("");
}

for (ListPageEntry entry : contentFeed.getEntries(ListPageEntry.class)) {
System.out.println("ListPageEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
for (Column col : entry.getData().getColumns()) {
System.out.print(" [" + col.getIndex() + "] " + col.getName() + "\t");
}
System.out.println("");
}

for (ListItemEntry entry : contentFeed.getEntries(ListItemEntry.class)) {
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
for (Field field : entry.getFields()) {
System.out.print(" [" + field.getIndex() + "] " + field.getValue() + "\t");
}
System.out.println("\n");
}

for (FileCabinetPageEntry entry : contentFeed.getEntries(FileCabinetPageEntry.class)) {
System.out.println("FileCabinetPageEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
System.out.println(" content: " + getContentBlob(entry));
System.out.println("");
}

for (CommentEntry entry : contentFeed.getEntries(CommentEntry.class)) {
System.out.println("CommentEntry:");
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
System.out.println(" in-reply-to: " + entry.getInReplyTo().toString());
System.out.println(" content: " + getContentBlob(entry));
System.out.println("");
}

for (AnnouncementsPageEntry entry : contentFeed.getEntries(AnnouncementsPageEntry.class)) {
System.out.println("AnnouncementsPageEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
System.out.println(" content: " + getContentBlob(entry));
System.out.println("");
}

for (AnnouncementEntry entry : contentFeed.getEntries(AnnouncementEntry.class)) {
System.out.println("AnnouncementEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
System.out.println(" draft?: " + entry.isDraft());
System.out.println(" content: " + getContentBlob(entry));
System.out.println("");
}

for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
System.out.println("AttachmentEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
if (entry.getSummary() != null) {
System.out.println(" description: " + entry.getSummary().getPlainText());
}
System.out.println(" revision: " + entry.getRevision().getValue());
MediaContent content = (MediaContent) entry.getContent();
System.out.println(" src: " + content.getUri());
System.out.println(" content type: " + content.getMimeType().getMediaType());
System.out.println("");
}

for (WebAttachmentEntry entry : contentFeed.getEntries(WebAttachmentEntry.class)) {
System.out.println("WebAttachmentEntry:");
System.out.println(" title: " + entry.getTitle().getPlainText());
System.out.println(" id: " + getEntryId(entry));
if (entry.getParentLink() != null) {
System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
}
if (entry.getSummary() != null) {
System.out.println(" description: " + entry.getSummary().getPlainText());
}
System.out.println(" src: " + ((MediaContent) entry.getContent()).getUri());
System.out.println("");
}
}

public String getContentBlob(BaseContentEntry<?> entry) {
return ((XhtmlTextConstruct) entry.getTextContent().getContent()).getXhtml().getBlob();
}

private void setContentBlob(BaseContentEntry<?> entry) {
XmlBlob xml = new XmlBlob();
xml.setBlob(String.format(
"content for %s", entry.getCategories().iterator().next().getLabel()));
entry.setContent(new XhtmlTextConstruct(xml));
}

public SiteEntry createSite(String title, String summary)
throws MalformedURLException, IOException, ServiceException {
return createSite(title, summary, null);
}

/**
* Creates a new Google Sites.
*
* @param title A name for the site.
* @param summary A description for the site.
* @param theme A theme to create the site with.
* @return The created site entry.
* @throws ServiceException
* @throws IOException
* @throws MalformedURLException
*/
public SiteEntry createSite(String title, String summary, String theme)
throws MalformedURLException, IOException, ServiceException {
SiteEntry entry = new SiteEntry();
entry.setTitle(new PlainTextConstruct(title));
entry.setSummary(new PlainTextConstruct(summary));

// Set theme if user specified it.
if (theme != null) {
Theme tt = new Theme();
tt.setValue(theme);
entry.setTheme(tt);
}

return service.insert(new URL(getSiteFeedUrl()), entry);
}

/**
* Copies a Google Site from an existing site.
*
* @param title A title heading for the new site.
* @param summary A description for the site.
* @param theme A theme to create the site with.
* @param sourceHref The self link of the site entry to copy this site from.
* If null, an empty site is created.
* @return The created site entry.
* @throws ServiceException
* @throws IOException
* @throws MalformedURLException
*/
public SiteEntry copySite(String title, String summary, String sourceHref)
throws MalformedURLException, IOException, ServiceException {
SiteEntry entry = new SiteEntry();
entry.setTitle(new PlainTextConstruct(title));
entry.setSummary(new PlainTextConstruct(summary));
entry.addLink(SitesLink.Rel.SOURCE, Link.Type.ATOM, sourceHref);

return service.insert(new URL(getSiteFeedUrl()), entry);
}

public BaseContentEntry<?> createPage(String kind, String title)
throws MalformedURLException, SitesException, IOException, ServiceException {
return createPage(kind, title, null);
}

/**
* Creates a new (sub)page.
*
* @param kind The type of page to created (e.g. webpage, filecabinet, listpage, etc).
* @param title A title heading for the page
* @param parent The full URL of the parent to create the subpage under
* or the parent entry's ID (e.g. 1234567890).
* @return The created entry.
* @throws SitesException
* @throws ServiceException
* @throws IOException
* @throws MalformedURLException
*/
public BaseContentEntry<?> createPage(String kind, String title, String parent)
throws SitesException, MalformedURLException, IOException, ServiceException {
BaseContentEntry<?> entry = null;
if (kind.equals("announcement")) {
entry = new AnnouncementEntry();
} else if (kind.equals("announcementspage")) {
entry = new AnnouncementsPageEntry();
} else if (kind.equals("comment")) {
entry = new CommentEntry();
} else if (kind.equals("filecabinet")) {
entry = new FileCabinetPageEntry();
} else if (kind.equals("listitem")) {
entry = new ListItemEntry();
} else if (kind.equals("listpage")) {
entry = new ListPageEntry();
} else if (kind.equals("webpage")) {
entry = new WebPageEntry();
} else {
if (kind.equals("attachment") || kind.equals("webattachment")) {
throw new SitesException("Trying to create " + kind
+ ". Please use upload command instead.");
} else {
throw new SitesException("Unknown kind '" + kind + "'");
}
}

entry.setTitle(new PlainTextConstruct(title));
setContentBlob(entry);

// Upload to a parent page?
if (parent != null) {
if (parent.lastIndexOf("/") == -1) {
parent = getContentFeedUrl() + parent;
}
entry.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parent);
}

return service.insert(new URL(getContentFeedUrl()), entry);
}

/**
* Downloads a file from the specified URL to disk.
*
* @param downloadUrl The full URL to download the file from.
* @param fullFilePath The local path to save the file to on disk.
* @throws ServiceException
* @throws IOException
*/
private void downloadFile(String downloadUrl, String fullFilePath) throws IOException,
ServiceException {
System.out.println("Downloading file from: " + downloadUrl);

MediaContent mc = new MediaContent();
mc.setUri(downloadUrl);
MediaSource ms = service.getMedia(mc);

InputStream inStream = null;
FileOutputStream outStream = null;

try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(fullFilePath);

int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}

/**
* Downloads an attachment.
*
* @param entry The attachment (entry) to download.
* @param directory Path to a local directory to download the attach to.
* @throws ServiceException
* @throws IOException
*/
public void downloadAttachment(AttachmentEntry entry, String directory)
throws IOException, ServiceException {
String url = ((OutOfLineContent) entry.getContent()).getUri();
downloadFile(url, directory + entry.getTitle().getPlainText());
}

/**
* Downloads an attachment.
*
* @param entry The attachment (entry) to download.
* @param entryId The content entry id of the attachment (e.g. 1234567890)
* @throws ServiceException
* @throws IOException
*/
public void downloadAttachment(String entryId, String directory)
throws IOException, ServiceException {
AttachmentEntry attachment = service.getEntry(
new URL(getContentFeedUrl() + entryId), AttachmentEntry.class);
String url = ((OutOfLineContent) attachment.getContent()).getUri();
///*MediaSource mediaSource = service.getMedia((MediaContent) entry.getContent());*/
downloadFile(url, directory + attachment.getTitle().getPlainText());
}

/**
* Downloads all attachments from a Site and assumes they all have different names.
*
* @param entry The attachment (entry) to download.
* @param directory Path to a local directory to download the attach to.
* @throws ServiceException
* @throws IOException
*/
public void downloadAllAttachments(String directory) throws IOException, ServiceException {
URL contentFeedUrl = new URL(getContentFeedUrl() + "?kind=attachment");
ContentFeed contentFeed = service.getFeed(contentFeedUrl, ContentFeed.class);
for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
downloadAttachment(entry, directory);
}
}

/**
* Uploads an attachment to a selected parent page.
*
* @param file The file contents to upload.
* @param parentPage Entry of the page to upload the attachment to.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage)
throws IOException, ServiceException {
return uploadAttachment(file, parentPage.getSelfLink().getHref(), file.getName(), "");
}

/**
* Uploads an attachment to a selected parent page.
*
* @param file The file contents to upload,
* @param parentPage Entry of the page to upload the attachment to.
* @param title A title to name the attachment.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage, String title)
throws IOException, ServiceException {
return uploadAttachment(file, parentPage.getSelfLink().getHref(), title, "");
}

/**
* Uploads an attachment to a selected parent page.
*
* @param file The file contents to upload.
* @param parentPage Entry of the page to upload the attachment to.
* @param title A title to name the attachment.
* @param description A description for the file.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage,
String title, String description) throws IOException, ServiceException {
return uploadAttachment(file, parentPage.getSelfLink().getHref(), title, description);
}

/**
* Uploads an attachment to a selected parent page.
*
* @param filename Path of the file to upload.
* @param parentPage Entry of the page to upload the attachment to.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(String filename, BasePageEntry<?> parentPage)
throws IOException, ServiceException {
File file = new File(filename);
return uploadAttachment(file, parentPage.getSelfLink().getHref(), file.getName(), "");
}

/**
* Uploads an attachment to a selected parent page.
*
* @param filename Path of the file to upload.
* @param parentUrl Full self id of the parent entry to upload the attachmen to.
* @param description A file description.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(String filename, String parentUrl, String description)
throws IOException, ServiceException {
File file = new File(filename);
return uploadAttachment(file, parentUrl, file.getName(), description);
}

/**
* Uploads an attachment to a parent page using the file name for a title.
*
* @param file The file contents to upload.
* @param parentUrl Feed URL of the page to upload the attachment to.
* @return Created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, String parentUrl)
throws IOException, ServiceException {
return uploadAttachment(file, parentUrl, file.getName(), "");
}

/**
* Uploads an attachment to a parent page using the file name for a title.
*
* @param file The file contents to upload
* @param parentLink Full self id of the parent entry to upload the attach to.
* @param description A file description.
* @return The created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, String parentLink, String description)
throws IOException, ServiceException {
return uploadAttachment(file, parentLink, file.getName(), description);
}

/**
* Uploads an attachment to a parent page.
*
* @param file The file contents to upload
* @param parentLink Full self id of the parent entry to upload the attach to.
* @param title A title for the attachment.
* @param description A description for the attachment.
* @return The created attachment entry.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry uploadAttachment(File file, String parentLink, String title,
String description) throws IOException, ServiceException {
String fileMimeType = mediaTypes.getContentType(file);

AttachmentEntry newAttachment = new AttachmentEntry();
newAttachment.setMediaSource(new MediaFileSource(file, fileMimeType));
newAttachment.setTitle(new PlainTextConstruct(title));
newAttachment.setSummary(new PlainTextConstruct(description));
newAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentLink);

return service.insert(new URL(getContentFeedUrl()), newAttachment);
}

/**
* Creates a web attachment under the selected file cabinet.
*
* @param contentUrl The full URL of the hosted file.
* @param filecabinet File cabinet to create the web attachment on.
* @param title A title for the attachment.
* @param description A description for the attachment.
* @return The created web attachment.
* @throws ServiceException
* @throws IOException
* @throws MalformedURLException
*/
public WebAttachmentEntry uploadWebAttachment(String contentUrl,
FileCabinetPageEntry filecabinet, String title, String description)
throws MalformedURLException, IOException, ServiceException {
MediaContent content = new MediaContent();
content.setUri(contentUrl);

WebAttachmentEntry webAttachment = new WebAttachmentEntry();
webAttachment.setTitle(new PlainTextConstruct(title));
webAttachment.setSummary(new PlainTextConstruct(description));
webAttachment.setContent(content);
webAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM,
filecabinet.getSelfLink().getHref());

return service.insert(new URL(getContentFeedUrl()), webAttachment);
}

/**
* Updates an existing attachment with new content.
*
* @param entry Attachment entry to update.
* @param newFile The replacement file content.
* @return The created attachment.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry updateAttachment(AttachmentEntry entry, File newFile)
throws IOException, ServiceException {
return updateAttachment(entry, newFile, null, null);
}

/**
* Updates an existing attachment's metadata.
*
* @param entry Attachment entry to update.
* @param newTitle A new title for the attachment.
* @param newDescription A new description for the attachment.
* @return The created attachment.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry updateAttachment(AttachmentEntry entry, String newTitle,
String newDescription) throws IOException, ServiceException {
entry.setTitle(new PlainTextConstruct(newTitle));
entry.setSummary(new PlainTextConstruct(newDescription));

return entry.update();
}

/**
* Updates an existing attachment's metadata and content.
*
* @param entry Attachment entry to update.
* @param newFile The replacement file content.
* @param newTitle A new title for the attachment.
* @param newDescription A new description for the attachment.
* @return The created attachment.
* @throws ServiceException
* @throws IOException
*/
public AttachmentEntry updateAttachment(AttachmentEntry entry, File newFile,
String newTitle, String newDescription) throws IOException, ServiceException {
entry.setMediaSource(new MediaFileSource(newFile, mediaTypes.getContentType(newFile)));
if (newTitle != null) {
entry.setTitle(new PlainTextConstruct(newTitle));
}
if (newDescription != null) {
entry.setSummary(new PlainTextConstruct(newDescription));
}

return entry.updateMedia(true);
}

}

Thursday, September 12, 2013

Google Plus list activities - java api

List retval = new ArrayList();

Plus.Activities.List listActivities =
plusSvc.activities().list(userid, "public");

listActivities.setMaxResults(100L);

// get the 1st page of activity objects
ActivityFeed activityFeed = listActivities.execute();

// unwrap the request and extract the pieces we want
List pageOfActivities = activityFeed.getItems();

// loop through until we arrive at an empty page
while (pageOfActivities != null) {
for (Activity activity : pageOfActivities) {
retval.add(activity);
System.out.println("ID " + activity.getId() + " Content: " +
activity.getPlusObject().getContent());
}

// we will know we are on the last page when the next page token
// is null (in which case, break).
if (activityFeed.getNextPageToken() == null) {
break;
}

// prepare to request the next page of activities
listActivities.setPageToken(activityFeed.getNextPageToken());

// execute and process the next page request
activityFeed = listActivities.execute();
pageOfActivities = activityFeed.getItems();
}

Wednesday, September 4, 2013

Google OAuth Scope List

Service

Scope

Google Drive

https://www.googleapis.com/auth/drive

Google Drive Files

https://www.googleapis.com/auth/drive.file

Chrome Web store

https://www.googleapis.com/auth/chromewebstore.readonly

Google Docs

https://docs.google.com/feeds/

Google Finance

https://finance.google.com/finance/feeds/

Gmail

https://mail.google.com/mail/feed/atom

Google Health

https://www.google.com/health/feeds/

Google Spreadsheets

https://spreadsheets.google.com/feeds/

Google Tasks

https://www.googleapis.com/auth/tasks

Google URL Shortener

https://www.googleapis.com/auth/urlshortener

Google Wave

http://wave.googleusercontent.com/api/rpc

Google Webmaster Tools

https://www.google.com/webmasters/tools/feeds/

User Info (Email)

https://www.googleapis.com/auth/userinfo.email

User Info (Profile)

https://www.googleapis.com/auth/userinfo.email

Youtube

https://gdata.youtube.com

Google H9

https://www.google.com/h9/feeds/

Google Maps

https://maps.google.com/maps/feeds/

Moderator

https://www.googleapis.com/auth/moderator

Open Social

https://www-opensocial.googleusercontent.com/api/people/

Orkut Rest API

https://www.googleapis.com/auth/orkut

Orkut

https://orkut.gmodules.com/social/rest

Picassa Web

https://picasaweb.google.com/data/

Google + login

https://www.googleapis.com/auth/plus.login

Google +

https://www.googleapis.com/auth/plus.me

Side Wiki

https://www.google.com/sidewiki/feeds/

Google Sites

https://sites.google.com/feeds/

Google Analytics

https://www.google.com/analytics/feeds/

Google App state

https://www.googleapis.com/auth/appstate

Google Base

https://www.google.com/base/feeds/

Goolge Buzz

https://www.googleapis.com/auth/buzz

Google Books

https://www.google.com/books/feeds/

Blogger

https://www.blogger.com/feeds/

Google Calendar

https://www.google.com/calendar/feeds/

Google Games

https://www.googleapis.com/auth/games

Google Cloud Messaging for Android

https://android.apis.google.com/c2dm

Google Cloud Messaging for Browser

https://www.googleapis.com/auth/gcm_for_chrome

Google Contacts

https://www.google.com/m8/feeds/

Sunday, August 25, 2013

YouTube Data API - Java Code Samples

Check the documentation here


package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
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.json.GoogleJsonResponseException;
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.youtube.YouTube;
import com.google.api.services.youtube.model.Activity;
import com.google.api.services.youtube.model.ActivityContentDetails;
import com.google.api.services.youtube.model.ActivityContentDetails.Bulletin;
import com.google.api.services.youtube.model.ActivitySnippet;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.ResourceId;
import com.google.common.collect.Lists;

/**
 * Creates a video bulletin that is posted to the user's channel feed.
 *
 * @author Jeremy Walker
 */
public class ChannelBulletin {

  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  /** Global instance of YouTube object to make all API requests. */
  private static YouTube youtube;

  /*
   * Global instance of the video id we want to post as a bulletin into our channel feed. You will
   * probably pull this from a search or your app.
   */
  private static String VIDEO_ID = "L-oNKK1CrnU";

  /**
   * Authorizes the installed application to access user's protected data.
   *
   * @param scopes list of scopes needed to run upload.
   */
  private static Credential authorize(List scopes) throws Exception {

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
        JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));

    // Checks that the defaults have been replaced (Default = "Enter X here").
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
          + "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }

    // Set up file credential store.
    FileCredentialStore credentialStore = new FileCredentialStore(
        new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
        JSON_FACTORY);

    // Set up authorization code flow.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
        .build();

    // Build the local server and bind it to port 8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
  }

  /**
   * Authorizes user, runs Youtube.Channnels.List to get the default channel, and posts a bulletin
   * with a video id to the user's default channel.
   *
   * @param args command line args (not used).
   */
  public static void main(String[] args) {

    // Scope required to upload to YouTube.
    List scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
      // Authorization.
      Credential credential = authorize(scopes);

      // YouTube object used to make all API requests.
      youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
          "youtube-cmdline-channelbulletin-sample").build();

      /*
       * Now that the user is authenticated, the app makes a channel list request to get the
       * authenticated user's channel. https://developers.google.com/youtube/v3/docs/channels/list
       */
      YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
      channelRequest.setMine("true");
      /*
       * Limits the results to only the data we need making your app more efficient.
       */
      channelRequest.setFields("items/contentDetails");
      ChannelListResponse channelResult = channelRequest.execute();

      /*
       * Gets the list of channels associated with the user.
       */
      List channelsList = channelResult.getItems();

      if (channelsList != null) {
        // Gets user's default channel id (first channel in list).
        String channelId = channelsList.get(0).getId();

        /*
         * We create the snippet to set the channel we will post to and the description that goes
         * along with our bulletin.
         */
        ActivitySnippet snippet = new ActivitySnippet();
        snippet.setChannelId(channelId);
        Calendar cal = Calendar.getInstance();
        snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());

        /*
         * We set the kind of the ResourceId to video (youtube#video). Please note, you could set
         * the type to a playlist (youtube#playlist) and use a playlist id instead of a video id.
         */
        ResourceId resource = new ResourceId();
        resource.setKind("youtube#video");
        resource.setVideoId(VIDEO_ID);

        Bulletin bulletin = new Bulletin();
        bulletin.setResourceId(resource);

        // We construct the ActivityContentDetails now that we have the Bulletin.
        ActivityContentDetails contentDetails = new ActivityContentDetails();
        contentDetails.setBulletin(bulletin);

        /*
         * Finally, we construct the activity we will write to YouTube via the API. We set the
         * snippet (covers description and channel we are posting to) and the content details
         * (covers video id and type).
         */
        Activity activity = new Activity();
        activity.setSnippet(snippet);
        activity.setContentDetails(contentDetails);

        /*
         * We specify the parts (contentDetails and snippet) we will write to YouTube. Those also
         * cover the parts that are returned.
         */
        YouTube.Activities.Insert insertActivities =
            youtube.activities().insert("contentDetails,snippet", activity);
        // This returns the Activity that was added to the user's YouTube channel.
        Activity newActivityInserted = insertActivities.execute();

        if (newActivityInserted != null) {
          System.out.println(
              "New Activity inserted of type " + newActivityInserted.getSnippet().getType());
          System.out.println(" - Video id "
              + newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
          System.out.println(
              " - Description: " + newActivityInserted.getSnippet().getDescription());
          System.out.println(" - Posted on " + newActivityInserted.getSnippet().getPublishedAt());
        } else {
          System.out.println("Activity failed.");
        }

      } else {
        System.out.println("No channels are assigned to this user.");
      }
    } catch (GoogleJsonResponseException e) {
      e.printStackTrace();
      System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
          + e.getDetails().getMessage());

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
}

Wednesday, August 29, 2012

Google Plugin for Eclipse 4.1 (Juno)

Check this link for details on the Google Plugin.

For online installation refer this link

For offline installation refer this link

Install the Google plugin for Eclipse and Get started with App-engine

Wednesday, August 22, 2012

Cloud Storage

Windows Skydrive – 8 GB

Dropbox – 5 GB

Box – 5 GB

Amazon Cloud Drive – 5 GB

Ubuntu One – 5 GB

Google Drive – 5 GB

Evernote – 2 GB

Zumo Drive – 2 GB

Picassa – 1 GB

ADrive – 50 GB

DriveHQ – 1 GB

SugarSync – 5 GB

4shared – 15 GB

Zero PC – 2GB

Wednesday, May 30, 2012

Google Apps Access domain users calendars



<script language="javascript">

$(document).ready(function() {         $('#dataProcessingIFrame').attr("src","http://www.google.com/calendar/embed?src=user%40domain.com&ctz=Asia/Dubai");
  });
 function changeurl(sel) {
    var value = sel.options[sel.selectedIndex].value;
   var url = "http://www.google.com/calendar/embed?src=user%40domain.com&ctz=Asia/Dubai";
    url = url.replace("user", value);
    $('#dataProcessingIFrame').attr("src",url);
}
 function openurl(sel) {
    var value = sel.options[sel.selectedIndex].value;
   if(value != "0") {
     var url = "http://www.google.com/calendar/embed?src="+value+"%40domain.com&ctz=Asia/Dubai";
        window.open(url,'_blank','width=600,height=600');
    }
 }
</script>



<select name="users" onchange="javascript: openurl(this);"> <option selected="" value="0">Select User</option> <option value="user">user@domain.com</option></select>

Tuesday, December 27, 2011

OpenLDAP testing on Cygwin

jeetu@FVC-Jeetu /usr/local/libexec
$ ./slapd.exe
jeetu@FVC-Jeetu /usr/local/libexec
$ ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts
# extended LDIF
#
# LDAPv3
# base <> with scope baseObject
# filter: (objectclass=*)
# requesting: namingContexts
#
#
dn:
namingContexts: dc=jeetualex,dc=info
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1
jeetu@FVC-Jeetu /usr/local/libexec
$ cat > jeetu.ldiff

jeetu@FVC-Jeetu /usr/local/libexec
$ cat > jeetu.ldif
dn: dc=jeetualex,dc=info
objectclass: dcObject
objectclass: organization
o: fvc
dc: jeetualex
dn: cn=Manager,dc=jeetualex,dc=info
objectclass: organizationalRole
cn: Manager
[1]+  Stopped                 cat > jeetu.ldif
jeetu@FVC-Jeetu /usr/local/libexec
$ ls -l
total 1601
-rw-r--r-- 1 jeetu Domain Users     174 Dec 27 20:27 jeetu.ldif
-rw-r--r-- 1 jeetu Domain Users       0 Dec 27 20:27 jeetu.ldiff
-rwxr-xr-x 1 jeetu Domain Users 1578510 Dec 27 18:16 slapd.exe
jeetu@FVC-Jeetu /usr/local/libexec
$ rm jeetu.ldiff
jeetu@FVC-Jeetu /usr/local/libexec
$ ls -l
total 1601
-rw-r--r-- 1 jeetu Domain Users     174 Dec 27 20:27 jeetu.ldif
-rwxr-xr-x 1 jeetu Domain Users 1578510 Dec 27 18:16 slapd.exe
jeetu@FVC-Jeetu /usr/local/libexec
$ vi jeetu.ldif
jeetu@FVC-Jeetu /usr/local/libexec
$ ldapadd -x -D "cn=Manager,dc=jeetualex,dc=info" -W -f jeetu.ldif
Enter LDAP Password:
adding new entry "dc=jeetualex,dc=info"
adding new entry "cn=Manager,dc=jeetualex,dc=info"

jeetu@FVC-Jeetu /usr/local/libexec
$ ldapsearch -x -b 'dc=example,dc=com' '(objectclass=*)'
# extended LDIF
#
# LDAPv3
# base <dc=example,dc=com> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#
# search result
search: 2
result: 32 No such object
# numResponses: 1
jeetu@FVC-Jeetu /usr/local/libexec
$ ldapsearch -x -b 'dc=jeetualex,dc=info' '(objectclass=*)'
# extended LDIF
#
# LDAPv3
# base <dc=jeetualex,dc=info> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#
# jeetualex.info
dn: dc=jeetualex,dc=info
objectClass: dcObject
objectClass: organization
o: fvc
dc: jeetualex
# Manager, jeetualex.info
dn: cn=Manager,dc=jeetualex,dc=info
objectClass: organizationalRole
cn: Manager
# search result
search: 2
result: 0 Success
# numResponses: 3
# numEntries: 2
jeetu@FVC-Jeetu /usr/local/libexec
$