code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude; import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl; import com.google.api.client.auth.oauth.OAuthCredentialsResponse; import com.google.api.client.auth.oauth.OAuthHmacSigner; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken; import com.google.api.client.sample.latitude.model.ClientCredentials; import com.google.api.client.sample.latitude.model.Util; import com.google.common.base.Preconditions; import java.awt.Desktop; import java.awt.Desktop.Action; import java.net.URI; /** * Implements OAuth authentication. * * @author Yaniv Inbar */ public class Auth { private static final String APP_NAME = "Google Latitude API Java Client"; private static OAuthHmacSigner signer; private static OAuthCredentialsResponse credentials; /** * For details regarding authentication and authorization for Google Latitude, see <a * href="http://code.google.com/apis/latitude/v1/using_rest.html#auth">Authentication and * authorization</a>. */ static void authorize() throws Exception { // callback server LoginCallbackServer callbackServer = null; String verifier = null; String tempToken = null; try { callbackServer = new LoginCallbackServer(); callbackServer.start(); // temporary token GoogleOAuthGetTemporaryToken temporaryToken = new GoogleOAuthGetTemporaryToken(); signer = new OAuthHmacSigner(); signer.clientSharedSecret = Preconditions.checkNotNull(ClientCredentials.ENTER_OAUTH_CONSUMER_SECRET); temporaryToken.transport = Util.AUTH_TRANSPORT; temporaryToken.signer = signer; temporaryToken.consumerKey = Preconditions.checkNotNull(ClientCredentials.ENTER_OAUTH_CONSUMER_KEY); temporaryToken.scope = "https://www.googleapis.com/auth/latitude"; temporaryToken.displayName = APP_NAME; temporaryToken.callback = callbackServer.getCallbackUrl(); OAuthCredentialsResponse tempCredentials = temporaryToken.execute(); signer.tokenSharedSecret = tempCredentials.tokenSecret; // authorization URL -- see // http://code.google.com/apis/latitude/v1/using_rest.html#auth OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl( "https://www.google.com/latitude/apps/OAuthAuthorizeToken"); // (required) The domain used to identify your application. authorizeUrl.put("domain", ClientCredentials.ENTER_OAUTH_CONSUMER_KEY); // (optional) The range of locations you want to access. Can be either // current or all. If this parameter is omitted, current is assumed. authorizeUrl.put("location", "all"); // (optional) The finest granularity of locations you want to access. Can // be either city or best. If this parameter is omitted, city is assumed. authorizeUrl.put("granularity", "best"); authorizeUrl.temporaryToken = tempToken = tempCredentials.token; String authorizationUrl = authorizeUrl.build(); // launch in browser boolean browsed = false; if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { desktop.browse(URI.create(authorizationUrl)); browsed = true; } } if (!browsed) { String browser = "google-chrome"; Runtime.getRuntime().exec(new String[] {browser, authorizationUrl}); } verifier = callbackServer.waitForVerifier(tempToken); } finally { if (callbackServer != null) { callbackServer.stop(); } } GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken(); accessToken.transport = Util.AUTH_TRANSPORT; accessToken.temporaryToken = tempToken; accessToken.signer = signer; accessToken.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; accessToken.verifier = verifier; credentials = accessToken.execute(); signer.tokenSharedSecret = credentials.tokenSecret; createOAuthParameters().signRequestsUsingAuthorizationHeader(Util.TRANSPORT); } static void revoke() { if (credentials != null) { try { GoogleOAuthGetAccessToken.revokeAccessToken(Util.AUTH_TRANSPORT, createOAuthParameters()); } catch (Exception e) { e.printStackTrace(System.err); } } } private static OAuthParameters createOAuthParameters() { OAuthParameters authorizer = new OAuthParameters(); authorizer.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; authorizer.signer = signer; authorizer.token = credentials.token; return authorizer; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude; import com.google.api.client.http.HttpResponseException; import com.google.api.client.sample.latitude.model.LocationResource; import com.google.api.client.sample.latitude.model.Util; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class LatitudeSample { public static void main(String[] args) { Util.enableLogging(); try { try { Auth.authorize(); showCurrentLocation(); showLocationHistory(); Auth.revoke(); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); Auth.revoke(); System.exit(1); } } private static void showCurrentLocation() throws IOException { System.out.println("Current location:"); LocationResource current = LocationResource.executeGetCurrentLocation(); System.out.println(Util.JSON_FACTORY.toString(current)); } private static void showLocationHistory() throws IOException { System.out.println(); System.out.println("Location History:"); List<LocationResource> locations = LocationResource.executeList(); for (LocationResource location : locations) { System.out.println(Util.JSON_FACTORY.toString(location)); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude.model; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.googleapis.json.JsonCParser; 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.jackson.JacksonFactory; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Yaniv Inbar */ public class Util { public static final boolean DEBUG = false; public static final JsonFactory JSON_FACTORY = new JacksonFactory(); public static final HttpTransport TRANSPORT = newTransport(false); public static final HttpTransport AUTH_TRANSPORT = newTransport(true); static HttpTransport newTransport(boolean forAuth) { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("Google-LatitudeSample/1.0"); result.defaultHeaders = headers; if (!forAuth) { JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; result.addParser(parser); } return result; } public static void enableLogging() { if (DEBUG) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude.model; import com.google.api.client.util.Key; import java.util.ArrayList; import java.util.List; /** * @author Yaniv Inbar */ public class LocationList { @Key public List<LocationResource> items = new ArrayList<LocationResource>(); }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * Latitude URL builder. * * @author Yaniv Inbar */ public final class LatitudeUrl extends GoogleUrl { @Key public String granularity; @Key("min-time") public String minTime; @Key("max-time") public String maxTime; @Key("max-results") public String maxResults; /** Constructs a new Latitude URL from the given encoded URI. */ public LatitudeUrl(String encodedUrl) { super(encodedUrl); if (Util.DEBUG) { prettyprint = true; } // API Key if (ClientCredentials.ENTER_KEY != null) { key = ClientCredentials.ENTER_KEY; } } private static LatitudeUrl root() { return new LatitudeUrl("https://www.googleapis.com/latitude/v1"); } public static LatitudeUrl forCurrentLocation() { LatitudeUrl result = root(); result.pathParts.add("currentLocation"); return result; } public static LatitudeUrl forLocation() { LatitudeUrl result = root(); result.pathParts.add("location"); return result; } public static LatitudeUrl forLocation(Long timestampMs) { LatitudeUrl result = forLocation(); result.pathParts.add(timestampMs.toString()); return result; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude.model; import com.google.api.client.googleapis.json.JsonCContent; import com.google.api.client.http.HttpRequest; import com.google.api.client.util.Key; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class LocationResource { @Key public Long timestampMs; @Key public Float latitude; @Key public Float longitude; @Key public Integer accuracy; @Key public Integer speed; @Key public Integer heading; @Key public Integer altitude; @Key public Integer altitudeAccuracy; @Key public String placeid; public static List<LocationResource> executeList() throws IOException { HttpRequest request = Util.TRANSPORT.buildGetRequest(); request.url = LatitudeUrl.forLocation(); return request.execute().parseAs(LocationList.class).items; } public static LocationResource executeGet(Long timestampMs) throws IOException { HttpRequest request = Util.TRANSPORT.buildGetRequest(); request.url = LatitudeUrl.forLocation(timestampMs); return request.execute().parseAs(LocationResource.class); } public LocationResource executeInsert() throws IOException { HttpRequest request = Util.TRANSPORT.buildPostRequest(); request.content = toContent(); request.url = LatitudeUrl.forLocation(); return request.execute().parseAs(LocationResource.class); } public static LocationResource executeGetCurrentLocation() throws IOException { HttpRequest request = Util.TRANSPORT.buildGetRequest(); request.url = LatitudeUrl.forCurrentLocation(); return request.execute().parseAs(LocationResource.class); } public LocationResource executeUpdateCurrent() throws IOException { HttpRequest request = Util.TRANSPORT.buildPutRequest(); request.content = toContent(); request.url = LatitudeUrl.forCurrentLocation(); return request.execute().parseAs(LocationResource.class); } public static void executeDelete(Long timestampMs) throws IOException { HttpRequest request = Util.TRANSPORT.buildDeleteRequest(); request.url = LatitudeUrl.forLocation(timestampMs); request.execute().ignore(); } public static void executeDeleteCurrent() throws IOException { HttpRequest request = Util.TRANSPORT.buildDeleteRequest(); request.url = LatitudeUrl.forCurrentLocation(); request.execute().ignore(); } JsonCContent toContent() { JsonCContent content = new JsonCContent(); content.jsonFactory = Util.JSON_FACTORY; content.data = this; return content; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.latitude.model; /** * @author Yaniv Inbar */ public class ClientCredentials { /** * OAuth Consumer Key obtained from the <a * href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page. */ public static final String ENTER_OAUTH_CONSUMER_KEY = null; /** * OAuth Consumer Secret obtained from the <a * href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page. */ public static final String ENTER_OAUTH_CONSUMER_SECRET = null; /** * API key obtained from the <a href="https://code.google.com/apis/console">Google APIs * console</a> or {@code null} for none. */ public static final String ENTER_KEY = null; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3; import com.google.api.client.repackaged.com.google.common.base.Preconditions; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Class that runs a Jetty server on a free port, waiting for OAuth to redirect * to it with the one-time authorization token. * <p> * Mostly copied from oacurl by phopkins@google.com. * * @author Yaniv Inbar */ public class LoginCallbackServer { private static final String CALLBACK_PATH = "/OAuthCallback"; private int port; private Server server; private Map<String, String> verifierMap = new HashMap<String, String>(); public void start() { if (server != null) { throw new IllegalStateException("Server is already started"); } try { port = getUnusedPort(); server = new Server(port); for (Connector c : server.getConnectors()) { c.setHost("localhost"); } server.addHandler(new CallbackHandler()); server.start(); } catch (Exception e) { throw new RuntimeException(e); } } public void stop() throws Exception { if (server != null) { server.stop(); server = null; } } public String getCallbackUrl() { Preconditions.checkArgument(port != 0, "Server is not yet started"); return "http://localhost:" + port + CALLBACK_PATH; } private static int getUnusedPort() throws IOException { Socket s = new Socket(); s.bind(null); try { return s.getLocalPort(); } finally { s.close(); } } /** * Call that blocks until the OAuth provider redirects back here with the * verifier token. * * @param requestToken request token * @return The verifier token, or null if there was a timeout. */ public String waitForVerifier(String requestToken) { synchronized (verifierMap) { while (!verifierMap.containsKey(requestToken)) { try { verifierMap.wait(3000); } catch (InterruptedException e) { return null; } } return verifierMap.remove(requestToken); } } /** * Jetty handler that takes the verifier token passed over from the OAuth * provider and stashes it where {@link LoginCallbackServer#waitForVerifier} * will find it. */ public class CallbackHandler extends AbstractHandler { public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException { if (!CALLBACK_PATH.equals(target)) { return; } writeLandingHtml(response); response.flushBuffer(); ((Request) request).setHandled(true); String requestToken = request.getParameter("oauth_token"); String verifier = request.getParameter("oauth_verifier"); synchronized (verifierMap) { verifierMap.put(requestToken, verifier); verifierMap.notifyAll(); } } private void writeLandingHtml(HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); PrintWriter doc = response.getWriter(); doc.println("<html>"); doc.println( "<head><title>OAuth Authentication Token Recieved</title></head>"); doc.println("<body>"); doc.println("Received verifier token. Closing..."); doc.println("<script type='text/javascript'>"); // We open "" in the same window to trigger JS ownership of it, which lets // us then close it via JS, at least in Chrome. doc.println("window.setTimeout(function() {"); doc.println( " window.open('', '_self', ''); window.close(); }, 1000);"); doc.println("if (window.opener) { window.opener.checkToken(); }"); doc.println("</script>"); doc.println("</body>"); doc.println("</HTML>"); doc.flush(); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.sample.docs.v3.model.Debug; import com.google.api.client.sample.docs.v3.model.DocsUrl; import com.google.api.client.sample.docs.v3.model.DocumentListEntry; import com.google.api.client.sample.docs.v3.model.DocumentListFeed; import com.google.api.client.sample.docs.v3.model.Namespace; import com.google.api.client.xml.atom.AtomParser; import java.io.IOException; /** * @author Yaniv Inbar */ public class DocsSample { private final HttpTransport transport; public DocsSample(HttpTransport transport) { super(); this.transport = transport; } public static void main(String[] args) { Debug.enableLogging(); try { try { HttpTransport transport = setUpTransport(); DocsSample sample = new DocsSample(transport); sample.authorize(); sample.showDocs(); Auth.revoke(); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); Auth.revoke(); System.exit(1); } } private static HttpTransport setUpTransport() { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Google-DocsSample/1.0"); headers.gdataVersion = "3"; AtomParser parser = new AtomParser(); parser.namespaceDictionary = Namespace.DICTIONARY; transport.addParser(parser); return transport; } private void showDocs() throws IOException { header("Show Documents List"); DocumentListFeed feed = DocumentListFeed.executeGet(transport, DocsUrl.forDefaultPrivateFull()); display(feed); } private void authorize() throws Exception { Auth.authorize(transport); } private static void header(String name) { System.out.println(); System.out.println("============== " + name + " =============="); System.out.println(); } private void display(DocumentListFeed feed) { for (DocumentListEntry doc : feed.docs) { display(doc); } } private void display(DocumentListEntry entry) { System.out.println(entry.title); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3; import com.google.api.client.auth.oauth.OAuthCredentialsResponse; import com.google.api.client.auth.oauth.OAuthHmacSigner; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken; import com.google.api.client.http.HttpTransport; import com.google.api.client.sample.docs.v3.model.DocsUrl; import java.awt.Desktop; import java.awt.Desktop.Action; import java.net.URI; /** * Implements OAuth authentication. * * @author Yaniv Inbar */ public class Auth { private static final String APP_NAME = "Google Documents List Data API Java Client Sample"; private static OAuthHmacSigner signer; private static OAuthCredentialsResponse credentials; static void authorize(HttpTransport transport) throws Exception { // callback server LoginCallbackServer callbackServer = null; String verifier = null; String tempToken = null; try { callbackServer = new LoginCallbackServer(); callbackServer.start(); // temporary token GoogleOAuthGetTemporaryToken temporaryToken = new GoogleOAuthGetTemporaryToken(); signer = new OAuthHmacSigner(); signer.clientSharedSecret = "anonymous"; temporaryToken.signer = signer; temporaryToken.consumerKey = "anonymous"; temporaryToken.scope = DocsUrl.ROOT_URL; temporaryToken.displayName = APP_NAME; temporaryToken.callback = callbackServer.getCallbackUrl(); OAuthCredentialsResponse tempCredentials = temporaryToken.execute(); signer.tokenSharedSecret = tempCredentials.tokenSecret; // authorization URL GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl = new GoogleOAuthAuthorizeTemporaryTokenUrl(); authorizeUrl.temporaryToken = tempToken = tempCredentials.token; String authorizationUrl = authorizeUrl.build(); // launch in browser boolean browsed = false; if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { desktop.browse(URI.create(authorizationUrl)); browsed = true; } } if (!browsed) { String browser = "google-chrome"; Runtime.getRuntime().exec(new String[] {browser, authorizationUrl}); } verifier = callbackServer.waitForVerifier(tempToken); } finally { if (callbackServer != null) { callbackServer.stop(); } } GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken(); accessToken.temporaryToken = tempToken; accessToken.signer = signer; accessToken.consumerKey = "anonymous"; accessToken.verifier = verifier; credentials = accessToken.execute(); signer.tokenSharedSecret = credentials.tokenSecret; createOAuthParameters().signRequestsUsingAuthorizationHeader(transport); } static void revoke() { if (credentials != null) { try { GoogleOAuthGetAccessToken.revokeAccessToken(createOAuthParameters()); } catch (Exception e) { e.printStackTrace(System.err); } } } private static OAuthParameters createOAuthParameters() { OAuthParameters authorizer = new OAuthParameters(); authorizer.consumerKey = "anonymous"; authorizer.signer = signer; authorizer.token = credentials.token; return authorizer; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.xml.XmlNamespaceDictionary; import java.util.Map; /** * @author Yaniv Inbar */ public class Namespace { public static final XmlNamespaceDictionary DICTIONARY = new XmlNamespaceDictionary(); static { Map<String, String> map = DICTIONARY.namespaceAliasToUriMap; map.put("", "http://www.w3.org/2005/Atom"); map.put("app", "http://www.w3.org/2007/app"); map.put("atom", "http://www.w3.org/2005/Atom"); map.put("batch", "http://schemas.google.com/gdata/batch"); map.put("docs", "http://schemas.google.com/docs/2007"); map.put("gAcl", "http://schemas.google.com/acl/2007"); map.put("gd", "http://schemas.google.com/g/2005"); map.put("openSearch", "http://a9.com/-/spec/opensearch/1.1/"); map.put("xml", "http://www.w3.org/XML/1998/namespace"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Link { @Key("@href") public String href; @Key("@rel") public String rel; public static String find(List<Link> links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Key; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class Feed { @Key("openSearch:totalResults") public int totalResults; @Key("link") public List<Link> links; static Feed executeGet( HttpTransport transport, DocsUrl url, Class<? extends Feed> feedClass) throws IOException { HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(feedClass); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Entry { @Key("@gd:etag") public String etag; @Key("link") public List<Link> links; @Key public String summary; @Key public String title; @Key public String updated; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; /** * @author Yaniv Inbar */ public class DocumentListEntry extends Entry { }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Yaniv Inbar */ public class Debug { public static final boolean ENABLED = false; public static void enableLogging() { if (ENABLED) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.googleapis.GoogleUrl; /** * @author Yaniv Inbar */ public class DocsUrl extends GoogleUrl { public static final String ROOT_URL = "https://docs.google.com/feeds"; public DocsUrl(String url) { super(url); if (Debug.ENABLED) { this.prettyprint = true; } } private static DocsUrl forRoot() { return new DocsUrl(ROOT_URL); } private static DocsUrl forDefault() { DocsUrl result = forRoot(); result.pathParts.add("default"); return result; } public static DocsUrl forDefaultPrivateFull() { DocsUrl result = forDefault(); result.pathParts.add("private"); result.pathParts.add("full"); return result; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.docs.v3.model; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Key; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author Yaniv Inbar */ public class DocumentListFeed extends Feed { @Key("entry") public List<DocumentListEntry> docs = new ArrayList<DocumentListEntry>(); public static DocumentListFeed executeGet( HttpTransport transport, DocsUrl url) throws IOException { return (DocumentListFeed) Feed.executeGet( transport, url, DocumentListFeed.class); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android; import com.google.api.client.extensions.android2.AndroidHttp; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.sample.calendar.android.model.CalendarClient; import com.google.api.client.sample.calendar.android.model.CalendarEntry; import com.google.api.client.sample.calendar.android.model.CalendarFeed; import com.google.api.client.sample.calendar.android.model.CalendarUrl; import com.google.api.client.util.DateTime; import com.google.common.collect.Lists; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.ListActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Sample for Google Calendar Data API using the Atom wire format. It shows how to authenticate, get * calendars, add a new calendar, update it, and delete it. * <p> * To enable logging of HTTP requests/responses, change {@link #LOGGING_LEVEL} to * {@link Level#CONFIG} or {@link Level#ALL} and run this command: * </p> * * <pre> adb shell setprop log.tag.HttpTransport DEBUG * </pre> * * @author Yaniv Inbar */ public final class CalendarAndroidSample extends ListActivity { /** Logging level for HTTP requests/responses. */ private static Level LOGGING_LEVEL = Level.OFF; private static final String AUTH_TOKEN_TYPE = "cl"; private static final String TAG = "CalendarSample"; private static final int MENU_ADD = 0; private static final int MENU_ACCOUNTS = 1; private static final int CONTEXT_EDIT = 0; private static final int CONTEXT_DELETE = 1; private static final int REQUEST_AUTHENTICATE = 0; CalendarClient client; private final List<CalendarEntry> calendars = Lists.newArrayList(); private final HttpTransport transport = AndroidHttp.newCompatibleTransport(); String gsessionid; String authToken; String accountName; static final String PREF = TAG; static final String PREF_ACCOUNT_NAME = "accountName"; static final String PREF_AUTH_TOKEN = "authToken"; static final String PREF_GSESSIONID = "gsessionid"; GoogleAccountManager accountManager; SharedPreferences settings; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL); accountManager = new GoogleAccountManager(this); settings = this.getSharedPreferences(PREF, 0); authToken = settings.getString(PREF_AUTH_TOKEN, null); gsessionid = settings.getString(PREF_GSESSIONID, null); final MethodOverride override = new MethodOverride(); // needed for PATCH client = new CalendarClient(transport.createRequestFactory(new HttpRequestInitializer() { public void initialize(HttpRequest request) { GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("Google-CalendarAndroidSample/1.0"); headers.gdataVersion = "2"; request.headers = headers; client.initializeParser(request); request.interceptor = new HttpExecuteInterceptor() { public void intercept(HttpRequest request) throws IOException { GoogleHeaders headers = (GoogleHeaders) request.headers; headers.setGoogleLogin(authToken); request.url.set("gsessionid", gsessionid); override.intercept(request); } }; request.unsuccessfulResponseHandler = new HttpUnsuccessfulResponseHandler() { public boolean handleResponse( HttpRequest request, HttpResponse response, boolean retrySupported) { switch (response.statusCode) { case 302: GoogleUrl url = new GoogleUrl(response.headers.location); gsessionid = (String) url.getFirst("gsessionid"); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_GSESSIONID, gsessionid); editor.commit(); return true; case 401: accountManager.invalidateAuthToken(authToken); authToken = null; SharedPreferences.Editor editor2 = settings.edit(); editor2.remove(PREF_AUTH_TOKEN); editor2.commit(); return false; } return false; } }; } })); getListView().setTextFilterEnabled(true); registerForContextMenu(getListView()); gotAccount(); } void setAuthToken(String authToken) { SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_AUTH_TOKEN, authToken); editor.commit(); this.authToken = authToken; } void setAccountName(String accountName) { SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_ACCOUNT_NAME, accountName); editor.remove(PREF_GSESSIONID); editor.commit(); this.accountName = accountName; gsessionid = null; } private void gotAccount() { Account account = accountManager.getAccountByName(accountName); if (account != null) { // handle invalid token if (authToken == null) { accountManager.manager.getAuthToken( account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle bundle = future.getResult(); if (bundle.containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT); int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, REQUEST_AUTHENTICATE); } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) { setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN)); executeRefreshCalendars(); } } catch (Exception e) { handleException(e); } } }, null); } else { executeRefreshCalendars(); } return; } chooseAccount(); } private void chooseAccount() { accountManager.manager.getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null, CalendarAndroidSample.this, null, null, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { Bundle bundle; try { bundle = future.getResult(); setAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME)); setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN)); executeRefreshCalendars(); } catch (OperationCanceledException e) { // user canceled } catch (AuthenticatorException e) { handleException(e); } catch (IOException e) { handleException(e); } } }, null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_AUTHENTICATE: if (resultCode == RESULT_OK) { gotAccount(); } else { chooseAccount(); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ADD, 0, getString(R.string.new_calendar)); if (accountManager.getAccounts().length >= 2) { menu.add(0, MENU_ACCOUNTS, 0, getString(R.string.switch_account)); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD: CalendarUrl url = CalendarUrl.forOwnCalendarsFeed(); CalendarEntry calendar = new CalendarEntry(); calendar.title = "Calendar " + new DateTime(new Date()); try { client.executeInsertCalendar(calendar, url); } catch (IOException e) { handleException(e); } executeRefreshCalendars(); return true; case MENU_ACCOUNTS: chooseAccount(); return true; } return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_EDIT, 0, getString(R.string.update_title)); menu.add(0, CONTEXT_DELETE, 0, getString(R.string.delete)); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); CalendarEntry calendar = calendars.get((int) info.id); try { switch (item.getItemId()) { case CONTEXT_EDIT: CalendarEntry patchedCalendar = calendar.clone(); patchedCalendar.title = calendar.title + " UPDATED " + new DateTime(new Date()); client.executePatchCalendarRelativeToOriginal(patchedCalendar, calendar); executeRefreshCalendars(); return true; case CONTEXT_DELETE: client.executeDelete(calendar); executeRefreshCalendars(); return true; default: return super.onContextItemSelected(item); } } catch (IOException e) { handleException(e); } return false; } void executeRefreshCalendars() { String[] calendarNames; List<CalendarEntry> calendars = this.calendars; calendars.clear(); try { CalendarUrl url = CalendarUrl.forAllCalendarsFeed(); // page through results while (true) { CalendarFeed feed = client.executeGetCalendarFeed(url); if (feed.calendars != null) { calendars.addAll(feed.calendars); } String nextLink = feed.getNextLink(); if (nextLink == null) { break; } } int numCalendars = calendars.size(); calendarNames = new String[numCalendars]; for (int i = 0; i < numCalendars; i++) { calendarNames[i] = calendars.get(i).title; } } catch (IOException e) { handleException(e); calendarNames = new String[] {e.getMessage()}; calendars.clear(); } setListAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, calendarNames)); } void handleException(Exception e) { e.printStackTrace(); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).response; int statusCode = response.statusCode; try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } // TODO(yanivi): should only try this once to avoid infinite loop if (statusCode == 401) { gotAccount(); return; } } Log.e(TAG, e.getMessage(), e); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; /** * @author Yaniv Inbar */ public class CalendarEntry extends Entry { public String getEventFeedLink() { return Link.find(links, "http://schemas.google.com/gCal/2005#eventFeed"); } @Override public CalendarEntry clone() { return (CalendarEntry) super.clone(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Link { @Key("@href") public String href; @Key("@rel") public String rel; public static String find(List<Link> links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Feed { @Key("link") public List<Link> links; public String getNextLink() { return Link.find(links, "next"); } public String getBatchLink() { return Link.find(links, "http://schemas.google.com/g/2005#batch"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class CalendarUrl extends GoogleUrl { public static final String ROOT_URL = "https://www.google.com/calendar/feeds"; @Key("max-results") public Integer maxResults; public CalendarUrl(String url) { super(url); if (CalendarClient.DEBUG) { this.prettyprint = true; } } private static CalendarUrl forRoot() { return new CalendarUrl(ROOT_URL); } public static CalendarUrl forCalendarMetafeed() { CalendarUrl result = forRoot(); result.pathParts.add("default"); return result; } public static CalendarUrl forAllCalendarsFeed() { CalendarUrl result = forCalendarMetafeed(); result.pathParts.add("allcalendars"); result.pathParts.add("full"); return result; } public static CalendarUrl forOwnCalendarsFeed() { CalendarUrl result = forCalendarMetafeed(); result.pathParts.add("owncalendars"); result.pathParts.add("full"); return result; } public static CalendarUrl forEventFeed(String userId, String visibility, String projection) { CalendarUrl result = forRoot(); result.pathParts.add(userId); result.pathParts.add(visibility); result.pathParts.add(projection); return result; } public static CalendarUrl forDefaultPrivateFullEventFeed() { return forEventFeed("default", "private", "full"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.util.Data; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Entry implements Cloneable { @Key public String summary; @Key public String title; @Key public String updated; @Key("link") public List<Link> links; @Override protected Entry clone() { try { @SuppressWarnings("unchecked") Entry result = (Entry) super.clone(); Data.deepCopy(this, result); return result; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } String getEditLink() { return Link.find(links, "edit"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.util.Key; import com.google.common.collect.Lists; import java.util.List; /** * @author Yaniv Inbar */ public class CalendarFeed extends Feed { @Key("entry") public List<CalendarEntry> calendars = Lists.newArrayList(); }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.android.model; import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent; import com.google.api.client.googleapis.xml.atom.GoogleAtom; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.xml.atom.AtomContent; import com.google.api.client.http.xml.atom.AtomParser; import com.google.api.client.xml.XmlNamespaceDictionary; import java.io.IOException; /** * @author Yaniv Inbar */ public class CalendarClient { /** Whether to enable debugging. */ public static final boolean DEBUG = true; static final XmlNamespaceDictionary DICTIONARY = new XmlNamespaceDictionary().set("", "http://www.w3.org/2005/Atom").set( "batch", "http://schemas.google.com/gdata/batch").set( "gd", "http://schemas.google.com/g/2005"); private final HttpRequestFactory requestFactory; public CalendarClient(HttpRequestFactory requestFactory) { this.requestFactory = requestFactory; } public void initializeParser(HttpRequest request) { AtomParser parser = new AtomParser(); parser.namespaceDictionary = DICTIONARY; request.addParser(parser); } public void executeDelete(Entry entry) throws IOException { HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(entry.getEditLink())); request.execute().ignore(); } Entry executeInsert(Entry entry, CalendarUrl url) throws IOException { AtomContent content = new AtomContent(); content.namespaceDictionary = DICTIONARY; content.entry = entry; HttpRequest request = requestFactory.buildPostRequest(url, content); return request.execute().parseAs(entry.getClass()); } Entry executePatchRelativeToOriginal(Entry updated, Entry original) throws IOException { AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent(); content.namespaceDictionary = DICTIONARY; content.originalEntry = original; content.patchedEntry = updated; HttpRequest request = requestFactory.buildPatchRequest(new GenericUrl(updated.getEditLink()), content); return request.execute().parseAs(updated.getClass()); } <F extends Feed> F executeGetFeed(CalendarUrl url, Class<F> feedClass) throws IOException { url.fields = GoogleAtom.getFieldsFor(feedClass); HttpRequest request = requestFactory.buildGetRequest(url); return request.execute().parseAs(feedClass); } public CalendarEntry executeInsertCalendar(CalendarEntry entry, CalendarUrl url) throws IOException { return (CalendarEntry) executeInsert(entry, url); } public CalendarEntry executePatchCalendarRelativeToOriginal( CalendarEntry updated, CalendarEntry original) throws IOException { return (CalendarEntry) executePatchRelativeToOriginal(updated, original); } public CalendarFeed executeGetCalendarFeed(CalendarUrl url) throws IOException { return executeGetFeed(url, CalendarFeed.class); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction; /** * @author Yaniv Inbar */ public class ClientLoginCredentials { static final String ENTER_USERNAME = "enter_username"; static final String ENTER_PASSWORD = "enter_password"; static final String OBJECT_PATH = "enter_bucket/language_id.txt"; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.googleapis.auth.clientlogin.ClientLogin; import com.google.api.client.googleapis.json.JsonCContent; import com.google.api.client.googleapis.json.JsonCParser; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.sample.prediction.model.CheckTraining; import com.google.api.client.sample.prediction.model.Debug; import com.google.api.client.sample.prediction.model.InputData; import com.google.api.client.sample.prediction.model.OutputData; import com.google.api.client.sample.prediction.model.PredictionUrl; import com.google.api.client.util.ArrayMap; import java.io.IOException; /** * @author Yaniv Inbar */ public class PredictionSample { public static void main(String[] args) { Debug.enableLogging(); HttpTransport transport = setUpTransport(); try { try { authenticateWithClientLogin(transport); train(transport); predict(transport, "Is this sentence in English?"); predict(transport, "¿Es esta frase en Español?"); predict(transport, "Est-ce cette phrase en Français?"); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } private static HttpTransport setUpTransport() { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Google-PredictionSample/1.0"); transport.addParser(new JsonCParser()); return transport; } private static void authenticateWithClientLogin(HttpTransport transport) throws IOException { ClientLogin authenticator = new ClientLogin(); authenticator.authTokenType = "xapi"; authenticator.username = ClientLoginCredentials.ENTER_USERNAME; authenticator.password = ClientLoginCredentials.ENTER_PASSWORD; authenticator.authenticate().setAuthorizationHeader(transport); } private static void train(HttpTransport transport) throws IOException { HttpRequest request = transport.buildPostRequest(); JsonCContent content = new JsonCContent(); content.data = ArrayMap.create(); request.content = content; request.url = PredictionUrl.forTraining(ClientLoginCredentials.OBJECT_PATH); request.execute().ignore(); System.out.println("Training started."); System.out.print("Waiting for training to complete"); System.out.flush(); while (true) { request = transport.buildGetRequest(); request.url = PredictionUrl.forCheckingTraining(ClientLoginCredentials.OBJECT_PATH); CheckTraining checkTraining = request.execute().parseAs(CheckTraining.class); if (checkTraining.modelinfo.toLowerCase().startsWith( "estimated accuracy")) { System.out.println(); System.out.println("Training completed."); System.out.println(checkTraining.modelinfo); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { break; } System.out.print("."); System.out.flush(); } } private static void predict(HttpTransport transport, String text) throws IOException { HttpRequest request = transport.buildPostRequest(); request.url = PredictionUrl.forPrediction(ClientLoginCredentials.OBJECT_PATH); JsonCContent content = new JsonCContent(); InputData inputData = new InputData(); inputData.input.text.add(text); content.data = inputData; request.content = content; OutputData outputData = request.execute().parseAs(OutputData.class); System.out.println("Text: " + text); System.out.println("Predicted language: " + outputData.outputLabel); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class InputData { @Key public Input input = new Input(); }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * Prediction URL builder. * * @author Yaniv Inbar */ public final class PredictionUrl extends GoogleUrl { @Key public String data; /** Constructs a new Prediction URL from the given encoded URL. */ public PredictionUrl(String encodedUrl) { super(encodedUrl); if (Debug.ENABLED) { prettyprint = true; } } private static PredictionUrl root() { return new PredictionUrl( "https://www.googleapis.com/prediction/v1.1/training"); } /** * Constructs a new training URL based on the given object path of the form * {@code "mybucket/myobject"}. */ public static PredictionUrl forTraining(String objectPath) { PredictionUrl result = root(); result.data = objectPath; return result; } /** * Constructs a new check training URL based on the given object path of the * form {@code "mybucket/myobject"}. */ public static PredictionUrl forCheckingTraining(String objectPath) { PredictionUrl result = root(); // this will ensure that objectPath is encoded properly, e.g. "/" -> "%2F" result.pathParts.add(objectPath); return result; } /** * Constructs a new prediction URL based on the given object path of the form * {@code "mybucket/myobject"}. */ public static PredictionUrl forPrediction(String objectPath) { PredictionUrl result = forCheckingTraining(objectPath); result.pathParts.add("predict"); return result; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class CheckTraining { @Key public String data; @Key public String modelinfo; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Yaniv Inbar */ public class Debug { public static final boolean ENABLED = false; public static void enableLogging() { if (ENABLED) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class OutputData { @Key public String outputLabel; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.prediction.model; import com.google.api.client.util.Key; import java.util.ArrayList; import java.util.List; /** * @author Yaniv Inbar */ public class Input { @Key public List<String> text = new ArrayList<String>(); }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.json.JsonHttpParser; import com.google.cloud.taskqueue.client.sample.model.Task; import com.google.cloud.taskqueue.client.sample.model.TaskQueue; import com.google.cloud.taskqueue.client.sample.model.Util; import java.io.IOException; import java.util.List; /** * Sample which leases task from TaskQueueService, performs work on the paylaod * of the task and then deletes the task. * @author Vibhooti Verma */ public class TaskQueuePuller { static final String APP_DESCRIPTION = "TaskQueue API Java Client Sample"; static String projectName; static String taskQueueName; static int leaseSecs; static int numTasks; public static boolean parseParams(String[] args) { try { projectName = args[0]; taskQueueName = args[1]; leaseSecs = Integer.parseInt(args[2]); numTasks = Integer.parseInt(args[3]); return true; } catch (ArrayIndexOutOfBoundsException ae) { System.out.println("Insufficient Arguments"); return false; } catch (NumberFormatException ae) { System.out.println("Please specify lease seconds and Number of tasks to" + "lease, in number format"); return false; } } public static void printUsage() { System.out.println("mvn -q exec:java -Dexec.args=\"" + "/TaskQueueApiSample <ProjectName> <TaskQueueName> " + "<LeaseSeconds> <NumberOfTasksToLease>\""); } /** * You can perform following operations using TaskQueueService. * 1. leasetasks * 2. gettask * 3. delete task * 4. getqueue * For illustration purpose, we are first getting the stats of the specified * queue followed by leasing tasks and deleting them. Users cna change the * flow according to their needs. */ public static void main(String[] args) { Util.enableLogging(); try { if (args.length != 4) { System.out.println("Insuficient arguments"); printUsage(); System.exit(1); } else if (!parseParams(args)) { printUsage(); System.exit(1); } try { setUpTransport(); authorize(); getTaskQueue(); leaseAndDeleteTask(); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); Auth.revoke(); System.exit(1); } } private static void setUpTransport() { JsonHttpParser parser = new JsonHttpParser(); parser.jsonFactory = Util.JSON_FACTORY; Util.TRANSPORT.addParser(parser); } /** * Method to perform authorization using oauth1. * @throws Exception */ private static void authorize() throws Exception { Auth.authorize(); } /** * Method to get details of the queue using the args specified by user. * @throws IOException */ private static void getTaskQueue() throws IOException { TaskQueue queue = new TaskQueue(); queue.get(projectName, taskQueueName, true); } /** * Method to get details of the task. * */ private static void getTask() throws IOException { Task task = new Task(); String id = "id"; task.get(projectName, taskQueueName, id); } /** * Method to lease multiple tasks, perform the tasks and one by one along with * deleting them from the taskqueue. * @throws IOException */ private static void leaseAndDeleteTask() throws IOException { Task task = new Task(); List<Task> leasedTasks = task.lease(projectName, taskQueueName, leaseSecs, numTasks); if (leasedTasks.size() == 0) { System.out.println("No tasks to lease and hence exiting"); } for (Task leasedTask : leasedTasks) { leasedTask.executeTask(); leasedTask.delete(); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample; import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl; import com.google.api.client.auth.oauth.OAuthCredentialsResponse; import com.google.api.client.auth.oauth.OAuthHmacSigner; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken; import com.google.cloud.taskqueue.client.sample.model.Util; import java.io.*; import java.util.Scanner; /** * Implements OAuth authentication. * * @author Vibhooti Verma */ public class Auth { private static OAuthHmacSigner signer; private static OAuthCredentialsResponse credentials; private static String TOKEN_FILE = ".taskqueue_token"; /** * Method to authorize the request using oauth1 authorization. This actually * signs the util.TRANSPORT object using the authorization header and makes it * eligible to access the the taskqueue service. The same TRANSPORT object is * used throughout the application(sample) to build any kind of request (post/ * get/delete etc). * There can be two cases during authorization: * 1. First time users: This asks the user to open the google authorization * url in browser and to provide their credentail and finally * paste the received verifier token. Once authorized, it automatically * stores access tokens (also called long lived tokens) in local copy for * later use. * 2. Once the credentails are found in local copy as plain text, * authorization is done seemlessely using them. However, it should be kept * in mind that storing token/crdentials in plain text is quite insecure and * a real application must use good encryption to store them. Since this is * a sample, we are currently storing them as plain text itself. * * @throws Exception */ static void authorize() throws Exception { TOKEN_FILE = System.getProperty("user.home") + "/" + TOKEN_FILE; signer = new OAuthHmacSigner(); signer.clientSharedSecret = ClientCredentials.ENTER_OAUTH_CONSUMER_SECRET; File file = new File(TOKEN_FILE); // If access tokens are already stored locally, make use of them. if (file.exists()) { createOAuthParametersFromTokenFile(). signRequestsUsingAuthorizationHeader(Util.TRANSPORT); return; } String verifier = null; String tempToken = null; try { GoogleOAuthGetTemporaryToken temporaryToken = new GoogleOAuthGetTemporaryToken(); temporaryToken.transport = Util.AUTH_TRANSPORT; temporaryToken.signer = signer; temporaryToken.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; temporaryToken.scope = "https://www.googleapis.com/auth/taskqueue"; temporaryToken.displayName = TaskQueueSample.APP_DESCRIPTION; // We are not implementing the callback server since mostly the workers // will run on VM and we want to save user from opening the brower on // VM. Hence setting the callback to oob. temporaryToken.callback = "oob"; OAuthCredentialsResponse tempCredentials = temporaryToken.execute(); signer.tokenSharedSecret = tempCredentials.tokenSecret; // authorization URL OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl( "https://www.google.com/accounts/OAuthAuthorizeToken"); authorizeUrl.set("scope", temporaryToken.scope); authorizeUrl.set("domain", ClientCredentials.ENTER_OAUTH_CONSUMER_KEY); authorizeUrl.set("xoauth_displayname", TaskQueueSample.APP_DESCRIPTION); authorizeUrl.temporaryToken = tempToken = tempCredentials.token; String authorizationUrl = authorizeUrl.build(); System.out.println("Please run this URL in a browser and paste the" + "token back here\n" + authorizationUrl); System.out.println("Enter verification code: "); InputStreamReader converter = new InputStreamReader(System.in); Scanner in = new Scanner(System.in); verifier = in.nextLine(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } // access token GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken(); accessToken.transport = Util.AUTH_TRANSPORT; accessToken.temporaryToken = tempToken; accessToken.signer = signer; accessToken.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; accessToken.verifier = verifier; credentials = accessToken.execute(); signer.tokenSharedSecret = credentials.tokenSecret; createOAuthParameters().signRequestsUsingAuthorizationHeader(Util.TRANSPORT); try { FileWriter fstream = new FileWriter(TOKEN_FILE); BufferedWriter out = new BufferedWriter(fstream); out.write(credentials.tokenSecret); out.newLine(); out.write(credentials.token); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } } /* * Method to revoke authorization of long lived access tokens. This should be * called if you do not want to retain the access tokens for later user. */ static void revoke() { if (credentials != null) { try { GoogleOAuthGetAccessToken.revokeAccessToken(Util.AUTH_TRANSPORT, createOAuthParameters()); } catch (Exception e) { e.printStackTrace(System.err); } } } /* * Create authentication parameters using access token credentials and signer. * Both of these are set in function calling this createoauthParameters * (mehtod:authorize in this case). * Signer contains both * 1. Consumer secret key * 2. Access token secret * */ public static OAuthParameters createOAuthParameters() { OAuthParameters authorizer = new OAuthParameters(); authorizer.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; authorizer.signer = signer; authorizer.token = credentials.token; return authorizer; } /* * Create authentication parameters using access token credentials stored in * file. */ public static OAuthParameters createOAuthParametersFromTokenFile() { String tokenSecret = ""; String token = ""; try { BufferedReader br = new BufferedReader(new FileReader(TOKEN_FILE)); tokenSecret = br.readLine(); token = br.readLine(); if (tokenSecret == null || token == null) { System.out.println("Credentials stored in " + TOKEN_FILE + " are incomplete or corrupt. Please delete the file and get new" + " credentials by running the sample again."); System.exit(0); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } signer.tokenSharedSecret = tokenSecret; OAuthParameters authorizer = new OAuthParameters(); authorizer.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY; authorizer.signer = signer; authorizer.token = token; return authorizer; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.json.JsonHttpParser; import com.google.cloud.taskqueue.client.sample.model.Task; import com.google.cloud.taskqueue.client.sample.model.TaskQueue; import com.google.cloud.taskqueue.client.sample.model.Util; import java.io.IOException; import java.util.List; /** * Sample which leases task from TaskQueueService, performs work on the payload * of the task and then deletes the task. * @author Vibhooti Verma */ public class TaskQueueSample { static final String APP_DESCRIPTION = "TaskQueue API Java Client Sample"; static String projectName; static String taskQueueName; static int leaseSecs; static int numTasks; public static boolean parseParams(String[] args) { try { projectName = args[0]; taskQueueName = args[1]; leaseSecs = Integer.parseInt(args[2]); numTasks = Integer.parseInt(args[3]); return true; } catch (ArrayIndexOutOfBoundsException ae) { System.out.println("Insufficient Arguments"); return false; } catch (NumberFormatException ae) { System.out.println("Please specify lease seconds and Number of tasks to" + "lease, in number format"); return false; } } public static void printUsage() { System.out.println("mvn -q exec:java -Dexec.args=\"" + "/TaskQueueApiSample <ProjectName> <TaskQueueName> " + "<LeaseSeconds> <NumberOfTasksToLease>\""); } /** * You can perform following operations using TaskQueueService. * 1. leasetasks * 2. gettask * 3. delete task * 4. getqueue * For illustration purpose, we are first getting the stats of the specified * queue followed by leasing tasks and deleting them. Users can change the * flow according to their needs. */ public static void main(String[] args) { Util.enableLogging(); try { if (args.length != 4) { System.out.println("Insuficient arguments"); printUsage(); System.exit(1); } else if (!parseParams(args)) { printUsage(); System.exit(1); } try { setUpTransport(); authorize(); getTaskQueue(); leaseAndDeleteTask(); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); Auth.revoke(); System.exit(1); } } private static void setUpTransport() { JsonHttpParser parser = new JsonHttpParser(); parser.jsonFactory = Util.JSON_FACTORY; Util.TRANSPORT.addParser(parser); } /** * Method to perform authorization using oauth1. * @throws Exception */ private static void authorize() throws Exception { Auth.authorize(); } /** * Method to get details of the queue using the args specified by user. * @throws IOException */ private static void getTaskQueue() throws IOException { TaskQueue queue = new TaskQueue(); System.out.println(queue.get(projectName, taskQueueName, true).toString()); } /** * Method to get details of the task. * */ private static void getTask() throws IOException { Task task = new Task(); String id = "id"; task.get(projectName, taskQueueName, id); } /** * Method to lease multiple tasks, perform the tasks and one by one along with * deleting them from the taskqueue. * @throws IOException */ private static void leaseAndDeleteTask() throws IOException { Task task = new Task(); List<Task> leasedTasks = task.lease(projectName, taskQueueName, leaseSecs, numTasks); if (leasedTasks.size() == 0) { System.out.println("No tasks to lease and hence exiting"); } for (Task leasedTask : leasedTasks) { leasedTask.executeTask(); leasedTask.delete(); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample; /** * @author Vibhooti Verma */ public class ClientCredentials { /** * OAuth Consumer Key obtained from the <a * href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page or {@code * anonymous} by default. */ static final String ENTER_OAUTH_CONSUMER_KEY = "anonymous"; /** * OAuth Consumer Secret obtained from the <a * href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page or {@code * anonymous} by default. */ static final String ENTER_OAUTH_CONSUMER_SECRET = "anonymous"; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.googleapis.json.JsonCContent; import com.google.api.client.http.HttpRequest; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; import java.io.IOException; /** * * Class to encapsulate TaskQueueService's TaskQueue object * * @author Vibhooti Verma */ public class TaskQueue extends GenericJson { /** TaskQueue identifier. */ @Key public String id; @Key public String kind; QueueStats stats; /** * Method to get details of a taskqueue from taskqueue service. * @params: * projectName: Name of the taskqueue project * queueName: Name of the taskqueue whose details are requested * getStats: Flag to get more stats of the queue * @returns A TaskQueue object with all the details. */ public TaskQueue get(String projectName, String taskQueueName, boolean getStats) throws IOException { HttpRequest request = Util.TRANSPORT.buildGetRequest(); request.url = TaskQueueUrl.forTaskQueueServiceQueues(projectName, taskQueueName, getStats); return request.execute().parseAs(TaskQueue.class); } /** Returns a new JSON-C content serializer for TaskQueue. */ private JsonCContent toContent() { JsonCContent result = new JsonCContent(); result.data = this; result.jsonFactory = Util.JSON_FACTORY; return result; } public final String toString(Object item) { return jsonFactory.toString(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleUtils; 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.jackson.JacksonFactory; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Vibhooti Verma */ public class Util { public static final boolean DEBUG = false; public static final HttpTransport TRANSPORT = newTransport(); public static final HttpTransport AUTH_TRANSPORT = newTransport(); public static final JsonFactory JSON_FACTORY = new JacksonFactory(); static HttpTransport newTransport() { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("Google-TaskQueueSample/1.0"); result.defaultHeaders = headers; return result; } public static void enableLogging() { if (DEBUG) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * Prepares Request URL for TaskQueue operations. * * @author Vibhooti Verma */ public class TaskQueueUrl extends GoogleUrl { @Key("leaseSecs") public Integer leaseSecs; @Key("numTasks") public Integer numTasks; @Key("getStats") public boolean getStats; /** Constructs a new TaskQueue URL from the given encoded URL. */ public TaskQueueUrl(String encodedUrl) { super(encodedUrl); alt = "json"; if (Util.DEBUG) { prettyprint = true; } } public static TaskQueueUrl forTaskQueueService() { return new TaskQueueUrl("https://www.googleapis.com/taskqueue/v1beta1/projects"); } public static TaskQueueUrl forTaskQueueServiceQueues(String projectName, String taskQueueName, boolean getStats) { TaskQueueUrl result = forTaskQueueService(); result.pathParts.add(projectName); result.pathParts.add("taskqueues"); result.pathParts.add(taskQueueName); result.getStats = getStats; return result; } public static TaskQueueUrl forTaskQueueServiceTasks(String projectName, String taskQueueName) { TaskQueueUrl result = forTaskQueueService(); result.pathParts.add(projectName); result.pathParts.add("taskqueues"); result.pathParts.add(taskQueueName); result.pathParts.add("tasks"); return result; } public static TaskQueueUrl forTaskQueueServiceTasks(String projectName, String taskQueueName, int leaseSecs, int numTasks) { TaskQueueUrl result = forTaskQueueServiceTasks(projectName, taskQueueName); result.leaseSecs = leaseSecs; result.numTasks = numTasks; return result; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.util.Key; /** * Class to represent stats/details of TaskQueue. * @author Vibhooti Verma */ public class QueueStats { @Key int leasedLastHour; @Key int leasedLastMinute; @Key int oldTasks; @Key int newTasks; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.util.Key; import java.util.ArrayList; import java.util.List; /** * Class to represent list of Task object during parsing of lease request * result. * @author Vibhooti Verma */ public class TaskList { @Key public List<Task> items = new ArrayList<Task>(); }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.cloud.taskqueue.client.sample.model; import com.google.api.client.googleapis.json.JsonCContent; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponseException; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; import java.io.IOException; import java.util.List; /** * Class to encapsulate TaskQueueService's task object * * @author Vibhooti Verma */ public class Task extends GenericJson { @Key public String id; @Key public String kind; @Key public long leaseTimestamp; @Key public String payloadBase64; // queueName is of format "projects/<project-name>/taskqueues/<taskqueue-name>" @Key public String queueName; public Task() { } /** * Method to extract project name from full queue name. * queueName is of format "projects/<project-name>/taskqueues/<taskqueue-name>" * */ public String getProjectFromQueueName() { try { String arr[] = queueName.split("/"); return arr[1]; } catch (ArrayIndexOutOfBoundsException ae) { System.out.println("Error: Project name could not be parsed from" + "queueName: " + queueName); return new String(""); } } /** * Method to extract queue name from full queue name. * queueName is of format "projects/<project-name>/taskqueues/<taskqueue-name>" * */ public String getQueueFromQueueName() { try { String arr[] = queueName.split("/"); return arr[3]; } catch (ArrayIndexOutOfBoundsException ae) { System.out.println("Error: Queue name could not be parsed from " + "queueName: " + queueName); return new String(""); } } /** * Method to delete task from taskqueue service. * This sends the delete request for this task object to taskqueue service. * * @throws: HttpResponseException if the http request call fails due to some * reason. */ public void delete() throws HttpResponseException, IOException { HttpRequest request = Util.TRANSPORT.buildDeleteRequest(); String projectName = getProjectFromQueueName(); String queueName = getQueueFromQueueName(); if (projectName.isEmpty() || queueName.isEmpty()) { System.out.println("Error parsing full queue name:" + this.queueName + " Hence unable to delete task" + this.id); return; } request.url = TaskQueueUrl.forTaskQueueServiceTasks(projectName, queueName); request.url.pathParts.add(this.id); try { request.execute(); } catch (HttpResponseException hre) { System.out.println("Error deleting task: " + this.id); throw hre; } } /** * Method to get details of as task from taskqueue service given project name, * queue name and task id. * * @returns: Task object with all the details such as payload, leasetimestamp. */ public Task get(String projectName, String taskQueueName, String id) throws IOException { HttpRequest request = Util.TRANSPORT.buildGetRequest(); request.url = TaskQueueUrl.forTaskQueueServiceTasks(projectName, taskQueueName); request.url.pathParts.add(id); return request.execute().parseAs(Task.class); } /** * Method to lease multiple tasks from taskqueue service. * @params: * projectName: Name of the project * taskqueueName: name of the queue whose task need to be leased. * leaseSecs: Number of seconds for which the task should be leased. This * should be approximately equal to time to execute the task. * numTasks: Number of tasks to be leased in one lease request. This usually * helps optimizing the time taken for the application to execute the tasks. * */ public List<Task> lease(String projectName, String taskQueueName, int leaseSecs, int numTasks) throws IOException { HttpRequest request = Util.TRANSPORT.buildPostRequest(); request.url = TaskQueueUrl.forTaskQueueServiceTasks( projectName, taskQueueName, leaseSecs, numTasks); request.url.pathParts.add("lease"); request.content = toContent(); return request.execute().parseAs(TaskList.class).items; } private JsonCContent toContent() { JsonCContent result = new JsonCContent(); result.data = this; result.jsonFactory = Util.JSON_FACTORY; return result; } /** * This method actually performs the desired work on tasks. It can make use of * payload of the task. By default, we are just printing the payload of the * leased task." */ public void executeTask() { System.out.println("Payload for the task:"); System.out.println(this.payloadBase64); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.sample.picasa.model.AlbumEntry; import com.google.api.client.sample.picasa.model.PicasaUrl; import com.google.api.client.sample.picasa.model.UserFeed; import com.google.api.client.sample.picasa.model.Util; import com.google.api.client.util.DateTime; import com.google.api.client.xml.atom.AtomParser; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore.Images; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Sample for Picasa Web Albums Data API using the Atom wire format. It shows * how to authenticate, get albums, add a new album, update it, and delete it. * <p> * It also demonstrates how to upload a photo to the "Drop Box" album. To see * this example in action, take a picture, click "Share", and select "Picasa * Basic Android Sample". * </p> * <p> * To enable logging of HTTP requests/responses, run this command: {@code adb * shell setprop log.tag.HttpTransport DEBUG}. Then press-and-hold an album, and * enable "Logging". * </p> * * @author Yaniv Inbar */ public final class PicasaAndroidSample extends ListActivity { private static final String AUTH_TOKEN_TYPE = "lh2"; private static final String TAG = "PicasaAndroidSample"; private static final int MENU_ADD = 0; private static final int MENU_ACCOUNTS = 1; private static final int CONTEXT_EDIT = 0; private static final int CONTEXT_DELETE = 1; private static final int CONTEXT_LOGGING = 2; private static final int REQUEST_AUTHENTICATE = 0; private static final String PREF = "MyPrefs"; private static final int DIALOG_ACCOUNTS = 0; private static HttpTransport transport; private String authToken; private String postLink; private final List<AlbumEntry> albums = new ArrayList<AlbumEntry>(); public PicasaAndroidSample() { transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Google-PicasaAndroidAample/1.0"); headers.gdataVersion = "2"; AtomParser parser = new AtomParser(); parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY; transport.addParser(parser); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences settings = getSharedPreferences(PREF, 0); setLogging(settings.getBoolean("logging", false)); getListView().setTextFilterEnabled(true); registerForContextMenu(getListView()); Intent intent = getIntent(); if (Intent.ACTION_SEND.equals(intent.getAction())) { sendData = new SendData(intent, getContentResolver()); } else if (Intent.ACTION_MAIN.equals(getIntent().getAction())) { sendData = null; } gotAccount(false); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ACCOUNTS: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Google account"); final AccountManager manager = AccountManager.get(this); final Account[] accounts = manager.getAccountsByType("com.google"); final int size = accounts.length; String[] names = new String[size]; for (int i = 0; i < size; i++) { names[i] = accounts[i].name; } builder.setItems(names, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { gotAccount(manager, accounts[which]); } }); return builder.create(); } return null; } private void gotAccount(boolean tokenExpired) { SharedPreferences settings = getSharedPreferences(PREF, 0); String accountName = settings.getString("accountName", null); if (accountName != null) { AccountManager manager = AccountManager.get(this); Account[] accounts = manager.getAccountsByType("com.google"); int size = accounts.length; for (int i = 0; i < size; i++) { Account account = accounts[i]; if (accountName.equals(account.name)) { if (tokenExpired) { manager.invalidateAuthToken("com.google", this.authToken); } gotAccount(manager, account); return; } } } showDialog(DIALOG_ACCOUNTS); } private void gotAccount(final AccountManager manager, final Account account) { SharedPreferences settings = getSharedPreferences(PREF, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("accountName", account.name); editor.commit(); new Thread() { @Override public void run() { try { final Bundle bundle = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null) .getResult(); runOnUiThread(new Runnable() { public void run() { try { if (bundle.containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT); int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, REQUEST_AUTHENTICATE); } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) { authenticatedClientLogin( bundle.getString(AccountManager.KEY_AUTHTOKEN)); } } catch (Exception e) { handleException(e); } } }); } catch (Exception e) { handleException(e); } } }.start(); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_AUTHENTICATE: if (resultCode == RESULT_OK) { gotAccount(false); } else { showDialog(DIALOG_ACCOUNTS); } break; } } private void authenticatedClientLogin(String authToken) { this.authToken = authToken; ((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken); authenticated(); } static class SendData { String fileName; Uri uri; String contentType; long contentLength; SendData(Intent intent, ContentResolver contentResolver) { Bundle extras = intent.getExtras(); if (extras.containsKey(Intent.EXTRA_STREAM)) { Uri uri = this.uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); String scheme = uri.getScheme(); if (scheme.equals("content")) { Cursor cursor = contentResolver.query(uri, null, null, null, null); cursor.moveToFirst(); this.fileName = cursor.getString( cursor.getColumnIndexOrThrow(Images.Media.DISPLAY_NAME)); this.contentType = intent.getType(); this.contentLength = cursor.getLong(cursor.getColumnIndexOrThrow(Images.Media.SIZE)); } } } } static SendData sendData; private void authenticated() { if (sendData != null) { try { if (sendData.fileName != null) { boolean success = false; try { HttpRequest request = transport.buildPostRequest(); request.url = PicasaUrl.relativeToRoot( "feed/api/user/default/albumid/default"); ((GoogleHeaders) request.headers).setSlugFromFileName( sendData.fileName); InputStreamContent content = new InputStreamContent(); content.inputStream = getContentResolver().openInputStream(sendData.uri); content.type = sendData.contentType; content.length = sendData.contentLength; request.content = content; request.execute().ignore(); success = true; } catch (IOException e) { handleException(e); } setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[] {success ? "OK" : "ERROR"})); } } finally { sendData = null; } } else { executeRefreshAlbums(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ADD, 0, "New album"); menu.add(0, MENU_ACCOUNTS, 0, "Switch Account"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD: AlbumEntry album = new AlbumEntry(); album.access = "private"; album.title = "Album " + new DateTime(new Date()); try { AlbumEntry.executeInsert(transport, album, this.postLink); } catch (IOException e) { handleException(e); } executeRefreshAlbums(); return true; case MENU_ACCOUNTS: showDialog(DIALOG_ACCOUNTS); return true; } return false; } @Override public void onCreateContextMenu( ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_EDIT, 0, "Update Title"); menu.add(0, CONTEXT_DELETE, 0, "Delete"); SharedPreferences settings = getSharedPreferences(PREF, 0); boolean logging = settings.getBoolean("logging", false); menu.add(0, CONTEXT_LOGGING, 0, "Logging").setCheckable(true).setChecked( logging); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); AlbumEntry album = albums.get((int) info.id); try { switch (item.getItemId()) { case CONTEXT_EDIT: AlbumEntry patchedAlbum = album.clone(); patchedAlbum.title = album.title + " UPDATED " + new DateTime(new Date()); patchedAlbum.executePatchRelativeToOriginal(transport, album); executeRefreshAlbums(); return true; case CONTEXT_DELETE: album.executeDelete(transport); executeRefreshAlbums(); return true; case CONTEXT_LOGGING: SharedPreferences settings = getSharedPreferences(PREF, 0); boolean logging = settings.getBoolean("logging", false); setLogging(!logging); return true; default: return super.onContextItemSelected(item); } } catch (IOException e) { handleException(e); } return false; } private void executeRefreshAlbums() { String[] albumNames; List<AlbumEntry> albums = this.albums; albums.clear(); try { PicasaUrl url = PicasaUrl.relativeToRoot("feed/api/user/default"); // page through results while (true) { UserFeed userFeed = UserFeed.executeGet(transport, url); this.postLink = userFeed.getPostLink(); if (userFeed.albums != null) { albums.addAll(userFeed.albums); } String nextLink = userFeed.getNextLink(); if (nextLink == null) { break; } } int numAlbums = albums.size(); albumNames = new String[numAlbums]; for (int i = 0; i < numAlbums; i++) { albumNames[i] = albums.get(i).title; } } catch (IOException e) { handleException(e); albumNames = new String[] {e.getMessage()}; albums.clear(); } setListAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, albumNames)); } private void setLogging(boolean logging) { Logger.getLogger("com.google.api.client").setLevel( logging ? Level.CONFIG : Level.OFF); SharedPreferences settings = getSharedPreferences(PREF, 0); boolean currentSetting = settings.getBoolean("logging", false); if (currentSetting != logging) { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("logging", logging); editor.commit(); } } private void handleException(Exception e) { e.printStackTrace(); SharedPreferences settings = getSharedPreferences(PREF, 0); boolean log = settings.getBoolean("logging", false); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).response; int statusCode = response.statusCode; try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } if (statusCode == 401 || statusCode == 403) { gotAccount(true); return; } if (log) { try { Log.e(TAG, response.parseAsString()); } catch (IOException parseException) { parseException.printStackTrace(); } } } if (log) { Log.e(TAG, e.getMessage(), e); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class Category { @Key("@scheme") public String scheme; @Key("@term") public String term; public static Category newKind(String kind) { Category category = new Category(); category.scheme = "http://schemas.google.com/g/2005#kind"; category.term = "http://schemas.google.com/photos/2007#" + kind; return category; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Key; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class UserFeed extends Feed { @Key("entry") public List<AlbumEntry> albums; public static UserFeed executeGet(HttpTransport transport, PicasaUrl url) throws IOException { url.kinds = "album"; return (UserFeed) Feed.executeGet(transport, url, UserFeed.class); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Link { @Key("@href") public String href; @Key("@rel") public String rel; public static String find(List<Link> links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.xml.XmlNamespaceDictionary; import java.util.Map; /** * @author Yaniv Inbar */ public class Util { public static final XmlNamespaceDictionary NAMESPACE_DICTIONARY = new XmlNamespaceDictionary(); static { Map<String, String> map = NAMESPACE_DICTIONARY.namespaceAliasToUriMap; map.put("", "http://www.w3.org/2005/Atom"); map.put("atom", "http://www.w3.org/2005/Atom"); map.put("exif", "http://schemas.google.com/photos/exif/2007"); map.put("gd", "http://schemas.google.com/g/2005"); map.put("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#"); map.put("georss", "http://www.georss.org/georss"); map.put("gml", "http://www.opengis.net/gml"); map.put("gphoto", "http://schemas.google.com/photos/2007"); map.put("media", "http://search.yahoo.com/mrss/"); map.put("openSearch", "http://a9.com/-/spec/opensearch/1.1/"); map.put("xml", "http://www.w3.org/XML/1998/namespace"); } private Util() { } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.googleapis.xml.atom.GData; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Key; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class Feed { @Key("link") public List<Link> links; public String getPostLink() { return Link.find(links, "http://schemas.google.com/g/2005#post"); } public String getNextLink() { return Link.find(links, "next"); } static Feed executeGet(HttpTransport transport, PicasaUrl url, Class<? extends Feed> feedClass) throws IOException { url.fields = GData.getFieldsFor(feedClass); HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(feedClass); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.DataUtil; import com.google.api.client.util.Key; import com.google.api.client.xml.atom.AtomContent; import java.io.IOException; import java.util.List; /** * @author Yaniv Inbar */ public class Entry implements Cloneable { @Key("@gd:etag") public String etag; @Key("link") public List<Link> links; @Key public String title; @Override protected Entry clone() { return DataUtil.clone(this); } public void executeDelete(HttpTransport transport) throws IOException { HttpRequest request = transport.buildDeleteRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = this.etag; request.execute().ignore(); } Entry executePatchRelativeToOriginal(HttpTransport transport, Entry original) throws IOException { HttpRequest request = transport.buildPatchRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = this.etag; AtomPatchRelativeToOriginalContent serializer = new AtomPatchRelativeToOriginalContent(); serializer.namespaceDictionary = Util.NAMESPACE_DICTIONARY; serializer.originalEntry = original; serializer.patchedEntry = this; request.content = serializer; return request.execute().parseAs(getClass()); } static Entry executeInsert(HttpTransport transport, Entry entry, String postLink) throws IOException { HttpRequest request = transport.buildPostRequest(); request.setUrl(postLink); AtomContent content = new AtomContent(); content.namespaceDictionary = Util.NAMESPACE_DICTIONARY; content.entry = entry; request.content = content; return request.execute().parseAs(entry.getClass()); } private String getEditLink() { return Link.find(links, "edit"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class PicasaUrl extends GoogleUrl { public static final String ROOT_URL = "https://picasaweb.google.com/data/"; @Key public String kinds; public PicasaUrl(String encodedUrl) { super(encodedUrl); } /** * Constructs a new URL based on the given relative path. * * @param relativePath encoded path relative to the {@link #ROOT_URL} * @return new URL */ public static PicasaUrl relativeToRoot(String relativePath) { return new PicasaUrl(ROOT_URL + relativePath); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Key; import java.io.IOException; /** * @author Yaniv Inbar */ public class AlbumEntry extends Entry { @Key("gphoto:access") public String access; @Key public Category category = Category.newKind("album"); @Override public AlbumEntry clone() { return (AlbumEntry) super.clone(); } public AlbumEntry executePatchRelativeToOriginal(HttpTransport transport, AlbumEntry original) throws IOException { return (AlbumEntry) super.executePatchRelativeToOriginal(transport, original); } public static AlbumEntry executeInsert(HttpTransport transport, AlbumEntry entry, String postLink) throws IOException { return (AlbumEntry) Entry.executeInsert(transport, entry, postLink); } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline; import com.google.api.services.buzz.model.Activity; import com.google.api.services.buzz.model.ActivityFeed; import com.google.api.services.buzz.model.Group; import com.google.api.services.buzz.model.GroupFeed; /** * @author Yaniv Inbar */ class View { static void header(String name) { System.out.println(); System.out.println("============== " + name + " =============="); System.out.println(); } static void display(ActivityFeed feed) { if (feed.items != null) { for (Activity activity : feed.items) { System.out.println(); System.out.println("-----------------------------------------------"); display(activity); } } } static void display(GroupFeed feed) { if (feed.items != null) { for (Group group : feed.items) { System.out.println(); System.out.println("-----------------------------------------------"); display(group); } } } static void display(Activity activity) { System.out.println("Content: " + activity.buzzObject.content); System.out.println("Updated: " + activity.updated); } static void display(Group group) { System.out.println("Title : " + group.title); } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline; import com.google.api.services.buzz.Buzz; import com.google.api.services.buzz.model.Group; import com.google.api.services.buzz.model.GroupFeed; import java.io.IOException; import java.util.Date; /** * @author Yaniv Inbar */ public class GroupActions { private static final String FIELDS_GROUP = "title,id"; private static final String FIELDS_GROUP_FEED = "items(" + FIELDS_GROUP + ")"; static void showGroups(Buzz buzz) throws IOException { View.header("Show Buzz Groups"); Buzz.Groups.List request = buzz.groups.list("@me"); request.put("fields", FIELDS_GROUP_FEED); GroupFeed feed = request.execute(); View.display(feed); } static Group insertGroup(Buzz buzz) throws IOException { View.header("Insert Buzz Group"); Group group = new Group(); group.title = "Temporary Group (" + new Date() + ")"; Buzz.Groups.Insert request = buzz.groups.insert("@me", group); request.put("fields", FIELDS_GROUP); Group result = request.execute(); View.display(result); return result; } static Group updateGroup(Buzz buzz, Group group) throws IOException { View.header("Update Buzz Group"); group.title = group.title + " (updated)"; Buzz.Groups.Update request = buzz.groups.update("@me", group.id.toString(), group); request.put("fields", FIELDS_GROUP); Group result = request.execute(); View.display(result); return result; } static void deleteGroup(Buzz buzz, Group group) throws IOException { View.header("Delete Buzz Group"); buzz.groups.delete("@me", group.id.toString()).execute(); System.out.println("Deleted."); } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline; import com.google.api.services.buzz.Buzz; import com.google.api.services.buzz.model.Activity; import com.google.api.services.buzz.model.ActivityFeed; import com.google.api.services.buzz.model.ActivityObject; import com.google.api.services.buzz.model.ActivityVisibility; import com.google.api.services.buzz.model.ActivityVisibilityEntries; import com.google.api.services.buzz.model.Group; import com.google.common.collect.Lists; import java.io.IOException; /** * @author Yaniv Inbar */ public class ActivityActions { private static final String FIELDS_ACTIVITY = "object/content,updated,id"; private static final String FIELDS_ACTIVITY_FEED = "items(" + FIELDS_ACTIVITY + ")"; static void showActivitiesForConsumption(Buzz buzz) throws IOException { View.header("Show Buzz Activities for Consumption"); Buzz.Activities.List request = buzz.activities.list("@me", "@consumption"); request.fields = FIELDS_ACTIVITY_FEED; ActivityFeed feed = request.execute(); View.display(feed); } static void showPersonalActivities(Buzz buzz) throws IOException { View.header("Show Buzz Personal Activities"); Buzz.Activities.List request = buzz.activities.list("@me", "@self"); request.fields = FIELDS_ACTIVITY_FEED; ActivityFeed feed = request.execute(); View.display(feed); } static Activity insertActivity(Buzz buzz, Group group) throws IOException { View.header("Insert Buzz Activity"); Activity activity = new Activity(); activity.buzzObject = new ActivityObject(); activity.buzzObject.content = "Posted using Google API Client Library for Java " + "(http://code.google.com/p/google-api-java-client/)"; activity.visibility = new ActivityVisibility(); activity.visibility.entries = Lists.newArrayList(); ActivityVisibilityEntries entry = new ActivityVisibilityEntries(); entry.id = group.id; activity.visibility.entries.add(entry); Buzz.Activities.Insert request = buzz.activities.insert("@me", activity); request.put("fields", FIELDS_ACTIVITY); Activity result = request.execute(); View.display(result); return result; } static Activity updateActivity(Buzz buzz, Activity activity) throws IOException { View.header("Update Buzz Activity"); activity.buzzObject.content = activity.buzzObject.content + " (updated)"; Buzz.Activities.Patch request = buzz.activities.patch("@me", "@self", activity.id.toString(), activity); request.fields = FIELDS_ACTIVITY; Activity result = request.execute(); View.display(result); return result; } static void deleteActivity(Buzz buzz, Activity activity) throws IOException { View.header("Delete Buzz Activity"); buzz.activities.delete("@me", "@self", activity.id.toString()).execute(); System.out.println("Deleted."); } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline.oauth; import com.google.api.client.auth.oauth2.draft10.AccessTokenErrorResponse; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import java.awt.Desktop; import java.awt.Desktop.Action; import java.io.IOException; import java.net.URI; /** * Implements OAuth authentication "native" flow recommended for installed clients in which the end * user must grant access in a web browser and then copy a code into the application. * * @author Yaniv Inbar */ public class OAuth2Native { /** * Authorizes the installed application to access user's protected data. * * @param transport HTTP transport * @param jsonFactory JSON factory * @param receiver verification code receiver * @param credentialStore credential store or {@code null} for none * @param browser browser to open in case {@link Desktop#isDesktopSupported()} is {@code false}. * If {@code null} it will simply prompt user to open the URL in their favorite browser. * @param clientId OAuth 2.0 client ID * @param clientSecret OAuth 2.0 client secret * @param scope OAuth 2.0 scope */ public static GoogleAccessProtectedResource authorize(HttpTransport transport, JsonFactory jsonFactory, VerificationCodeReceiver receiver, final CredentialStore credentialStore, String browser, String clientId, String clientSecret, String scope) throws Exception { AccessTokenResponse response = null; if (credentialStore != null) { response = credentialStore.read(); } if (response == null) { try { String redirectUrl = receiver.getRedirectUrl(); launchInBrowser(browser, redirectUrl, clientId, scope); response = exchangeCodeForAccessToken(redirectUrl, receiver, transport, jsonFactory, clientId, clientSecret); if (credentialStore != null) { credentialStore.write(response); } } finally { receiver.stop(); } } final AccessTokenResponse responseForStorage = response; return new GoogleAccessProtectedResource(response.accessToken, transport, jsonFactory, clientId, clientSecret, response.refreshToken) { @Override protected void onAccessToken(String accessToken) { if (credentialStore != null) { responseForStorage.accessToken = accessToken; credentialStore.write(responseForStorage); } } }; } private static void launchInBrowser( String browser, String redirectUrl, String clientId, String scope) throws IOException { String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope).build(); if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { desktop.browse(URI.create(authorizationUrl)); return; } } if (browser != null) { Runtime.getRuntime().exec(new String[] {browser, authorizationUrl}); } else { System.out.println("Open the following address in your favorite browser:"); System.out.println(" " + authorizationUrl); } } private static AccessTokenResponse exchangeCodeForAccessToken(String redirectUrl, VerificationCodeReceiver receiver, HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret) throws IOException { String code = receiver.waitForCode(); try { // exchange code for an access token return new GoogleAuthorizationCodeGrant(new NetHttpTransport(), jsonFactory, clientId, clientSecret, code, redirectUrl).execute(); } catch (HttpResponseException e) { AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class); System.out.println(); System.err.println("Error: " + response.error); System.out.println(); System.exit(1); return null; } } private OAuth2Native() { } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline.oauth; import com.google.api.client.auth.oauth2.draft10.InstalledApp; import java.util.Scanner; /** * Verification code receiver that prompts user to paste the code copied from the browser. * * @author Yaniv Inbar */ public class PromptReceiver implements VerificationCodeReceiver { @Override public String waitForCode() { String code; do { System.out.print("Please enter code: "); code = new Scanner(System.in).nextLine(); } while (code.isEmpty()); return code; } @Override public String getRedirectUrl() { return InstalledApp.OOB_REDIRECT_URI; } @Override public void stop() { } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline.oauth; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Runs a Jetty server on a free port, waiting for OAuth to redirect to it with the verification * code. * <p> * Mostly copied from oacurl by phopkins@google.com. * </p> * * @author Yaniv Inbar */ public final class LocalServerReceiver implements VerificationCodeReceiver { private static final String CALLBACK_PATH = "/Callback"; /** Server or {@code null} before {@link #getRedirectUrl()}. */ private Server server; /** Verification code or {@code null} before received. */ volatile String code; @Override public String getRedirectUrl() throws Exception { int port = getUnusedPort(); server = new Server(port); for (Connector c : server.getConnectors()) { c.setHost("localhost"); } server.addHandler(new CallbackHandler()); server.start(); return "http://localhost:" + port + CALLBACK_PATH; } @Override public synchronized String waitForCode() { try { this.wait(); } catch (InterruptedException exception) { // should not happen } return code; } @Override public void stop() throws Exception { if (server != null) { server.stop(); server = null; } } private static int getUnusedPort() throws IOException { Socket s = new Socket(); s.bind(null); try { return s.getLocalPort(); } finally { s.close(); } } /** * Jetty handler that takes the verifier token passed over from the OAuth provider and stashes it * where {@link #waitForCode} will find it. */ class CallbackHandler extends AbstractHandler { @Override public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException { if (!CALLBACK_PATH.equals(target)) { return; } writeLandingHtml(response); response.flushBuffer(); ((Request) request).setHandled(true); String error = request.getParameter("error"); if (error != null) { System.out.println("Authorization failed. Error=" + error); System.out.println("Quitting."); System.exit(1); } code = request.getParameter("code"); synchronized (LocalServerReceiver.this) { LocalServerReceiver.this.notify(); } } private void writeLandingHtml(HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); PrintWriter doc = response.getWriter(); doc.println("<html>"); doc.println("<head><title>OAuth 2.0 Authentication Token Recieved</title></head>"); doc.println("<body>"); doc.println("Received verification code. Closing..."); doc.println("<script type='text/javascript'>"); // We open "" in the same window to trigger JS ownership of it, which lets // us then close it via JS, at least in Chrome. doc.println("window.setTimeout(function() {"); doc.println(" window.open('', '_self', ''); window.close(); }, 1000);"); doc.println("if (window.opener) { window.opener.checkToken(); }"); doc.println("</script>"); doc.println("</body>"); doc.println("</HTML>"); doc.flush(); } } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline.oauth; /** * Verification code receiver. * * @author Yaniv Inbar */ public interface VerificationCodeReceiver { /** Returns the redirect URL. */ String getRedirectUrl() throws Exception; /** Waits for a verification code. */ String waitForCode(); /** Releases any resources and stops any processes started. */ void stop() throws Exception; }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline.oauth; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; /** * Stores the access and refresh token credentials in a persistent storage like a secured file, a * database or a web service. * * <p> * Ideally one should leverage the OS functionalities to store the access token and refresh token in * encrypted form across invocation of this application. * </p> * * @see <a href="http://msdn.microsoft.com/en-us/library/ms717803(VS.85).aspx">Windows Data * Protection Techniques</a> * @see <a href= * "http://developer.apple.com/library/mac/#documentation/Security/Conceptual/keychainServConcepts/01introduction/introduction.html" * >Keychains on Mac</a> * @author Yaniv Inbar */ public interface CredentialStore { /** * Reads the access and refresh token credentials from store. * * @return stored access and refresh token credentials or {@code null} for none */ AccessTokenResponse read(); /** * Writes the access and refresh token credentials into the store. * * @param response access and refresh token credentials */ void write(AccessTokenResponse response); }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.client.sample.buzz.cmdline.oauth.LocalServerReceiver; import com.google.api.client.sample.buzz.cmdline.oauth.OAuth2Native; import com.google.api.services.buzz.Buzz; import com.google.api.services.buzz.model.Activity; import com.google.api.services.buzz.model.Group; /** * @author Yaniv Inbar */ public class BuzzSample { /** * Set to {@code true} to only perform read-only actions or {@code false} to also do * insert/update/delete. */ private static final boolean READ_ONLY = false; private static void run(JsonFactory jsonFactory) throws Exception { // authorization HttpTransport transport = new NetHttpTransport(); GoogleAccessProtectedResource accessProtectedResource = OAuth2Native.authorize(transport, jsonFactory, new LocalServerReceiver(), null, "google-chrome", OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET, OAuth2ClientCredentials.SCOPE); // set up Buzz final Buzz buzz = new Buzz(transport, accessProtectedResource, jsonFactory); buzz.setApplicationName("Google-BuzzSample/1.0"); buzz.prettyPrint = true; // groups GroupActions.showGroups(buzz); Group group = null; if (!READ_ONLY) { group = GroupActions.insertGroup(buzz); group = GroupActions.updateGroup(buzz, group); } // activities ActivityActions.showActivitiesForConsumption(buzz); ActivityActions.showPersonalActivities(buzz); if (!READ_ONLY) { Activity activity = ActivityActions.insertActivity(buzz, group); activity = ActivityActions.updateActivity(buzz, activity); // clean up ActivityActions.deleteActivity(buzz, activity); GroupActions.deleteGroup(buzz, group); } } public static void main(String[] args) { JsonFactory jsonFactory = new JacksonFactory(); try { try { if (OAuth2ClientCredentials.CLIENT_ID == null || OAuth2ClientCredentials.CLIENT_SECRET == null) { System.err.println( "Please enter your client ID and secret in " + OAuth2ClientCredentials.class); } else { run(jsonFactory); } // success! return; } catch (HttpResponseException e) { if (!e.response.contentType.equals(Json.CONTENT_TYPE)) { System.err.println(e.response.parseAsString()); } else { GoogleJsonError errorResponse = GoogleJsonError.parse(jsonFactory, e.response); System.err.println(errorResponse.code + " Error: " + errorResponse.message); for (ErrorInfo error : errorResponse.errors) { System.err.println(jsonFactory.toString(error)); } } } } catch (Throwable t) { t.printStackTrace(); } System.exit(1); } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.buzz.cmdline; /** * OAuth 2 credentials found in the <a href="https://code.google.com/apis/console">Google apis * console</a>. * * <p> * Once at the Google apis console, click on "Add project...", or if you've already set up a * project, click the arrow next to the project name and click on "Create..." under "Other * projects". For "Buzz API", click on the status switch to flip it to "ON", and agree to the terms * of service. Next, click on "API Access". Click on "Create an OAuth 2.0 Client ID...". Select a * product name and click "Next". Make sure you select "Installed application" and click "Create * client ID". * </p> * * @author Yaniv Inbar */ class OAuth2ClientCredentials { /** Value of the "Client ID" shown under "Client ID for installed applications". */ static final String CLIENT_ID = "359672225969.apps.googleusercontent.com"; /** Value of the "Client secret" shown under "Client ID for installed applications". */ static final String CLIENT_SECRET = "6SGxS5nYm7msXVxeN9cIDlO9"; /** OAuth 2 scope to use (may also append {@code ".readonly"} for the read-only scope). */ static final String SCOPE = "https://www.googleapis.com/auth/buzz"; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa; import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.InputStreamContent; import com.google.api.client.sample.picasa.model.AlbumEntry; import com.google.api.client.sample.picasa.model.AlbumFeed; import com.google.api.client.sample.picasa.model.PhotoEntry; import com.google.api.client.sample.picasa.model.PicasaClient; import com.google.api.client.sample.picasa.model.PicasaUrl; import com.google.api.client.sample.picasa.model.UserFeed; import com.google.api.client.sample.picasa.model.Util; import java.io.File; import java.io.IOException; import java.net.URL; /** * @author Yaniv Inbar */ public class PicasaSample { public static void main(String[] args) { Util.enableLogging(); PicasaClient client = new PicasaClient(); try { client.authorize(); try { UserFeed feed = showAlbums(client); AlbumEntry album = postAlbum(client, feed); postPhoto(client, album); // postVideo(client, album); album = getUpdatedAlbum(client, album); album = updateTitle(client, album); deleteAlbum(client, album); shutdown(client); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); shutdown(client); System.exit(1); } } private static void shutdown(PicasaClient client) { try { client.shutdown(); } catch (IOException e) { e.printStackTrace(); } } private static UserFeed showAlbums(PicasaClient client) throws IOException { // build URL for the default user feed of albums PicasaUrl url = PicasaUrl.relativeToRoot("feed/api/user/default"); // execute GData request for the feed UserFeed feed = client.executeGetUserFeed(url); System.out.println("User: " + feed.author.name); System.out.println("Total number of albums: " + feed.totalResults); // show albums if (feed.albums != null) { for (AlbumEntry album : feed.albums) { showAlbum(client, album); } } return feed; } private static void showAlbum(PicasaClient client, AlbumEntry album) throws IOException { System.out.println(); System.out.println("-----------------------------------------------"); System.out.println("Album title: " + album.title); System.out.println("Updated: " + album.updated); System.out.println("Album ETag: " + album.etag); if (album.summary != null) { System.out.println("Description: " + album.summary); } if (album.numPhotos != 0) { System.out.println("Total number of photos: " + album.numPhotos); PicasaUrl url = new PicasaUrl(album.getFeedLink()); AlbumFeed feed = client.executeGetAlbumFeed(url); for (PhotoEntry photo : feed.photos) { System.out.println(); System.out.println("Photo title: " + photo.title); if (photo.summary != null) { System.out.println("Photo description: " + photo.summary); } System.out.println("Image MIME type: " + photo.mediaGroup.content.type); System.out.println("Image URL: " + photo.mediaGroup.content.url); } } } private static AlbumEntry postAlbum(PicasaClient client, UserFeed feed) throws IOException { System.out.println(); AlbumEntry newAlbum = new AlbumEntry(); newAlbum.access = "private"; newAlbum.title = "A new album"; newAlbum.summary = "My favorite photos"; AlbumEntry album = client.insertAlbum(feed, newAlbum); showAlbum(client, album); return album; } private static PhotoEntry postPhoto(PicasaClient client, AlbumEntry album) throws IOException { String fileName = "picasaweblogo-en_US.gif"; String photoUrlString = "http://www.google.com/accounts/lh2/" + fileName; InputStreamContent content = new InputStreamContent(); content.inputStream = new URL(photoUrlString).openStream(); content.type = "image/jpeg"; PhotoEntry photo = client.executeInsertPhotoEntry(album.getFeedLink(), content, fileName); System.out.println("Posted photo: " + photo.title); return photo; } @SuppressWarnings("unused") private static PhotoEntry postVideo(PicasaClient client, AlbumEntry album) throws IOException { // NOTE: this video is not included in the sample File file = new File("myvideo.3gp"); FileContent imageContent = new FileContent(file); imageContent.type = "video/3gpp"; PhotoEntry video = new PhotoEntry(); video.title = file.getName(); video.summary = "My video"; PhotoEntry result = client.executeInsertPhotoEntryWithMetadata(video, album.getFeedLink(), imageContent); System.out.println("Posted video (pending processing): " + result.title); return result; } private static AlbumEntry getUpdatedAlbum(PicasaClient client, AlbumEntry album) throws IOException { album = client.executeGetAlbum(album.getSelfLink()); showAlbum(client, album); return album; } private static AlbumEntry updateTitle(PicasaClient client, AlbumEntry album) throws IOException { AlbumEntry patched = album.clone(); patched.title = "My favorite web logos"; album = client.executePatchAlbumRelativeToOriginal(patched, album); showAlbum(client, album); return album; } private static void deleteAlbum(PicasaClient client, AlbumEntry album) throws IOException { client.executeDeleteEntry(album); System.out.println(); System.out.println("Album deleted."); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class Category { @Key("@scheme") public String scheme; @Key("@term") public String term; public static Category newKind(String kind) { Category category = new Category(); category.scheme = "http://schemas.google.com/g/2005#kind"; category.term = "http://schemas.google.com/photos/2007#" + kind; return category; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class UserFeed extends Feed { @Key("entry") public List<AlbumEntry> albums; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class MediaContent { @Key("@type") public String type; @Key("@url") public String url; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.common.base.Preconditions; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Class that runs a Jetty server on a free port, waiting for OAuth to redirect to it with the * one-time authorization token. * <p> * Mostly copied from oacurl by phopkins@google.com. * * @author Yaniv Inbar */ public class LoginCallbackServer { private static final String CALLBACK_PATH = "/OAuthCallback"; private int port; private Server server; Map<String, String> verifierMap = new HashMap<String, String>(); public void start() { if (server != null) { throw new IllegalStateException("Server is already started"); } try { port = getUnusedPort(); server = new Server(port); for (Connector c : server.getConnectors()) { c.setHost("localhost"); } server.addHandler(new CallbackHandler()); server.start(); } catch (Exception e) { throw new RuntimeException(e); } } public void stop() throws Exception { if (server != null) { server.stop(); server = null; } } public String getCallbackUrl() { Preconditions.checkArgument(port != 0, "Server is not yet started"); return "http://localhost:" + port + CALLBACK_PATH; } private static int getUnusedPort() throws IOException { Socket s = new Socket(); s.bind(null); try { return s.getLocalPort(); } finally { s.close(); } } /** * Call that blocks until the OAuth provider redirects back here with the verifier token. * * @param requestToken request token * @return The verifier token, or null if there was a timeout. */ public String waitForVerifier(String requestToken) { synchronized (verifierMap) { while (!verifierMap.containsKey(requestToken)) { try { verifierMap.wait(3000); } catch (InterruptedException e) { return null; } } return verifierMap.remove(requestToken); } } /** * Jetty handler that takes the verifier token passed over from the OAuth provider and stashes it * where {@link LoginCallbackServer#waitForVerifier} will find it. */ public class CallbackHandler extends AbstractHandler { public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException { if (!CALLBACK_PATH.equals(target)) { return; } writeLandingHtml(response); response.flushBuffer(); ((Request) request).setHandled(true); String requestToken = request.getParameter("oauth_token"); String verifier = request.getParameter("oauth_verifier"); synchronized (verifierMap) { verifierMap.put(requestToken, verifier); verifierMap.notifyAll(); } } private void writeLandingHtml(HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); PrintWriter doc = response.getWriter(); doc.println("<html>"); doc.println("<head><title>OAuth Authentication Token Recieved</title></head>"); doc.println("<body>"); doc.println("Received verifier token. Closing..."); doc.println("<script type='text/javascript'>"); // We open "" in the same window to trigger JS ownership of it, which lets // us then close it via JS, at least in Chrome. doc.println("window.setTimeout(function() {"); doc.println(" window.open('', '_self', ''); window.close(); }, 1000);"); doc.println("if (window.opener) { window.opener.checkToken(); }"); doc.println("</script>"); doc.println("</body>"); doc.println("</HTML>"); doc.flush(); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Link { @Key("@href") public String href; @Key("@rel") public String rel; public static String find(List<Link> links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Yaniv Inbar */ public class Util { public static final boolean DEBUG = true; public static void enableLogging() { if (DEBUG) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class PhotoEntry extends Entry { @Key public Category category = Category.newKind("photo"); @Key("media:group") public MediaGroup mediaGroup; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class AlbumFeed extends Feed { @Key("entry") public List<PhotoEntry> photos; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Feed { @Key public Author author; @Key("openSearch:totalResults") public int totalResults; @Key("link") public List<Link> links; String getPostLink() { return Link.find(links, "http://schemas.google.com/g/2005#post"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.auth.oauth.OAuthCredentialsResponse; import com.google.api.client.auth.oauth.OAuthHmacSigner; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken; import com.google.api.client.http.HttpTransport; import java.awt.Desktop; import java.awt.Desktop.Action; import java.net.URI; /** * Implements OAuth authentication. * * @author Yaniv Inbar */ public class Auth { private static final String APP_NAME = "Picasa Web Albums Data API Java Client"; private static final String SCOPE = PicasaUrl.ROOT_URL; private static OAuthHmacSigner signer; private static OAuthCredentialsResponse credentials; static OAuthParameters authorize(HttpTransport transport) throws Exception { // callback server LoginCallbackServer callbackServer = null; String verifier = null; String tempToken = null; try { callbackServer = new LoginCallbackServer(); callbackServer.start(); // temporary token GoogleOAuthGetTemporaryToken temporaryToken = new GoogleOAuthGetTemporaryToken(); signer = new OAuthHmacSigner(); signer.clientSharedSecret = "anonymous"; temporaryToken.transport = transport; temporaryToken.signer = signer; temporaryToken.consumerKey = "anonymous"; temporaryToken.scope = SCOPE; temporaryToken.displayName = APP_NAME; temporaryToken.callback = callbackServer.getCallbackUrl(); OAuthCredentialsResponse tempCredentials = temporaryToken.execute(); signer.tokenSharedSecret = tempCredentials.tokenSecret; // authorization URL GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl = new GoogleOAuthAuthorizeTemporaryTokenUrl(); authorizeUrl.temporaryToken = tempToken = tempCredentials.token; String authorizationUrl = authorizeUrl.build(); // launch in browser boolean browsed = false; if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { desktop.browse(URI.create(authorizationUrl)); browsed = true; } } if (!browsed) { String browser = "google-chrome"; Runtime.getRuntime().exec(new String[] {browser, authorizationUrl}); } verifier = callbackServer.waitForVerifier(tempToken); } finally { if (callbackServer != null) { callbackServer.stop(); } } GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken(); accessToken.transport = transport; accessToken.temporaryToken = tempToken; accessToken.signer = signer; accessToken.consumerKey = "anonymous"; accessToken.verifier = verifier; credentials = accessToken.execute(); signer.tokenSharedSecret = credentials.tokenSecret; return createOAuthParameters(); } public static void revoke(HttpTransport transport) { if (credentials != null) { try { GoogleOAuthGetAccessToken.revokeAccessToken(transport, createOAuthParameters()); } catch (Exception e) { e.printStackTrace(System.err); } } } private static OAuthParameters createOAuthParameters() { OAuthParameters authorizer = new OAuthParameters(); authorizer.consumerKey = "anonymous"; authorizer.signer = signer; authorizer.token = credentials.token; return authorizer; } }
Java
/* * Copyright (c) 2011 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent; import com.google.api.client.googleapis.xml.atom.GoogleAtom; import com.google.api.client.http.AbstractInputStreamContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.MultipartRelatedContent; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.xml.atom.AtomContent; import com.google.api.client.http.xml.atom.AtomParser; import com.google.api.client.xml.XmlNamespaceDictionary; import java.io.IOException; /** * @author Yaniv Inbar */ public final class PicasaClient { static final XmlNamespaceDictionary DICTIONARY = new XmlNamespaceDictionary() .set("", "http://www.w3.org/2005/Atom") .set("exif", "http://schemas.google.com/photos/exif/2007") .set("gd", "http://schemas.google.com/g/2005") .set("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#") .set("georss", "http://www.georss.org/georss") .set("gml", "http://www.opengis.net/gml") .set("gphoto", "http://schemas.google.com/photos/2007") .set("media", "http://search.yahoo.com/mrss/") .set("openSearch", "http://a9.com/-/spec/opensearch/1.1/") .set("xml", "http://www.w3.org/XML/1998/namespace"); private final HttpTransport transport = new NetHttpTransport(); private HttpRequestFactory requestFactory; public void authorize() throws Exception { final OAuthParameters parameters = Auth.authorize(transport); // OAuth final MethodOverride override = new MethodOverride(); // needed for PATCH requestFactory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("Google-PicasaSample/1.0"); headers.gdataVersion = "2"; request.headers = headers; request.interceptor = new HttpExecuteInterceptor() { @Override public void intercept(HttpRequest request) throws IOException { override.intercept(request); parameters.intercept(request); } }; AtomParser parser = new AtomParser(); parser.namespaceDictionary = DICTIONARY; request.addParser(parser); } }); } public void shutdown() throws IOException { transport.shutdown(); Auth.revoke(transport); } public void executeDeleteEntry(Entry entry) throws IOException { HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(entry.getEditLink())); request.headers.ifMatch = entry.etag; request.execute().ignore(); } Entry executeGetEntry(PicasaUrl url, Class<? extends Entry> entryClass) throws IOException { url.fields = GoogleAtom.getFieldsFor(entryClass); HttpRequest request = requestFactory.buildGetRequest(url); return request.execute().parseAs(entryClass); } Entry executePatchEntryRelativeToOriginal(Entry updated, Entry original) throws IOException { AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent(); content.namespaceDictionary = DICTIONARY; content.originalEntry = original; content.patchedEntry = updated; HttpRequest request = requestFactory.buildPatchRequest(new GenericUrl(updated.getEditLink()), content); request.headers.ifMatch = updated.etag; return request.execute().parseAs(updated.getClass()); } public AlbumEntry executeGetAlbum(String link) throws IOException { PicasaUrl url = new PicasaUrl(link); return (AlbumEntry) executeGetEntry(url, AlbumEntry.class); } public AlbumEntry executePatchAlbumRelativeToOriginal(AlbumEntry updated, AlbumEntry original) throws IOException { return (AlbumEntry) executePatchEntryRelativeToOriginal(updated, original); } <F extends Feed> F executeGetFeed(PicasaUrl url, Class<F> feedClass) throws IOException { url.fields = GoogleAtom.getFieldsFor(feedClass); HttpRequest request = requestFactory.buildGetRequest(url); return request.execute().parseAs(feedClass); } Entry executeInsert(Feed feed, Entry entry) throws IOException { AtomContent content = new AtomContent(); content.namespaceDictionary = DICTIONARY; content.entry = entry; HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(feed.getPostLink()), content); return request.execute().parseAs(entry.getClass()); } public AlbumFeed executeGetAlbumFeed(PicasaUrl url) throws IOException { url.kinds = "photo"; url.maxResults = 5; return executeGetFeed(url, AlbumFeed.class); } public UserFeed executeGetUserFeed(PicasaUrl url) throws IOException { url.kinds = "album"; url.maxResults = 3; return executeGetFeed(url, UserFeed.class); } public AlbumEntry insertAlbum(UserFeed userFeed, AlbumEntry entry) throws IOException { return (AlbumEntry) executeInsert(userFeed, entry); } public PhotoEntry executeInsertPhotoEntry( String albumFeedLink, InputStreamContent content, String fileName) throws IOException { HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(albumFeedLink), content); GoogleHeaders headers = (GoogleHeaders) request.headers; headers.setSlugFromFileName(fileName); return request.execute().parseAs(PhotoEntry.class); } public PhotoEntry executeInsertPhotoEntryWithMetadata( PhotoEntry photo, String albumFeedLink, AbstractInputStreamContent content) throws IOException { HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(albumFeedLink), null); AtomContent atomContent = new AtomContent(); atomContent.namespaceDictionary = DICTIONARY; atomContent.entry = photo; MultipartRelatedContent multiPartContent = MultipartRelatedContent.forRequest(request); multiPartContent.parts.add(atomContent); multiPartContent.parts.add(content); request.content = multiPartContent; return request.execute().parseAs(PhotoEntry.class); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Data; import com.google.api.client.util.Key; import java.util.List; /** * @author Yaniv Inbar */ public class Entry implements Cloneable { @Key("@gd:etag") public String etag; @Key("link") public List<Link> links; @Key public String summary; @Key public String title; @Key public String updated; public String getFeedLink() { return Link.find(links, "http://schemas.google.com/g/2005#feed"); } public String getSelfLink() { return Link.find(links, "self"); } @Override protected Entry clone() { try { @SuppressWarnings("unchecked") Entry result = (Entry) super.clone(); Data.deepCopy(this, result); return result; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } String getEditLink() { return Link.find(links, "edit"); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class MediaGroup { @Key("media:content") public MediaContent content; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class Author { @Key public String name; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class PicasaUrl extends GoogleUrl { public static final String ROOT_URL = "https://picasaweb.google.com/data/"; @Key("max-results") public Integer maxResults; @Key public String kinds; public PicasaUrl(String url) { super(url); if (Util.DEBUG) { this.prettyprint = true; } } /** * Constructs a new Picasa Web Albums URL based on the given relative path. * * @param relativePath encoded path relative to the {@link #ROOT_URL} * @return new Picasa URL */ public static PicasaUrl relativeToRoot(String relativePath) { return new PicasaUrl(ROOT_URL + relativePath); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.picasa.model; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class AlbumEntry extends Entry { @Key("gphoto:access") public String access; @Key public Category category = Category.newKind("album"); @Key("gphoto:numphotos") public int numPhotos; @Override public AlbumEntry clone() { return (AlbumEntry) super.clone(); } }
Java
package com.google.api.client.sample.tasks.v1.android; import com.google.api.client.extensions.android2.AndroidHttp; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.tasks.v1.Tasks; import com.google.api.services.tasks.v1.model.Task; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Sample for Tasks API on Android. * It shows how to authenticate using OAuth2, and get the list of tasks. * <p> * To enable logging of HTTP requests/responses, change {@link #LOGGING_LEVEL} to * {@link Level#CONFIG} or {@link Level#ALL} and run this command: * </p> * * <pre> adb shell setprop log.tag.HttpTransport DEBUG * </pre> * * @author Johan Euphrosine (based on Yaniv Inbar Buzz sample) */ public class TasksSample extends ListActivity { /** Logging level for HTTP requests/responses. */ private static Level LOGGING_LEVEL = Level.OFF; private static final String TAG = "TasksSample"; private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/tasks"; private static final String PREF = "MyPrefs"; private static final int DIALOG_ACCOUNTS = 0; private static final int MENU_ACCOUNTS = 0; public static final int REQUEST_AUTHENTICATE = 0; private final HttpTransport transport = AndroidHttp.newCompatibleTransport(); Tasks service; GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(null); // TODO: save auth token in preferences public GoogleAccountManager accountManager; // Follow API access Instructions in instructions.html // And replace INSERT_YOUR_API_KEY with your generated API Key. static final String API_KEY = "INSERT_YOUR_API_KEY"; @Override public void onCreate(Bundle savedInstanceState) { service = new Tasks(transport, accessProtectedResource, new JacksonFactory()); service.accessKey = API_KEY; service.setApplicationName("Google-TasksSample/1.0"); super.onCreate(savedInstanceState); accountManager = new GoogleAccountManager(this); Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL); gotAccount(false); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ACCOUNTS: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Google account"); final Account[] accounts = accountManager.getAccounts(); final int size = accounts.length; String[] names = new String[size]; for (int i = 0; i < size; i++) { names[i] = accounts[i].name; } builder.setItems(names, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { gotAccount(accounts[which]); } }); return builder.create(); } return null; } void gotAccount(boolean tokenExpired) { SharedPreferences settings = getSharedPreferences(PREF, 0); String accountName = settings.getString("accountName", null); Account account = accountManager.getAccountByName(accountName); if (account != null) { if (tokenExpired) { accountManager.invalidateAuthToken(accessProtectedResource.getAccessToken()); accessProtectedResource.setAccessToken(null); } gotAccount(account); return; } showDialog(DIALOG_ACCOUNTS); } void gotAccount(final Account account) { SharedPreferences settings = getSharedPreferences(PREF, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("accountName", account.name); editor.commit(); accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { Bundle bundle = future.getResult(); if (bundle.containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT); intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK); startActivityForResult(intent, REQUEST_AUTHENTICATE); } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) { accessProtectedResource.setAccessToken(bundle .getString(AccountManager.KEY_AUTHTOKEN)); onAuthToken(); } } catch (Exception e) { handleException(e); } } }, null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_AUTHENTICATE: if (resultCode == RESULT_OK) { gotAccount(false); } else { showDialog(DIALOG_ACCOUNTS); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ACCOUNTS, 0, "Switch Account"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ACCOUNTS: showDialog(DIALOG_ACCOUNTS); return true; } return false; } void handleException(Exception e) { e.printStackTrace(); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).response; int statusCode = response.statusCode; try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } // TODO: should only try this once to avoid infinite loop if (statusCode == 401) { gotAccount(true); return; } } Log.e(TAG, e.getMessage(), e); } void onAuthToken() { try { List<String> tasks = new ArrayList<String>(); for (Task task : service.tasks.list("@default").execute().items) { tasks.add(task.title); } setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, tasks)); } catch (IOException e) { handleException(e); } setContentView(R.layout.main); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.diacritization; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.googleapis.json.JsonCParser; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import java.io.IOException; /** * @author Yaniv Inbar */ public class DiacritizationSample { public static void main(String[] args) { Debug.enableLogging(); HttpTransport transport = setUpTransport(); try { try { diacritize(transport, "مرحبا العالم"); } catch (HttpResponseException e) { System.err.println(e.response.parseAsString()); throw e; } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } private static HttpTransport setUpTransport() { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Google-DiacritizationSample/1.0"); transport.addParser(new JsonCParser()); return transport; } private static void diacritize(HttpTransport transport, String message) throws IOException { System.out.println("Arabic message: " + message); HttpRequest request = transport.buildGetRequest(); DiacritizationUrl url = new DiacritizationUrl(); url.message = message; request.url = url; DiacritizationResponse response = request.execute().parseAs(DiacritizationResponse.class); System.out.println( "Diacritized Arabic message: " + response.diacritizedText); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.diacritization; import com.google.api.client.googleapis.GoogleUrl; import com.google.api.client.util.Key; /** * Diacritization URL builder. * * @author Yaniv Inbar */ public final class DiacritizationUrl extends GoogleUrl { @Key public String lang = "ar"; @Key public String message; @Key("last_letter") public boolean lastLetter; /** Constructs a new Diacritization URL. */ public DiacritizationUrl() { super("https://www.googleapis.com/language/diacritize/v1"); if (Debug.ENABLED) { prettyprint = true; } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.diacritization; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Yaniv Inbar */ public class Debug { public static final boolean ENABLED = false; public static void enableLogging() { if (ENABLED) { Logger logger = Logger.getLogger("com.google.api.client"); logger.setLevel(Level.CONFIG); logger.addHandler(new Handler() { @Override public void close() throws SecurityException { } @Override public void flush() { } @Override public void publish(LogRecord record) { // default ConsoleHandler will take care of >= INFO if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.diacritization; import com.google.api.client.util.Key; /** * @author Yaniv Inbar */ public class DiacritizationResponse { @Key("diacritized_text") public String diacritizedText; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.AuthenticationException; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.RootPanel; import java.util.List; /** * Main entry-point for the Calendar GWT sample. * * @author Yaniv Inbar */ public class CalendarGwtSample implements EntryPoint { CalendarsFrame calendarsFrame; List<GwtCalendar> calendars; static final CalendarServiceAsync SERVICE = GWT.create(CalendarService.class); public void onModuleLoad() { calendarsFrame = new CalendarsFrame(this); RootPanel.get("main").add(calendarsFrame); // "loading calendars..." FlexTable calendarsTable = calendarsFrame.calendarsTable; calendarsTable.setText(0, 0, "Loading Calendars..."); calendarsTable.getCellFormatter().addStyleName(0, 0, "methodsHeaderRow"); // import calendars SERVICE.getCalendars(new AsyncCallback<List<GwtCalendar>>() { @Override public void onFailure(Throwable caught) { handleFailure(caught); } @Override public void onSuccess(List<GwtCalendar> result) { calendars = result; calendarsFrame.addButton.setEnabled(true); refreshTable(); } }); } void refreshTable() { FlexTable calendarsTable = calendarsFrame.calendarsTable; calendarsTable.removeAllRows(); calendarsTable.setText(0, 1, "Calendar Title"); calendarsTable.setText(0, 2, "Updated"); calendarsTable.getCellFormatter().addStyleName(0, 1, "methodsHeaderRow"); calendarsTable.getCellFormatter().addStyleName(0, 2, "methodsHeaderRow"); for (int i = 0; i < calendars.size(); i++) { GwtCalendar calendar = calendars.get(i); calendarsTable.setWidget(i + 1, 0, new CalendarButtons(this, calendar, i)); calendarsTable.setText(i + 1, 1, calendar.title); calendarsTable.setText(i + 1, 2, calendar.updated); } } static void handleFailure(Throwable caught) { if (caught instanceof AuthenticationException) { Window.Location.reload(); } else { caught.printStackTrace(); Window.alert("ERROR: " + caught.getMessage()); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HorizontalPanel; /** * Delete dialog content. * * @author Yaniv Inbar */ public class DeleteDialogContent extends Composite { interface MyUiBinder extends UiBinder<HorizontalPanel, DeleteDialogContent> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField Button deleteButton; @UiField Button cancelButton; private final DialogBox dialogBox; private final GwtCalendar calendar; final CalendarGwtSample main; final int calendarIndex; DeleteDialogContent( CalendarGwtSample main, DialogBox dialogBox, GwtCalendar calendar, int calendarIndex) { this.main = main; this.dialogBox = dialogBox; this.calendar = calendar; this.calendarIndex = calendarIndex; initWidget(uiBinder.createAndBindUi(this)); } @SuppressWarnings("unchecked") @UiHandler("deleteButton") void handleDelete(ClickEvent e) { dialogBox.hide(); CalendarGwtSample.SERVICE.delete(calendar, new AsyncCallback() { @Override public void onFailure(Throwable caught) { CalendarGwtSample.handleFailure(caught); } @Override public void onSuccess(Object result) { main.calendars.remove(calendarIndex); main.refreshTable(); } }); } @UiHandler("cancelButton") void handleCancel(ClickEvent e) { dialogBox.hide(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import java.io.IOException; import java.util.List; /** * GWT RPC service for calendars. * * @author Yaniv Inbar */ @RemoteServiceRelativePath("calendarService") public interface CalendarService extends RemoteService { List<GwtCalendar> getCalendars() throws IOException; void delete(GwtCalendar calendar) throws IOException; GwtCalendar insert(GwtCalendar calendar) throws IOException; GwtCalendar update(GwtCalendar original, GwtCalendar updated) throws IOException; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.TextBox; /** * Update dialog content. * * @author Yaniv Inbar */ public class UpdateDialogContent extends Composite { interface MyUiBinder extends UiBinder<HorizontalPanel, UpdateDialogContent> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField TextBox textBox; @UiField Button updateButton; @UiField Button cancelButton; private final DialogBox dialogBox; private final GwtCalendar calendar; final CalendarGwtSample main; final int calendarIndex; UpdateDialogContent( CalendarGwtSample main, DialogBox dialogBox, GwtCalendar calendar, int calendarIndex) { this.main = main; this.dialogBox = dialogBox; this.calendar = calendar; this.calendarIndex = calendarIndex; initWidget(uiBinder.createAndBindUi(this)); textBox.setText(calendar.title); textBox.selectAll(); } @UiHandler("updateButton") void handleUpdate(ClickEvent e) { dialogBox.hide(); GwtCalendar updated = new GwtCalendar(); updated.editLink = calendar.editLink; updated.title = textBox.getText(); updated.updated = calendar.updated; CalendarGwtSample.SERVICE.update(calendar, updated, new AsyncCallback<GwtCalendar>() { @Override public void onFailure(Throwable caught) { CalendarGwtSample.handleFailure(caught); } @Override public void onSuccess(GwtCalendar result) { main.calendars.set(calendarIndex, result); main.refreshTable(); } }); } @UiHandler("cancelButton") void handleCancel(ClickEvent e) { dialogBox.hide(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Main calendars UI frame. * * @author Yaniv Inbar */ public class CalendarsFrame extends Composite { interface MyUiBinder extends UiBinder<VerticalPanel, CalendarsFrame> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField TextBox addTextBox; @UiField Button addButton; @UiField FlexTable calendarsTable; final CalendarGwtSample main; public CalendarsFrame(CalendarGwtSample main) { this.main = main; initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("addButton") void handleAdd(ClickEvent e) { GwtCalendar calendar = new GwtCalendar(); calendar.title = addTextBox.getText(); if (calendar.title != null) { addTextBox.setText(""); CalendarGwtSample.SERVICE.insert(calendar, new AsyncCallback<GwtCalendar>() { @Override public void onFailure(Throwable caught) { CalendarGwtSample.handleFailure(caught); } @Override public void onSuccess(GwtCalendar result) { main.calendars.add(result); main.refreshTable(); } }); } } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HorizontalPanel; /** * Buttons for a calendar. * * @author Yaniv Inbar */ public class CalendarButtons extends Composite { interface MyUiBinder extends UiBinder<HorizontalPanel, CalendarButtons> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField Button deleteButton; @UiField Button updateButton; private final int calendarIndex; private final CalendarGwtSample main; private final GwtCalendar calendar; public CalendarButtons(CalendarGwtSample main, GwtCalendar calendar, int calendarIndex) { this.main = main; this.calendar = calendar; this.calendarIndex = calendarIndex; initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("deleteButton") void handleDelete(ClickEvent e) { DialogBox dialogBox = new DialogBox(); dialogBox.setAnimationEnabled(true); dialogBox.setText("Are you sure you want to permanently delete the calendar?"); DeleteDialogContent content = new DeleteDialogContent(main, dialogBox, calendar, calendarIndex); dialogBox.add(content); dialogBox.show(); } @UiHandler("updateButton") void handleUpdate(ClickEvent e) { DialogBox dialogBox = new DialogBox(); dialogBox.setAnimationEnabled(true); dialogBox.setText("Update Calendar Title:"); UpdateDialogContent content = new UpdateDialogContent(main, dialogBox, calendar, calendarIndex); dialogBox.add(content); dialogBox.show(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.client; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.gwt.user.client.rpc.AsyncCallback; import java.util.List; /** * Async interface for GWT RPC service for calendars. * * @author Yaniv Inbar */ public interface CalendarServiceAsync { void getCalendars(AsyncCallback<List<GwtCalendar>> callback); void delete(GwtCalendar calendar, AsyncCallback<Void> callback); void insert(GwtCalendar calendar, AsyncCallback<GwtCalendar> callback); void update(GwtCalendar original, GwtCalendar updated, AsyncCallback<GwtCalendar> callback); }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.shared; import java.io.IOException; /** * Authentication failed exception. * * @author Yaniv Inbar */ @SuppressWarnings("serial") public class AuthenticationException extends IOException { }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.shared; import java.io.Serializable; /** * Calendar class used for GWT RPC. * * @author Yaniv Inbar */ @SuppressWarnings("serial") public class GwtCalendar implements Serializable { public String editLink; public String title; public String updated; }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import com.google.appengine.api.users.UserServiceFactory; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * OAuth per-user credentials store. * * @author Yaniv Inbar */ @PersistenceCapable public final class UserCredentials { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) String userId; @Persistent String gsessionid; @Persistent boolean temporary; @Persistent String token; @Persistent String tokenSecret; UserCredentials makePersistent() { return PersistenceUtil.makePersistent(this); } static String getCurrentUserId() { return UserServiceFactory.getUserService().getCurrentUser().getUserId(); } static UserCredentials forCurrentUser() { PersistenceManager manager = PersistenceUtil.getPersistenceManager(); try { return forCurrentUser(manager); } finally { manager.close(); } } static void deleteCurrentUserFromStore() { PersistenceManager manager = PersistenceUtil.getPersistenceManager(); try { UserCredentials cred = forCurrentUser(manager); if (cred != null) { manager.deletePersistent(cred); } } finally { manager.close(); } } private static UserCredentials forCurrentUser(PersistenceManager manager) { @SuppressWarnings("unchecked") List<UserCredentials> creds = (List<UserCredentials>) manager.newQuery( UserCredentials.class, "userId == '" + getCurrentUserId() + "'").execute(); return creds.isEmpty() ? null : creds.get(0); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import com.google.api.client.xml.XmlNamespaceDictionary; /** * Namespaces used by the Google Calendar Data API, mapped from XML namespace alias to XML namespace * URI. * * @author Yaniv Inbar */ class Namespace { static final XmlNamespaceDictionary DICTIONARY = new XmlNamespaceDictionary().set("", "http://www.w3.org/2005/Atom"); private Namespace() { } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import com.google.api.client.http.HttpTransport; import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.ArrayList; /** * Calendar entry. * * @author Yaniv Inbar */ public class CalendarEntry extends Entry { public CalendarEntry() { } CalendarEntry(GwtCalendar calendar) { Preconditions.checkNotNull(calendar); links = new ArrayList<Link>(); links.add(Link.editLink(calendar.editLink)); title = calendar.title; updated = calendar.updated; } GwtCalendar toCalendar() { GwtCalendar result = new GwtCalendar(); result.editLink = getEditLink(); result.title = title; result.updated = updated; return result; } String getEventFeedLink() { return Link.find(links, "http://schemas.google.com/gCal/2005#eventFeed"); } @Override protected CalendarEntry clone() { return (CalendarEntry) super.clone(); } @Override CalendarEntry executeInsert(HttpTransport transport, CalendarUrl url) throws IOException { return (CalendarEntry) super.executeInsert(transport, url); } CalendarEntry executePatchRelativeToOriginal(HttpTransport transport, CalendarEntry original) throws IOException { return (CalendarEntry) super.executePatchRelativeToOriginal(transport, original); } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; /** * Utility class for JDO persistence. * * @author Yaniv Inbar */ class PersistenceUtil { /** Persistence manager factory instance. */ private static final PersistenceManagerFactory FACTORY = JDOHelper.getPersistenceManagerFactory("transactions-optional"); static PersistenceManager getPersistenceManager() { return FACTORY.getPersistenceManager(); } static <T> T makePersistent(T object) { PersistenceManager manager = getPersistenceManager(); try { return manager.makePersistent(object); } finally { manager.close(); } } private PersistenceUtil() { } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import com.google.api.client.util.Key; import java.util.List; /** * Generic Atom link. * * @author Yaniv Inbar */ public class Link { @Key("@href") String href; @Key("@rel") String rel; static Link editLink(String href) { Link link = new Link(); link.rel = "edit"; link.href = href; return link; } static String find(List<Link> links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } }
Java
/* * Copyright (c) 2010 Google Inc. * * 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. */ package com.google.api.client.sample.calendar.v2.appengine.server; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl; import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponseException; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Google Calendar Data API App Engine sample. * * @author Yaniv Inbar */ @SuppressWarnings("serial") public class CalendarAppEngineSample extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String fullUrl = Auth.getFullURL(request); // check if we have user credentials UserCredentials userCredentials = UserCredentials.forCurrentUser(); if (userCredentials == null) { // get the temporary OAuth token GoogleOAuthGetTemporaryToken requestToken = new GoogleOAuthGetTemporaryToken(); requestToken.displayName = Constants.APP_NAME; requestToken.signer = Auth.createSigner(null); requestToken.consumerKey = Constants.ENTER_DOMAIN; requestToken.scope = CalendarUrl.ROOT_URL; GenericUrl url = new GenericUrl(fullUrl); url.setRawPath("/access_granted"); requestToken.callback = url.build(); userCredentials = Auth.executeGetToken(requestToken, null); } // have a temporary token? if (userCredentials.temporary) { // redirect to grant access UI GoogleOAuthAuthorizeTemporaryTokenUrl url = new GoogleOAuthAuthorizeTemporaryTokenUrl(); url.temporaryToken = userCredentials.token; response.sendRedirect(url.build()); return; } writeHtmlContent(request, response, fullUrl); } catch (HttpResponseException e) { throw Auth.newIOException(e); } } /** * Write GWT HTML hosted content. */ private static void writeHtmlContent( HttpServletRequest request, HttpServletResponse response, String fullUrl) throws IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.println("<!doctype html><html><head>"); writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.println("<title>" + Constants.APP_NAME + "</title>"); writer.println("<link type=\"text/css\" rel=\"stylesheet\" href=\"" + Constants.GWT_MODULE_NAME + ".css\">"); writer.println("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"" + Constants.GWT_MODULE_NAME + "/" + Constants.GWT_MODULE_NAME + ".nocache.js\"></script>"); writer.println("</head><body>"); UserService userService = UserServiceFactory.getUserService(); writer.println("<div class=\"header\"><b>" + request.getUserPrincipal().getName() + "</b> | " + "<a href=\"" + userService.createLogoutURL(fullUrl) + "\">Log out</a> | " + "<a href=\"http://code.google.com/p/google-api-java-client/source/browse?repo=" + "samples#hg/calendar-v2-atom-oauth-appengine-sample\">See source code for " + "this sample</a></div>"); writer.println("<div id=\"main\"/>"); writer.println("</body></html>"); } }
Java