updating analytics sample to migrate auth to new client lib flows
reviewed here: https://codereview.appspot.com/9749044/
diff --git a/samples/analytics/README b/samples/analytics/README
index 8b3860a..4e422dd 100644
--- a/samples/analytics/README
+++ b/samples/analytics/README
@@ -1,4 +1,4 @@
-Command-line samples for producting reports with the Analytics API.
+Command-line samples for producing reports with the Analytics API.
 
 api: analytics
 keywords: cmdline
diff --git a/samples/analytics/core_reporting_v3_reference.py b/samples/analytics/core_reporting_v3_reference.py
index 6132263..71d7da2 100755
--- a/samples/analytics/core_reporting_v3_reference.py
+++ b/samples/analytics/core_reporting_v3_reference.py
@@ -33,7 +33,7 @@
   applications: https://code.google.com/apis/console
 
   Learn more about registering your analytics application here:
-  http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
+  http://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization
 
 Supply your TABLE_ID
 
@@ -45,7 +45,11 @@
 
 Sample Usage:
 
-  $ python core_reporting_v3_reference.py
+  $ python core_reporting_v3_reference.py ga:xxxx
+
+Where the table ID is used to identify from which Google Anlaytics profile
+to retrieve data. This ID is in the format ga:xxxx where xxxx is the
+profile ID.
 
 Also you can also get help on all the command-line flags the program
 understands by running:
@@ -55,28 +59,29 @@
 
 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
 
+import argparse
 import sys
-import sample_utils
 
 from apiclient.errors import HttpError
+from apiclient import sample_tools
 from oauth2client.client import AccessTokenRefreshError
 
-
-# The table ID is used to identify from which Google Anlaytics profile
-# to retrieve data. This ID is in the format ga:xxxx where xxxx is the
-# profile ID.
-TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE'
+# Declare command-line flags.
+argparser = argparse.ArgumentParser(add_help=False)
+argparser.add_argument('table_id', type=str,
+                     help=('The table ID of the profile you wish to access. '
+                           'Format is ga:xxx where xxx is your profile ID.'))
 
 
 def main(argv):
-  sample_utils.process_flags(argv)
-
   # Authenticate and construct service.
-  service = sample_utils.initialize_service()
+  service, flags = sample_tools.init(
+      argv, 'analytics', 'v3', __doc__, __file__, parents=[argparser],
+      scope='https://www.googleapis.com/auth/analytics.readonly')
 
   # Try to make a request to the API. Print the results or handle errors.
   try:
-    results = get_api_query(service).execute()
+    results = get_api_query(service, flags.table_id).execute()
     print_results(results)
 
   except TypeError, error:
@@ -94,15 +99,16 @@
            'the application to re-authorize')
 
 
-def get_api_query(service):
+def get_api_query(service, table_id):
   """Returns a query object to retrieve data from the Core Reporting API.
 
   Args:
     service: The service object built by the Google API Python client library.
+    table_id: str The table ID form which to retrieve data.
   """
 
   return service.data().ga().get(
-      ids=TABLE_ID,
+      ids=table_id,
       start_date='2012-01-01',
       end_date='2012-01-15',
       metrics='ga:visits',
diff --git a/samples/analytics/hello_analytics_api_v3.py b/samples/analytics/hello_analytics_api_v3.py
index 271c213..915e7f8 100755
--- a/samples/analytics/hello_analytics_api_v3.py
+++ b/samples/analytics/hello_analytics_api_v3.py
@@ -43,18 +43,19 @@
 
 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
 
+import argparse
 import sys
-import sample_utils
 
 from apiclient.errors import HttpError
+from apiclient import sample_tools
 from oauth2client.client import AccessTokenRefreshError
 
 
 def main(argv):
-  sample_utils.process_flags(argv)
-
   # Authenticate and construct service.
-  service = sample_utils.initialize_service()
+  service, flags = sample_tools.init(
+      argv, 'analytics', 'v3', __doc__, __file__,
+      scope='https://www.googleapis.com/auth/analytics.readonly')
 
   # Try to make a request to the API. Print the results or handle errors.
   try:
diff --git a/samples/analytics/management_v3_reference.py b/samples/analytics/management_v3_reference.py
index 2d73445..10ecd23 100755
--- a/samples/analytics/management_v3_reference.py
+++ b/samples/analytics/management_v3_reference.py
@@ -28,9 +28,6 @@
 all the goals for the first profile. The sample then prints all the
 user's advanced segments.
 
-To read an indepth discussion on how this file works, check out the Management
-API Python Getting Started guide here:
-http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html
 
 Before You Begin:
 
@@ -42,7 +39,7 @@
   applications: https://code.google.com/apis/console
 
   Learn more about registering your analytics application here:
-  http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
+  https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
 
 Sample Usage:
 
@@ -56,18 +53,19 @@
 
 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
 
+import argparse
 import sys
-import sample_utils
 
 from apiclient.errors import HttpError
+from apiclient import sample_tools
 from oauth2client.client import AccessTokenRefreshError
 
 
 def main(argv):
-  sample_utils.process_flags(argv)
-
   # Authenticate and construct service.
-  service = sample_utils.initialize_service()
+  service, flags = sample_tools.init(
+      argv, 'analytics', 'v3', __doc__, __file__,
+      scope='https://www.googleapis.com/auth/analytics.readonly')
 
   # Traverse the Management hiearchy and print results or handle errors.
   try:
@@ -157,7 +155,8 @@
     print 'Child link href = %s' % child_link.get('href')
     print 'Child link type = %s' % child_link.get('type')
     print
-  else:
+
+  if not accounts_response.get('items'):
     print 'No accounts found.\n'
 
 
@@ -192,7 +191,8 @@
     print 'Child link href    = %s' % child_link.get('href')
     print 'Child link type    = %s' % child_link.get('type')
     print
-  else:
+
+  if not webproperties_response.get('items'):
     print 'No webproperties found.\n'
 
 
@@ -239,7 +239,8 @@
     print 'Child link href  = %s' % child_link.get('href')
     print 'Child link type  = %s' % child_link.get('type')
     print
-  else:
+
+  if not profiles_response.get('items'):
     print 'No profiles found.\n'
 
 
@@ -295,7 +296,8 @@
       print_event_goal_details(goal.get('eventDetails'))
 
     print
-  else:
+
+  if not goals_response.get('items'):
     print 'No goals found.\n'
 
 
@@ -317,7 +319,8 @@
     print 'Step Number  = %s' % goal_step.get('number')
     print 'Step Name    = %s' % goal_step.get('name')
     print 'Step URL     = %s' % goal_step.get('url')
-  else:
+
+  if not goal_details.get('steps'):
     print 'No Steps Configured'
 
 
diff --git a/samples/analytics/sample_utils.py b/samples/analytics/sample_utils.py
deleted file mode 100644
index 10aa12c..0000000
--- a/samples/analytics/sample_utils.py
+++ /dev/null
@@ -1,133 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2012 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Utilities for Analytics API code samples.
-
-Handles various tasks to do with logging, authentication and initialization.
-Mostly taken from Sergio :)
-
-Before You Begin:
-
-You must update the client_secrets.json file with a client id, client secret,
-and the redirect uri. You get these values by creating a new project
-in the Google APIs console and registering for OAuth2.0 for installed
-applications: https://code.google.com/apis/console
-
-Also all OAuth2.0 tokens are stored for resue in the file specified
-as TOKEN_FILE_NAME. You can modify this file name if you wish.
-"""
-
-__author__ = ('sergio.gomes@google.com (Sergio Gomes)'
-              'api.nickm@gmail.com (Nick Mihailovski)')
-
-import logging
-import os
-import sys
-from apiclient.discovery import build
-import gflags
-import httplib2
-from oauth2client.client import flow_from_clientsecrets
-from oauth2client.client import OOB_CALLBACK_URN
-from oauth2client.file import Storage
-from oauth2client.tools import run
-
-
-FLAGS = gflags.FLAGS
-
-# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
-# application, including client_id and client_secret. You get these values by
-# creating a new project in the Google APIs console and registering for
-# OAuth2.0 for installed applications: <https://code.google.com/apis/console>
-CLIENT_SECRETS = 'client_secrets.json'
-
-
-# Helpful message to display in the browser if the CLIENT_SECRETS file
-# is missing.
-MISSING_CLIENT_SECRETS_MESSAGE = """
-WARNING: Please configure OAuth 2.0
-
-To make this sample run you will need to populate the client_secrets.json file
-found at:
-
-   %s
-
-with information from the APIs Console <https://code.google.com/apis/console>.
-
-""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
-
-# Set up a Flow object to be used if we need to authenticate.
-FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
-    scope='https://www.googleapis.com/auth/analytics.readonly',
-    redirect_uri=OOB_CALLBACK_URN,
-    message=MISSING_CLIENT_SECRETS_MESSAGE)
-
-# The gflags module makes defining command-line options easy for applications.
-# Run this program with the '--help' argument to see all the flags that it
-# understands.
-gflags.DEFINE_enum('logging_level', 'ERROR',
-                   ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
-                   'Set the level of logging detail.')
-
-
-# Name of file that will store the access and refresh tokens to access
-# the API without having to login each time. Make sure this file is in
-# a secure place.
-TOKEN_FILE_NAME = 'analytics.dat'
-
-
-def process_flags(argv):
-  """Uses the command-line flags to set the logging level.
-
-  Args:
-    argv: List of command line arguments passed to the python script.
-  """
-
-  # Let the gflags module process the command-line arguments.
-  try:
-    argv = FLAGS(argv)
-  except gflags.FlagsError, e:
-    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
-    sys.exit(1)
-
-  # Set the logging according to the command-line flag.
-  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
-
-
-def initialize_service():
-  """Returns an instance of service from discovery data and does auth.
-
-  This method tries to read any existing OAuth 2.0 credentials from the
-  Storage object. If the credentials do not exist, new credentials are
-  obtained. The crdentials are used to authorize an http object. The
-  http object is used to build the analytics service object.
-
-  Returns:
-    An analytics v3 service object.
-  """
-
-  # Create an httplib2.Http object to handle our HTTP requests.
-  http = httplib2.Http()
-
-  # Prepare credentials, and authorize HTTP object with them.
-  storage = Storage(TOKEN_FILE_NAME)
-  credentials = storage.get()
-  if credentials is None or credentials.invalid:
-    credentials = run(FLOW, storage)
-
-  http = credentials.authorize(http)
-
-  # Retrieve service.
-  return build('analytics', 'v3', http=http)