Using Google’s Data API in Brew: An Introduction

Using Google’s Data API in Brew: An Introduction

ecently, Google released its robust “Google Data API” with little fanfare. In fact, if you aren’t an avid tech blog reader or didn’t go to Google Developer Day, you might have missed it. Upon inspection, it’s clear that Google did not have the mobile developer in mind when mapping out these APIs, but that doesn’t mean you can’t make the most of the tools they’ve released. While Google has made pre-compiled libraries available for several higher order languages (from Java to Python), as Brew developers, you will have to take the hard road and use HTTP. However, since the HTTP protocol API is the least common denominator, it will work well on any system with a decent HTTP/HTTPS implementation.

In this article, you’ll learn to add basic Calendar functionality to your mobile application and how to get the XML feed for a public calendar and login through secure HTTPS. Along the way, you should get a good sense of how to use IWEB and Brew’s straightforward implementation of SSL. This article is meant as an introduction to Google’s API, not a tour de force. Stay tuned to this site as forthcoming articles will deal with J2ME development and more complicated features.

Carefully Consider Your Options
Before diving into writing some Brew code, you have a very important decision to make. Integrating your Brew application directly with Google’s web service can have some dangerous consequences. This issue is a classic conundrum in the mobile world. Do you integrate directly with a third party’s servers or do you write a server layer to bridge your Brew application and the third party service? It’s important to point out a few things to consider before coming to a final decision. First, if Google “updates” its API without support for backwards compatibility, your application will fail to interact with the service. This could have the nasty side effect of forcing you to resubmit your application to NSTL. Second, Google could remove the service entirely, forcing you to remove your app from the catalogue or disable portions of it. Recently Google removed its SOAP search API, much to the chagrin of the developers who made use of it. Fair warning: just because it’s working now doesn’t guarantee that it will continue working in the future.

The alternative has its drawbacks as well. Developing a server layer adds to your costs?which can be far more expensive than a round of NSTL submits. Additionally, you’ll have to pay for the bandwidth and CPU time for your server middleware. At the least, I’d suggest sending the traffic through a simple proxy you control, so at some later date you could modify your server to follow the changes in Google’s API.

You’ve probably had enough warnings and doom and gloom; let’s look at some code.

Retrieving a Public Feed
The first, and possibly simplest, way you’ll interact with the Google calendar API is to retrieve an XML feed for a public calendar. It’s a great place to start because it involves one (sometimes two) simple HTTP get requests and no cookies or tokens. First, make sure the calendar you want to access is public. Once that’s done, you should be able to access it through this simple function:

static void GetCalendarStream(void *pData){	GApp *pme = (GApp*)pData;	char *szPostHeader;	ISourceUtil *pUtil;	IPeek *ppeek;	ISHELL_CreateInstance(pme->a.m_pIShell, 		AEECLSID_WEB, (void **)&pme->pEventWeb);	CALLBACK_Init(&pme->clb, CalCallback, pme);	szPostHeader = MALLOC(200);	SPRINTF(szPostHeader, "Content-Type:application/atom+xml
");	IWEB_GetResponse(pme->pEventWeb,(pme->pEventWeb, &pme->pResp, &pme->clb, "http://www.google.com/calendar/feeds/[email protected]/public/full",		WEBOPT_HEADER, szPostHeader,		WEBOPT_METHOD, "GET",		WEBOPT_HANDLERDATA, pme,		WEBOPT_HEADERHANDLER, EventHeader,		WEBOPT_COPYOPTS, TRUE,		WEBOPT_END));	FREE(szPostHeader);	}

This is a fairly straightforward example of an IWEB GetResponse call. You’ll need to set the content type in the headers by hand. Google specs out the feed URL as follows:

"http://www.google.com/calendar/feeds/*email-address*/*access-level*/*feed-level*"

In the previous example, you can see that you’ve looked up a non-existent [email protected] account. This example requests only public events (hence the “public” access level) and full details on all those events. To read calendars that have not been made public, you’ll have to log in. You’ll see more on that later.

Now that you’ve requested all this data, how do you receive it? The easiest thing to do is write it to a file. Listing 1 shows you how to capture it.

Make sure the connection was successful and then, using a basic readable loop, pull the data over the network connection and write it to a file. While this process is interesting, it provides limited opportunity for getting the feeds for public calendars. In order to achieve more interesting results, such as letting users add events to their calendar or request a private feed, you’ll need to fix it so they can log into their Google Calendar account.

Logging In
Logging in is a little bit more complicated than grabbing the public feed. The process can be a multi-step endeavor requiring tokens, SSL, and eventually even cookies. Google’s documentation outlines the process for logging into a calendar account. First, you’ll need to POST to this URL:

"Email=*email_address*&Passwd=*password*&service=cl&source=Devx-Sample-Code-1" 

over HTTPS to:

https://www.google.com/accounts/ClientLogin.

Listing 2 shows the function to accomplish the post.

While it may be a review for experienced Brew developers, let’s break down Listing 2‘s code a little bit. First, you’ll need a few Brew objects. You need an SSL root cert to use https, an IWEB object to make the request, and a SourceUtil to format the post data for the IWEB object. Next, you can use CALLBACK_Init to set up your response callback function. In this example, the post data is hard coded to [email protected] and a simple password. You’ll probably want to pull this information from a text control or previously cached login info. Note the “service=cl”. This tells Google’s servers that you want the Calendar service. Google’s documentation also specifies the required content type, so you’ll have to placate them and put “Content-Type:application/x-www-form-urlencoded” in the header.

Now that you have all your data, turn the post into an ISource and post the data over IWEB. Then it’s just cleanup and return. As always, it’s important to guard resources and memory allocations to keep your application from crashing in low resource situations.

Once you’ve sent out the post, you’ll have to wait for the callback containing the authentication token. For reference, here’s the function.

static void LoginCallback(void *pData){	char *szResp;	WebRespInfo *info;	GApp *pme = (GApp *)pData;	if(info->nCode == 200 && pme->pResp)		info = IWEBRESP_GetInfo(pme->pResp);	else	{		DBGPRINTF("Web Resp Failure");		return;	}	//bla = IWEB_GetOpt(pme->pWeb, WEBOPT_HEADER, 0, &lOpt);	szResp = MALLOC(info->lContentLength+1);	ISOURCE_Read(info->pisMessage, szResp, info->lContentLength);	//szResp = (char *)lOpt.pVal;	if(bla = info->lContentLength)		pme->szToken = szResp;}

The above function should look a lot like Listing 2. Allocate a pointer to hang on to your authentication token, which should be returned to you in the body of the response. Google requires that you put the token returned on the line “Auth=” into the header of your next request as “Authorization: GoogleLogin auth=”. Now that you’ve got your login token, the rest of the information private to the account is available to you.

Go Code!
Using what you’ve covered in this inroductory, you’ve got examples for basic IWEB use, the steps necessary to grasp the XML feed for a public Calendar feed, and an example of using SSL to allow users to login to Google from within your mobile application. Perhaps you could use a public Google calendar to list upcoming events related to your application. Additionally, the process for logging into the Calendar is nearly identical to logging into other Google data services. Stay tuned to DevX for further, more advanced, examples for using Google’s powerful Data API. As Google told us on their website, and on Developer Day: “Go Code!”

devx-admin

devx-admin

Share the Post:
Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations.

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI,

Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency tokens have seen a substantial

GlobalFoundries Titan

GlobalFoundries: Semiconductor Industry Titan

GlobalFoundries, a company that might not be a household name but has managed to make enormous strides in its relatively short 14-year history. As the third-largest semiconductor foundry in the

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security in the sector remains strong.

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations. However, the United States’ stance

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are now contemplating constructing domestic manufacturing

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI, ChatGPT is known for its

Future of Cybersecurity

Cybersecurity Battles: Lapsus$ Era Unfolds

In 2023, the cybersecurity field faces significant challenges due to the continuous transformation of threats and the increasing abilities of hackers. A prime example of this is the group of

Apple's AI Future

Inside Apple’s AI Expansion Plans

Rather than following the widespread pattern of job cuts in the tech sector, Apple’s CEO Tim Cook disclosed plans to increase the company’s UK workforce. The main area of focus

AI Finance

AI Stocks to Watch

As investor interest in artificial intelligence (AI) grows, many companies are highlighting their AI product plans. However, discovering AI stocks that already generate revenue from generative AI, such as OpenAI,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its