Showing posts with label DocList. Show all posts
Showing posts with label DocList. Show all posts

Download your DocList arbitrary file uploads in .NET


The .NET client's Download() method currently handles exporting documents, presentations, and spreadsheets. However, it cannot download PDFs or arbitrary file types. Those types cannot be exported to different formats. Instead, you need to override the Download() method in docsrequest.cs to hit the content src link:

public Stream Download(Document document) {
  string queryUri = "";
  Service s = this.Service;

  string downloadUrl = document.DocumentEntry.Content.Src.ToString();
  Uri target = new Uri(downloadUrl);

  return s.Query(target);
}

Update a document's content in .NET



class Demo {
  private DocumentsService service = null;

  public Demo() {
    service = new DocumentsService("google-DocUpdateTip-v1");
    service.setUserCredentials("username@gmail.com", "pa$$word");
    GDataGAuthRequestFactory reqFactory = (GDataGAuthRequestFactory)service.RequestFactory;
    reqFactory.ProtocolMajor = 3;
  }

  static void Main(string[] args) {
    Demo demo = new Demo();

    // Fetch only documents
    DocumentsListQuery query = new DocumentsListQuery("http://docs.google.com/feeds/default/private/full/-/document");
    DocumentsFeed doclistFeed = demo.service.Query(query);

    // Update first document found
    DocumentEntry entry = (DocumentEntry)doclistFeed.Entries[0];
    Console.WriteLine("Updating " + entry.Title.Text + "...");

    DocumentEntry updatedEntry = demo.UpdateDocContents(entry, "C:/Documents and Settings/replacement.doc");
    Console.WriteLine(entry.Title.Text + " Updated!, view at " + entry.AlternateUri.ToString());
  }

  public DocumentEntry UpdateDocContents(DocumentEntry entryToUpdate, String replacementFileName) {
    FileInfo fileInfo = new FileInfo(replacementFileName);
    FileStream stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

    DocumentEntry entry = null;

    try {
      // Convert the extension to caps and strip the "." off the front
      String ext = fileInfo.Extension.ToUpper().Substring(1);

      String contentType = (String)DocumentsService.GDocumentsAllowedTypes[ext];
      if (contentType == null) {
        throw new ArgumentException("File extension '" + ext + "' is not recognized as valid.");
      }
      
      // Set ETag because we're making an update
      GDataRequestFactory factory = (GDataRequestFactory)service.RequestFactory;
      factory.CustomHeaders.Add("If-Match: " + entryToUpdate.Etag);

      Uri mediaUri = new Uri(entryToUpdate.MediaUri.ToString());
      entry = service.Update(mediaUri, stream, contentType, entryToUpdate.Title.Text) as DocumentEntry;
    } finally {
      stream.Close();
    }

    return entry;
  }
}


Create a new Google Docs Spreadsheet from content using AJAX


This example shows how one could use jQuery to make an AJAX request that creates new Google Docs Spreadsheet from existing text/csv content. This particular examples uses ClientLogin
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"
        type="text/javascript"></script>

<script type="text/javascript">
var token = 'YOUR_CLIENTLOGIN_AUTH_TOKEN';

function constructContentBody(docTitle, docType, contentBody, contentType) {
  var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
              '<entry xmlns="http://www.w3.org/2005/Atom">',
              '<category scheme="http://schemas.google.com/g/2005#kind"',
              ' term="http://schemas.google.com/docs/2007#', docType, '"/>',
              '<title>', docTitle, '</title>',
              '</entry>'].join('');
             
  var body = ['--END_OF_PART\r\n',
              'Content-Type: application/atom+xml;\r\n\r\n',
              atom, '\r\n',
              '--END_OF_PART\r\n',
              'Content-Type: ', contentType, '\r\n\r\n',
              contentBody, '\r\n',
              '--END_OF_PART--\r\n'].join('');
  return body;
}

function createSpreadsheetFromContent(title, content, contentType) {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

  $.ajax({
    type: 'POST',
    url: 'http://docs.google.com/feeds/documents/private/full',
    contentType: 'multipart/related; boundary=END_OF_PART',
    data: constructContentBody(title, 'spreadsheet', content, contentType),
    dataType: 'xml',
    beforeSend: function(xhr) {
      $('#data').html('uploading...');
      xhr.setRequestHeader('Authorization', 'GoogleLogin auth=' + token);
    },
    success: function(resp) {
      $('#data').html('Spreadsheet created!');
    }
  });
}
</script>
</head>
<body>

<div id="data"></div>

<button onclick="createSpreadsheetFromContent('ANewTitle', '1,2,3,4', 'text/csv')">Create spreadsheet w/ content</button>
</body>
</html>

Download a Google Doc using the PHP library


At the time of writing this tip, the Zend_Gdata_Docs component of the PHP library does not contain the export/download functionality of the DocList API. Here is an example of using AuthSub and file_get_contents() to download a document as a .txt file:

function download($client, $url, $format=null) {
  $sessionToken = $client->getHttpClient()->getAuthSubToken();
  $opts = array(
    'http' => array(
      'method' => 'GET',
      'header' => "GData-Version: 3.0\r\n".
                  "Authorization: AuthSub token=\"$sessionToken\"\r\n"
    )
  );
  if ($url != null) {
    $url =  $url . "&exportFormat=$format";
  }
  return file_get_contents($url, false, stream_context_create($opts));
}

// TODO 1: setup a Zend_Gdata_Docs client in $docs_client
// TODO 2: fetch a $feed or $entry
$contentLink = $feed->entries[0]->content->getSrc();
$fileContents = download($docs_client, $contentLink, 'txt');
echo 'Contents of document "' . $feed->entries[0]->title . '":<hr>';
echo "<pre>$fileContents</pre>";

OAuth in Google App Engine


This sample demonstrates a basic structure that you can use to perform 3-legged OAuth using the Google Data Python client library in Google App Engine. This particular example talks to the Documents List Data API.

App Engine (Python) + OAuth sample

Note: The sample is available in two versions, one that signs requests with RSA-SHA1 and another that signs with HMAC-SHA1.

Retrieving a document's content URL in Java


If you have a published document, its contents can be viewed by fetching the DocumentListEntry object's <content> src URL:
List<DocumentListEntry> entries = resultFeed.getEntries();
for (DocumentListEntry entry : entries) {
  MediaContent content = (MediaContent)entry.getContent();
  System.out.println("View '" + entry.getTitle().getPlainText() + "' at " + content.getUri());        
}

Using the JavaScript Client Library w/ non-supported Services


The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API.
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('gdata', '1.x');
google.setOnLoadCallback(initialize);

function initialize() {
  var scope = 'http://docs.google.com/feeds/';
  if (google.accounts.user.checkLogin(scope)) {   
    var service = new google.gdata.client.GoogleService('writely', 'DocList-App-v1.0'); 
    service.getFeed(scope + 'documents/private/full/', handleFeed, handleError);
  } else {
    var token = google.accounts.user.login(scope); // can ignore returned token
  }
};

var handleFeed = function(response) {
  var entries = response.feed.entry;
  if (!entries.length) {
    alert('You have no entries!');
    return;
  }
  var html = [];
  for (var i = 0, entry; entry = entries[i]; i++) {
    var title = entry.title.$t;
    html.push('<li>' + title + '</li>');
  }
  document.getElementById('data').innerHTML = html.join('');
};

var handleError = function(e) {
  alert('Error: ' + e.cause ? e.cause.statusText : e.message);
};
</script>

<div id="data"><!-- dynamically filled --></div>

Accessing a feed using ClientLogin & Ruby


Example of accessing the DocList API using ClientLogin in Ruby:
require 'net/http'
require 'net/https'
require 'cgi'
require 'rubygems'
require 'xmlsimple'
require 'pp'

def get_feed(uri, headers=nil)
  uri = URI.parse(uri)
  Net::HTTP.start(uri.host, uri.port) do |http|
    return http.get(uri.path, headers)
  end
end

email = 'user@gmail.com'
password = CGI::escape('pa$$word')
service = 'writely'
source = 'MyCompany-MyApp-0.1'
path = '/accounts/ClientLogin'

data = ["accountType=HOSTED_OR_GOOGLE", 
        "Email=#{email}",
        "Passwd=#{password}",
        "service=#{service}",
        "source=#{source}"].join('&')

http = Net::HTTP.new(host='www.google.com', port=443)
http.use_ssl = true
http.start

headers = {'Content-Type' => 'application/x-www-form-urlencoded'}
resp, data = http.post(path, data, headers)

token = data[/Auth=(.*)/, 1]  # parse out the Auth token

headers['Authorization'] = "GoogleLogin auth=#{token}"
resp = get_feed('http://docs.google.com/feeds/documents/private/full', headers)

doc = XmlSimple.xml_in(resp.body, 'KeyAttr' => 'name')
pp doc

Using the PHP Client Library through a Proxy connection


To access a Google Data API through a proxy connection you will need to use the Zend_Http_Client_Adapter_Proxy proxy adapter. In the snippet below, we are going to access our private Google Documents feed from the DocumentsList API through a proxy connection:
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_App_HttpException');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Docs');

Zend_Loader::loadClass('Zend_Http_Client_Exception');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Http_Client_Adapter_Proxy');


// Configure the proxy connection
$config = array(
    'adapter'    => 'Zend_Http_Client_Adapter_Proxy',
    'proxy_host' => 'your.proxy.server.net',
    'proxy_port' => 3128
);

// We are setting http://www.google.com:443 as the initial URL since we need to perform
// ClientLogin authentication first.
$proxiedHttpClient = new Zend_Http_Client('http://www.google.com:443', $config);

$username = 'foo@example.com';
$password = 'barbaz';
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;

// Try to perform the ClientLogin authentication using our proxy client.
// If there is an error, we exit since it doesn't make sense to go on. You may want to 
// modify this according to the needs of your application.
try {
  $httpClient = Zend_Gdata_ClientLogin::getHttpClient($username, $password, $service,
    $proxiedHttpClient);
} catch (Zend_Gdata_App_HttpException $httpException) {
  exit("An error occurred trying to connect to the proxy server\n" .        
    $httpException->getMessage() . "\n");
}

// If that worked, proceed and retrieve the documents feed.
// Remember to set your application ID.
$docsClient = new Zend_Gdata_Docs($httpClient, $yourApplicationId);
$feed = $docsClient->getDocumentListFeed();

?>

Retrieving a single document entry using the Java client library


The snippet below demonstrates how to retrieve a single DocumentListEntry using the Java client library:
import java.net.URL;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.docs.DocumentListEntry;

public class DocumentListGetEntry {

  public static void main(String[] args) {
    try {
      DocsService docsService = new DocsService("Document List Demo");
      docsService.setUserCredentials("foobar@example.com", "secret");
   
      URL documentURI = new URL("http://docs.google.com/feeds/documents/private/full/spreadsheet%3Apc6ppXdYxYkSSOvE8tCUELw");
      DocumentListEntry entry = docsService.getEntry(documentURI, DocumentListEntry.class);
   
      System.out.println(entry.getTitle().getPlainText());  
  
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
}

Save A Google Docs Document As A File In .NET


Given a DocumentEntry, save to local file "C:\example.html"
Uri documentUri = new Uri(entry.Content.AbsoluteUri);
Stream stream = service.Query(documentUri);
StreamReader streamReader = new StreamReader(stream);
StreamWriter streamWriter = new StreamWriter("C:\\example.html");
string line = "";
while( (line = streamReader.ReadLine()) != null) {
    streamWriter.WriteLine(line);
}
streamReader.Close();
streamWriter.Close();