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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities for Google's Atom XML implementation (see detailed package specification). * * <h2>Package Specification</h2> * * <p> * User-defined Partial XML data models allow you to defined Plain Old Java Objects (POJO's) to * define how the library should parse/serialize XML. Each field that should be included must have * an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility * (private, package private, protected, or public) and must not be static. * </p> * * <p> * The optional value parameter of this @{@link com.google.api.client.util.Key} annotation specifies * the XPath name to use to represent the field. For example, an XML attribute <code>a</code> has an * XPath name of <code>@a</code>, an XML element <code>&lt;a&gt;</code> has an XPath name of <code> *a * </code>, and an XML text content has an XPath name of <code>text()</code>. These are named based * on their usage with the <a * href="http://code.google.com/apis/gdata/docs/2.0/reference.html#PartialResponse">partial * response/update syntax</a> for Google API's. If the @{@link com.google.api.client.util.Key} * annotation is missing, the default is to use the Atom XML namespace and the Java field's name as * the local XML name. By default, the field name is used as the JSON key. Any unrecognized XML is * normally simply ignored and not stored. If the ability to store unknown keys is important, use * {@link com.google.api.client.xml.GenericXml}. * </p> * * <p> * Let's take a look at a typical partial Atom XML album feed from the Picasa Web Albums Data API: * </p> * * <pre><code> &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gphoto='http://schemas.google.com/photos/2007'&gt; &lt;link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://picasaweb.google.com/data/feed/api/user/liz' /&gt; &lt;author&gt; &lt;name&gt;Liz&lt;/name&gt; &lt;/author&gt; &lt;openSearch:totalResults&gt;1&lt;/openSearch:totalResults&gt; &lt;entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'&gt; &lt;category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/photos/2007#album' /&gt; &lt;title&gt;lolcats&lt;/title&gt; &lt;summary&gt;Hilarious Felines&lt;/summary&gt; &lt;gphoto:access&gt;public&lt;/gphoto:access&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> * * <p> * Here's one possible way to design the Java data classes for this (each class in its own Java * file): * </p> * * <pre><code> import com.google.api.client.util.*; import java.util.List; public class Link { &#64;Key("&#64;href") public String href; &#64;Key("&#64;rel") public String rel; public static String find(List&lt;Link&gt; links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } } public class Category { &#64;Key("&#64;scheme") public String scheme; &#64;Key("&#64;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; } } public class AlbumEntry { &#64;Key public String summary; &#64;Key public String title; &#64;Key("gphoto:access") public String access; public Category category = newKind("album"); private String getEditLink() { return Link.find(links, "edit"); } } public class Author { &#64;Key public String name; } public class AlbumFeed { &#64;Key public Author author; &#64;Key("openSearch:totalResults") public int totalResults; &#64;Key("entry") public List&lt;AlbumEntry&gt; photos; &#64;Key("link") public List&lt;Link&gt; links; private String getPostLink() { return Link.find(links, "http://schemas.google.com/g/2005#post"); } } </code></pre> * * <p> * You can also use the @{@link com.google.api.client.util.Key} annotation to defined query * parameters for a URL. For example: * </p> * * <pre><code> public class PicasaUrl extends GoogleUrl { &#64;Key("max-results") public Integer maxResults; &#64;Key public String kinds; public PicasaUrl(String url) { super(url); } public static PicasaUrl fromRelativePath(String relativePath) { PicasaUrl result = new PicasaUrl(PicasaWebAlbums.ROOT_URL); result.path += relativePath; return result; } } </code></pre> * * <p> * To work with a Google API, you first need to set up the * {@link com.google.api.client.http.HttpTransport}. For example: * </p> * * <pre><code> private static HttpTransport setUpTransport() throws IOException { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); HttpHeaders headers = new HttpHeaders(); headers.setApplicationName("Google-PicasaSample/1.0"); headers.gdataVersion = "2"; AtomParser parser = new AtomParser(); parser.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; transport.addParser(parser); // insert authentication code... return transport; } </code></pre> * * <p> * Now that we have a transport, we can execute a partial GET request to the Picasa Web Albums API * and parse the result: * </p> * * <pre><code> public static AlbumFeed executeGet(HttpTransport transport, PicasaUrl url) throws IOException { url.fields = GoogleAtom.getFieldsFor(AlbumFeed.class); url.kinds = "photo"; url.maxResults = 5; HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(AlbumFeed.class); } </code></pre> * * <p> * If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute} * method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an * {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a * success response inside of a catch block. For example: * </p> * * <pre><code> try { ... } catch (HttpResponseException e) { if (e.response.getParser() != null) { Error error = e.response.parseAs(Error.class); // process error response } else { String errorContentString = e.response.parseAsString(); // process error response as string } throw e; } </code></pre> * * <p> * To update an album, we use the transport to execute an efficient partial update request using the * PATCH method to the Picasa Web Albums API: * </p> * * <pre><code> public AlbumEntry executePatchRelativeToOriginal(HttpTransport transport, AlbumEntry original) throws IOException { HttpRequest request = transport.buildPatchRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = etag; AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent(); content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; content.originalEntry = original; content.patchedEntry = this; request.content = content; return request.execute().parseAs(AlbumEntry.class); } private static AlbumEntry updateTitle(HttpTransport transport, AlbumEntry album) throws IOException { AlbumEntry patched = album.clone(); patched.title = "An alternate title"; return patched.executePatchRelativeToOriginal(transport, album); } </code></pre> * * <p> * To insert an album, we use the transport to execute a POST request to the Picasa Web Albums API: * </p> * * <pre><code> public AlbumEntry insertAlbum(HttpTransport transport, AlbumEntry entry) throws IOException { HttpRequest request = transport.buildPostRequest(); request.setUrl(getPostLink()); AtomContent content = new AtomContent(); content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; content.entry = entry; request.content = content; return request.execute().parseAs(AlbumEntry.class); } </code></pre> * * <p> * To delete an album, we use the transport to execute a DELETE request to the Picasa Web Albums * API: * </p> * * <pre><code> public void executeDelete(HttpTransport transport) throws IOException { HttpRequest request = transport.buildDeleteRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = etag; request.execute().ignore(); } </code></pre> * * <p> * NOTE: As you might guess, the library uses reflection to populate the user-defined data model. * It's not quite as fast as writing the wire format parsing code yourself can potentially be, but * it's a lot easier. * </p> * * <p> * NOTE: If you prefer to use your favorite XML parsing library instead (there are many of them), * that's supported as well. Just call {@link com.google.api.client.http.HttpRequest#execute()} and * parse the returned byte stream. * </p> * * @since 1.0 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.xml.atom;
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.googleapis.xml.atom; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.xml.AbstractXmlHttpContent; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import com.google.api.client.xml.XmlNamespaceDictionary; import com.google.api.client.xml.atom.Atom; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.Map; /** * {@link Beta} <br/> * Serializes an optimal Atom XML PATCH HTTP content based on the data key/value mapping object for * an Atom entry, by comparing the original value to the patched value. * * <p> * Sample usage: * </p> * * <pre> * <code> static void setContent(HttpRequest request, XmlNamespaceDictionary namespaceDictionary, Object originalEntry, Object patchedEntry) { request.setContent( new AtomPatchRelativeToOriginalContent(namespaceDictionary, originalEntry, patchedEntry)); } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class AtomPatchRelativeToOriginalContent extends AbstractXmlHttpContent { /** Key/value pair data for the updated/patched Atom entry. */ private final Object patchedEntry; /** Key/value pair data for the original unmodified Atom entry. */ private final Object originalEntry; /** * @param namespaceDictionary XML namespace dictionary * @since 1.5 */ public AtomPatchRelativeToOriginalContent( XmlNamespaceDictionary namespaceDictionary, Object originalEntry, Object patchedEntry) { super(namespaceDictionary); this.originalEntry = Preconditions.checkNotNull(originalEntry); this.patchedEntry = Preconditions.checkNotNull(patchedEntry); } @Override protected void writeTo(XmlSerializer serializer) throws IOException { Map<String, Object> patch = GoogleAtom.computePatch(patchedEntry, originalEntry); getNamespaceDictionary().serialize(serializer, Atom.ATOM_NAMESPACE, "entry", patch); } @Override public AtomPatchRelativeToOriginalContent setMediaType(HttpMediaType mediaType) { super.setMediaType(mediaType); return this; } /** * Returns the data key name/value pairs for the updated/patched Atom entry. * * @since 1.5 */ public final Object getPatchedEntry() { return patchedEntry; } /** * Returns the data key name/value pairs for the original unmodified Atom entry. * * @since 1.5 */ public final Object getOriginalEntry() { return originalEntry; } }
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.googleapis.xml.atom; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.xml.atom.AtomContent; import com.google.api.client.util.Beta; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; /** * {@link Beta} <br/> * Serializes Atom XML PATCH HTTP content based on the data key/value mapping object for an Atom * entry. * * <p> * Default value for {@link #getType()} is {@link Xml#MEDIA_TYPE}. * </p> * * <p> * Sample usage: * </p> * * <pre> *<code> static void setContent( HttpRequest request, XmlNamespaceDictionary namespaceDictionary, Object patchEntry) { request.setContent(new AtomPatchContent(namespaceDictionary, patchEntry)); } * </code> * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class AtomPatchContent extends AtomContent { /** * @param namespaceDictionary XML namespace dictionary * @param patchEntry key/value pair data for the Atom PATCH entry * @since 1.5 */ public AtomPatchContent(XmlNamespaceDictionary namespaceDictionary, Object patchEntry) { super(namespaceDictionary, patchEntry, true); setMediaType(new HttpMediaType(Xml.MEDIA_TYPE)); } @Override public AtomPatchContent setMediaType(HttpMediaType mediaType) { super.setMediaType(mediaType); return this; } }
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.googleapis.xml.atom; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.Types; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; import com.google.api.client.xml.atom.AbstractAtomFeedParser; import com.google.api.client.xml.atom.Atom; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.HashMap; /** * {@link Beta} <br/> * GData Atom feed pull parser when the entry class can be computed from the kind. * * @param <T> feed type * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class MultiKindFeedParser<T> extends AbstractAtomFeedParser<T> { private final HashMap<String, Class<?>> kindToEntryClassMap = new HashMap<String, Class<?>>(); /** * @param namespaceDictionary XML namespace dictionary * @param parser XML pull parser to use * @param inputStream input stream to read * @param feedClass feed class to parse */ MultiKindFeedParser(XmlNamespaceDictionary namespaceDictionary, XmlPullParser parser, InputStream inputStream, Class<T> feedClass) { super(namespaceDictionary, parser, inputStream, feedClass); } /** Sets the entry classes to use when parsing. */ public void setEntryClasses(Class<?>... entryClasses) { int numEntries = entryClasses.length; HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap; for (int i = 0; i < numEntries; i++) { Class<?> entryClass = entryClasses[i]; ClassInfo typeInfo = ClassInfo.of(entryClass); Field field = typeInfo.getField("@gd:kind"); if (field == null) { throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName()); } Object entry = Types.newInstance(entryClass); String kind = (String) FieldInfo.getFieldValue(field, entry); if (kind == null) { throw new IllegalArgumentException( "missing value for @gd:kind field in " + entryClass.getName()); } kindToEntryClassMap.put(kind, entryClass); } } @Override protected Object parseEntryInternal() throws IOException, XmlPullParserException { XmlPullParser parser = getParser(); String kind = parser.getAttributeValue(GoogleAtom.GD_NAMESPACE, "kind"); Class<?> entryClass = this.kindToEntryClassMap.get(kind); if (entryClass == null) { throw new IllegalArgumentException("unrecognized kind: " + kind); } Object result = Types.newInstance(entryClass); Xml.parseElement(parser, result, getNamespaceDictionary(), null); return result; } /** * Parses the given HTTP response using the given feed class and entry classes. * * @param <T> feed type * @param <E> entry type * @param response HTTP response * @param namespaceDictionary XML namespace dictionary * @param feedClass feed class * @param entryClasses entry class * @return Atom multi-kind feed pull parser * @throws IOException I/O exception * @throws XmlPullParserException XML pull parser exception */ public static <T, E> MultiKindFeedParser<T> create(HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses) throws IOException, XmlPullParserException { InputStream content = response.getContent(); try { Atom.checkContentType(response.getContentType()); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); MultiKindFeedParser<T> result = new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass); result.setEntryClasses(entryClasses); return result; } finally { content.close(); } } }
Java
/* * Copyright (c) 2013 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.googleapis.media; import com.google.api.client.http.HttpIOExceptionHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * MediaUpload error handler handles an {@link IOException} and an abnormal HTTP response by calling * to {@link MediaHttpUploader#serverErrorCallback()}. * * @author Eyal Peled */ @Beta class MediaUploadErrorHandler implements HttpUnsuccessfulResponseHandler, HttpIOExceptionHandler { static final Logger LOGGER = Logger.getLogger(MediaUploadErrorHandler.class.getName()); /** The uploader to callback on if there is a server error. */ private final MediaHttpUploader uploader; /** The original {@link HttpIOExceptionHandler} of the HTTP request. */ private final HttpIOExceptionHandler originalIOExceptionHandler; /** The original {@link HttpUnsuccessfulResponseHandler} of the HTTP request. */ private final HttpUnsuccessfulResponseHandler originalUnsuccessfulHandler; /** * Constructs a new instance from {@link MediaHttpUploader} and {@link HttpRequest}. */ public MediaUploadErrorHandler(MediaHttpUploader uploader, HttpRequest request) { this.uploader = Preconditions.checkNotNull(uploader); originalIOExceptionHandler = request.getIOExceptionHandler(); originalUnsuccessfulHandler = request.getUnsuccessfulResponseHandler(); request.setIOExceptionHandler(this); request.setUnsuccessfulResponseHandler(this); } public boolean handleIOException(HttpRequest request, boolean supportsRetry) throws IOException { boolean handled = originalIOExceptionHandler != null && originalIOExceptionHandler.handleIOException(request, supportsRetry); // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if I/O // exception was handled, or call it regardless if (handled) { try { uploader.serverErrorCallback(); } catch (IOException e) { LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); } } return handled; } public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException { boolean handled = originalUnsuccessfulHandler != null && originalUnsuccessfulHandler.handleResponse(request, response, supportsRetry); // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if the // abnormal response was handled, or call it regardless if (handled && supportsRetry && response.getStatusCode() / 100 == 5) { try { uploader.serverErrorCallback(); } catch (IOException e) { LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); } } return handled; } }
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. */ /** * Media for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.media;
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.googleapis.media; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.http.AbstractInputStreamContent; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.ExponentialBackOffPolicy; import com.google.api.client.http.GZipEncoding; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffIOExceptionHandler; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; 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.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.MultipartContent; import com.google.api.client.util.Beta; import com.google.api.client.util.ByteStreams; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * Media HTTP Uploader, with support for both direct and resumable media uploads. Documentation is * available <a href='http://code.google.com/p/google-api-java-client/wiki/MediaUpload'>here</a>. * * <p> * For resumable uploads, when the media content length is known, if the provided * {@link InputStream} has {@link InputStream#markSupported} as {@code false} then it is wrapped in * an {@link BufferedInputStream} to support the {@link InputStream#mark} and * {@link InputStream#reset} methods required for handling server errors. If the media content * length is unknown then each chunk is stored temporarily in memory. This is required to determine * when the last chunk is reached. * </p> * * <p> * See {@link #setDisableGZipContent(boolean)} for information on when content is gzipped and how to * control that behavior. * </p> * * <p> * Back-off is disabled by default. To enable it for an abnormal HTTP response and an I/O exception * you should call {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} instance and * {@link HttpRequest#setIOExceptionHandler} with {@link HttpBackOffIOExceptionHandler}. * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default for an * abnormal HTTP response and there was a regular retry (without back-off) when I/O exception was * thrown. Starting with version 1.15 back-off is disabled and there is no retry on I/O exception by * default. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.9 * * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") public final class MediaHttpUploader { /** * Upload content type header. * * @since 1.13 */ public static final String CONTENT_LENGTH_HEADER = "X-Upload-Content-Length"; /** * Upload content length header. * * @since 1.13 */ public static final String CONTENT_TYPE_HEADER = "X-Upload-Content-Type"; /** * Upload state associated with the Media HTTP uploader. */ public enum UploadState { /** The upload process has not started yet. */ NOT_STARTED, /** Set before the initiation request is sent. */ INITIATION_STARTED, /** Set after the initiation request completes. */ INITIATION_COMPLETE, /** Set after a media file chunk is uploaded. */ MEDIA_IN_PROGRESS, /** Set after the complete media file is successfully uploaded. */ MEDIA_COMPLETE } /** The current state of the uploader. */ private UploadState uploadState = UploadState.NOT_STARTED; static final int MB = 0x100000; private static final int KB = 0x400; /** * Minimum number of bytes that can be uploaded to the server (set to 256KB). */ public static final int MINIMUM_CHUNK_SIZE = 256 * KB; /** * Default maximum number of bytes that will be uploaded to the server in any single HTTP request * (set to 10 MB). */ public static final int DEFAULT_CHUNK_SIZE = 10 * MB; /** The HTTP content of the media to be uploaded. */ private final AbstractInputStreamContent mediaContent; /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The transport to use for requests. */ private final HttpTransport transport; /** HTTP content metadata of the media to be uploaded or {@code null} for none. */ private HttpContent metadata; /** * The length of the HTTP media content. * * <p> * {@code 0} before it is lazily initialized in {@link #getMediaContentLength()} after which it * could still be {@code 0} for empty media content. Will be {@code < 0} if the media content * length has not been specified. * </p> */ private long mediaContentLength; /** * Determines if media content length has been calculated yet in {@link #getMediaContentLength()}. */ private boolean isMediaContentLengthCalculated; /** * The HTTP method used for the initiation request. * * <p> * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media * update). The default value is {@link HttpMethods#POST}. * </p> */ private String initiationRequestMethod = HttpMethods.POST; /** The HTTP headers used in the initiation request. */ private HttpHeaders initiationHeaders = new HttpHeaders(); /** * The HTTP request object that is currently used to send upload requests or {@code null} before * {@link #upload}. */ private HttpRequest currentRequest; /** An Input stream of the HTTP media content or {@code null} before {@link #upload}. */ private InputStream contentInputStream; /** * Determines whether the back off policy is enabled or disabled. The default value is * {@code false}. */ @Deprecated @Beta private boolean backOffPolicyEnabled = false; /** * Determines whether direct media upload is enabled or disabled. If value is set to {@code true} * then a direct upload will be done where the whole media content is uploaded in a single request * If value is set to {@code false} then the upload uses the resumable media upload protocol to * upload in data chunks. Defaults to {@code false}. */ private boolean directUploadEnabled; /** * Progress listener to send progress notifications to or {@code null} for none. */ private MediaHttpUploaderProgressListener progressListener; /** * The total number of bytes uploaded by this uploader. This value will not be calculated for * direct uploads when the content length is not known in advance. */ // TODO(rmistry): Figure out a way to compute the content length using CountingInputStream. private long bytesUploaded; /** * Maximum size of individual chunks that will get uploaded by single HTTP requests. The default * value is {@link #DEFAULT_CHUNK_SIZE}. */ private int chunkSize = DEFAULT_CHUNK_SIZE; /** * Used to cache a single byte when the media content length is unknown or {@code null} for none. */ private Byte cachedByte; /** * The content buffer of the current request or {@code null} for none. It is used for resumable * media upload when the media content length is not specified. It is instantiated for every * request in {@link #setContentAndHeadersOnCurrentRequest} and is set to {@code null} when the * request is completed in {@link #upload}. */ private byte currentRequestContentBuffer[]; /** * Whether to disable GZip compression of HTTP content. * * <p> * The default value is {@code false}. * </p> */ private boolean disableGZipContent; /** Sleeper. **/ Sleeper sleeper = Sleeper.DEFAULT; /** * Construct the {@link MediaHttpUploader}. * * <p> * The input stream received by calling {@link AbstractInputStreamContent#getInputStream} is * closed when the upload process is successfully completed. For resumable uploads, when the media * content length is known, if the input stream has {@link InputStream#markSupported} as * {@code false} then it is wrapped in an {@link BufferedInputStream} to support the * {@link InputStream#mark} and {@link InputStream#reset} methods required for handling server * errors. If the media content length is unknown then each chunk is stored temporarily in memory. * This is required to determine when the last chunk is reached. * </p> * * @param mediaContent The Input stream content of the media to be uploaded * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public MediaHttpUploader(AbstractInputStreamContent mediaContent, HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.mediaContent = Preconditions.checkNotNull(mediaContent); this.transport = Preconditions.checkNotNull(transport); this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Executes a direct media upload or resumable media upload conforming to the specifications * listed <a href='http://code.google.com/apis/gdata/docs/resumable_upload.html'>here.</a> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpUploader} must be instantiated * before upload called be called again. * </p> * * <p> * If an error is encountered during the request execution the caller is responsible for parsing * the response correctly. For example for JSON errors: * </p> * * <pre> if (!response.isSuccessStatusCode()) { throw GoogleJsonResponseException.from(jsonFactory, response); } * </pre> * * <p> * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the * response stream is properly closed. Example usage: * </p> * * <pre> HttpResponse response = batch.upload(initiationRequestUrl); try { // process the HTTP response object } finally { response.disconnect(); } * </pre> * * @param initiationRequestUrl The request URL where the initiation request will be sent * @return HTTP response */ public HttpResponse upload(GenericUrl initiationRequestUrl) throws IOException { Preconditions.checkArgument(uploadState == UploadState.NOT_STARTED); if (directUploadEnabled) { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequestWithBackOffAndGZip(request); boolean responseProcessed = false; try { if (getMediaContentLength() >= 0) { bytesUploaded = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; } // Make initial request to get the unique upload URL. HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl); if (!initialResponse.isSuccessStatusCode()) { // If the initiation request is not successful return it immediately. return initialResponse; } GenericUrl uploadUrl; try { uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation()); } finally { initialResponse.disconnect(); } // Convert media content into a byte stream to upload in chunks. contentInputStream = mediaContent.getInputStream(); if (!contentInputStream.markSupported() && getMediaContentLength() >= 0) { // If we know the media content length then wrap the stream into a Buffered input stream to // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for // handling server errors. contentInputStream = new BufferedInputStream(contentInputStream); } HttpResponse response; // Upload the media content in chunks. while (true) { currentRequest = requestFactory.buildPutRequest(uploadUrl, null); setContentAndHeadersOnCurrentRequest(bytesUploaded); if (backOffPolicyEnabled) { // use exponential back-off on server error currentRequest.setBackOffPolicy(new MediaUploadExponentialBackOffPolicy(this)); } else { // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response // TODO(peleyal): uncomment this when issue 772 is fixed // new MediaUploadErrorHandler(this, currentRequest); } if (getMediaContentLength() >= 0) { // TODO(rmistry): Support gzipping content for the case where media content length is // known (https://code.google.com/p/google-api-java-client/issues/detail?id=691). } else if (!disableGZipContent) { currentRequest.setEncoding(new GZipEncoding()); } response = executeCurrentRequest(currentRequest); boolean returningResponse = false; try { if (response.isSuccessStatusCode()) { bytesUploaded = getMediaContentLength(); if (mediaContent.getCloseInputStream()) { contentInputStream.close(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); returningResponse = true; return response; } if (response.getStatusCode() != 308) { returningResponse = true; return response; } // Check to see if the upload URL has changed on the server. String updatedUploadUrl = response.getHeaders().getLocation(); if (updatedUploadUrl != null) { uploadUrl = new GenericUrl(updatedUploadUrl); } bytesUploaded = getNextByteIndex(response.getHeaders().getRange()); currentRequestContentBuffer = null; updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); } finally { if (!returningResponse) { response.disconnect(); } } } } /** * Uses lazy initialization to compute the media content length. * * <p> * This is done to avoid throwing an {@link IOException} in the constructor. * </p> */ private long getMediaContentLength() throws IOException { if (!isMediaContentLengthCalculated) { mediaContentLength = mediaContent.getLength(); isMediaContentLengthCalculated = true; } return mediaContentLength; } /** * This method sends a POST request with empty content to get the unique upload URL. * * @param initiationRequestUrl The request URL where the initiation request will be sent */ private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (getMediaContentLength() >= 0) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequestWithBackOffAndGZip(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; } /** * Executes the current request with some minimal common code. * * @param request current request * @return HTTP response */ private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException { // method override for non-POST verbs new MethodOverride().intercept(request); // don't throw an exception so we can let a custom Google exception be thrown request.setThrowExceptionOnExecuteError(false); // execute the request HttpResponse response = request.execute(); return response; } /** * Executes the current request with some common code that includes exponential backoff and GZip * encoding. * * @param request current request * @return HTTP response */ private HttpResponse executeCurrentRequestWithBackOffAndGZip(HttpRequest request) throws IOException { // use exponential backoff on server error if (backOffPolicyEnabled) { request.setBackOffPolicy(new ExponentialBackOffPolicy()); } // enable GZip encoding if necessary if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) { request.setEncoding(new GZipEncoding()); } // execute request HttpResponse response = executeCurrentRequest(request); return response; } /** * Sets the HTTP media content chunk and the required headers that should be used in the upload * request. * * @param bytesWritten The number of bytes that have been successfully uploaded on the server */ private void setContentAndHeadersOnCurrentRequest(long bytesWritten) throws IOException { int blockSize; if (getMediaContentLength() >= 0) { // We know exactly what the blockSize will be because we know the media content length. blockSize = (int) Math.min(chunkSize, getMediaContentLength() - bytesWritten); } else { // Use the chunkSize as the blockSize because we do know what what it is yet. blockSize = chunkSize; } AbstractInputStreamContent contentChunk; int actualBlockSize = blockSize; String mediaContentLengthStr; if (getMediaContentLength() >= 0) { // Mark the current position in case we need to retry the request. contentInputStream.mark(blockSize); InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize); contentChunk = new InputStreamContent( mediaContent.getType(), limitInputStream).setRetrySupported(true) .setLength(blockSize).setCloseInputStream(false); mediaContentLengthStr = String.valueOf(getMediaContentLength()); } else { // If the media content length is not known we implement a custom buffered input stream that // enables us to detect the length of the media content when the last chunk is sent. We // accomplish this by always trying to read an extra byte further than the end of the current // chunk. int actualBytesRead; int bytesAllowedToRead; int contentBufferStartIndex = 0; if (currentRequestContentBuffer == null) { bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize; currentRequestContentBuffer = new byte[blockSize + 1]; if (cachedByte != null) { currentRequestContentBuffer[0] = cachedByte; } actualBytesRead = ByteStreams.read( contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead, bytesAllowedToRead); } else { // currentRequestContentBuffer is not null that means this is a request to recover from a // server error. The new request will be constructed from the previous request's byte // buffer. bytesAllowedToRead = (int) (chunkSize - (bytesWritten - bytesUploaded) + 1); contentBufferStartIndex = (int) (bytesWritten - bytesUploaded); actualBytesRead = bytesAllowedToRead; } if (actualBytesRead < bytesAllowedToRead) { actualBlockSize = Math.max(0, actualBytesRead); if (cachedByte != null) { actualBlockSize++; } // At this point we know we reached the media content length because we either read less // than the specified chunk size or there is no more data left to be read. mediaContentLengthStr = String.valueOf(bytesWritten + actualBlockSize); } else { cachedByte = currentRequestContentBuffer[blockSize]; mediaContentLengthStr = "*"; } contentChunk = new ByteArrayContent( mediaContent.getType(), currentRequestContentBuffer, contentBufferStartIndex, actualBlockSize); } currentRequest.setContent(contentChunk); if (actualBlockSize == 0) { // special case of zero content media being uploaded currentRequest.getHeaders().setContentRange("bytes */0"); } else { currentRequest.getHeaders().setContentRange("bytes " + bytesWritten + "-" + (bytesWritten + actualBlockSize - 1) + "/" + mediaContentLengthStr); } } /** * {@link Beta} <br/> * The call back method that will be invoked on a server error or an I/O exception during * resumable upload inside {@link #upload}. * * <p> * This method will query the current status of the upload to find how many bytes were * successfully uploaded before the server error occurred. It will then adjust the HTTP Request * object to contain the correct range header and media content chunk. * </p> */ @Beta public void serverErrorCallback() throws IOException { Preconditions.checkNotNull(currentRequest, "The current request should not be null"); // TODO(rmistry): Handle timeouts here similar to how server errors are handled. // Query the current status of the upload by issuing an empty PUT request on the upload URI. HttpRequest request = requestFactory.buildPutRequest(currentRequest.getUrl(), new EmptyContent()); request.getHeaders().setContentRange( "bytes */" + (getMediaContentLength() >= 0 ? getMediaContentLength() : "*")); HttpResponse response = executeCurrentRequestWithBackOffAndGZip(request); try { long bytesWritten = getNextByteIndex(response.getHeaders().getRange()); // Check to see if the upload URL has changed on the server. String updatedUploadUrl = response.getHeaders().getLocation(); if (updatedUploadUrl != null) { currentRequest.setUrl(new GenericUrl(updatedUploadUrl)); } if (getMediaContentLength() >= 0) { // The current position of the input stream is likely incorrect because the upload was // interrupted. Reset the position and skip ahead to the correct spot. // We do not need to do this when the media content length is unknown because we store the // last chunk in a byte buffer. contentInputStream.reset(); long skipValue = bytesUploaded - bytesWritten; long actualSkipValue = contentInputStream.skip(skipValue); Preconditions.checkState(skipValue == actualSkipValue); } // Adjust the HTTP request that encountered the server error with the correct range header // and media content chunk. setContentAndHeadersOnCurrentRequest(bytesWritten); } finally { response.disconnect(); } } /** * Returns the next byte index identifying data that the server has not yet received, obtained * from the HTTP Range header (E.g a header of "Range: 0-55" would cause 56 to be returned). * <code>null</code> or malformed headers cause 0 to be returned. * * @param rangeHeader in the HTTP response * @return the byte index beginning where the server has yet to receive data */ private long getNextByteIndex(String rangeHeader) { if (rangeHeader == null) { return 0L; } return Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('-') + 1)) + 1; } /** Returns HTTP content metadata for the media request or {@code null} for none. */ public HttpContent getMetadata() { return metadata; } /** Sets HTTP content metadata for the media request or {@code null} for none. */ public MediaHttpUploader setMetadata(HttpContent metadata) { this.metadata = metadata; return this; } /** Returns the HTTP content of the media to be uploaded. */ public HttpContent getMediaContent() { return mediaContent; } /** Returns the transport to use for requests. */ public HttpTransport getTransport() { return transport; } /** * {@link Beta} <br/> * Sets whether the back off policy is enabled or disabled. The default value is {@code false}. * * <p> * Upgrade warning: in prior version 1.14 the default value was {@code true}, but starting with * version 1.15 the default value is {@code false}. * </p> * * @deprecated (scheduled to be removed in the 1.16). Use * {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} in {@link HttpRequestInitializer} * instead. */ @Beta @Deprecated public MediaHttpUploader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) { this.backOffPolicyEnabled = backOffPolicyEnabled; return this; } /** * {@link Beta} <br/> * Returns whether the back off policy is enabled or disabled. * * @deprecated (scheduled to be removed in the 1.16). Use * {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} in {@link HttpRequestInitializer} * instead. */ @Beta @Deprecated public boolean isBackOffPolicyEnabled() { return backOffPolicyEnabled; } /** * Sets whether direct media upload is enabled or disabled. * * <p> * If value is set to {@code true} then a direct upload will be done where the whole media content * is uploaded in a single request. If value is set to {@code false} then the upload uses the * resumable media upload protocol to upload in data chunks. * </p> * * <p> * Direct upload is recommended if the content size falls below a certain minimum limit. This is * because there's minimum block write size for some Google APIs, so if the resumable request * fails in the space of that first block, the client will have to restart from the beginning * anyway. * </p> * * <p> * Defaults to {@code false}. * </p> * * @since 1.9 */ public MediaHttpUploader setDirectUploadEnabled(boolean directUploadEnabled) { this.directUploadEnabled = directUploadEnabled; return this; } /** * Returns whether direct media upload is enabled or disabled. If value is set to {@code true} * then a direct upload will be done where the whole media content is uploaded in a single * request. If value is set to {@code false} then the upload uses the resumable media upload * protocol to upload in data chunks. Defaults to {@code false}. * * @since 1.9 */ public boolean isDirectUploadEnabled() { return directUploadEnabled; } /** * Sets the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpUploader setProgressListener(MediaHttpUploaderProgressListener progressListener) { this.progressListener = progressListener; return this; } /** * Returns the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpUploaderProgressListener getProgressListener() { return progressListener; } /** * Sets the maximum size of individual chunks that will get uploaded by single HTTP requests. The * default value is {@link #DEFAULT_CHUNK_SIZE}. * * <p> * The minimum allowable value is {@link #MINIMUM_CHUNK_SIZE} and the specified chunk size must be * a multiple of {@link #MINIMUM_CHUNK_SIZE}. * </p> */ public MediaHttpUploader setChunkSize(int chunkSize) { Preconditions.checkArgument(chunkSize > 0 && chunkSize % MINIMUM_CHUNK_SIZE == 0); this.chunkSize = chunkSize; return this; } /** * Returns the maximum size of individual chunks that will get uploaded by single HTTP requests. * The default value is {@link #DEFAULT_CHUNK_SIZE}. */ public int getChunkSize() { return chunkSize; } /** * Returns whether to disable GZip compression of HTTP content. * * @since 1.13 */ public boolean getDisableGZipContent() { return disableGZipContent; } /** * Sets whether to disable GZip compression of HTTP content. * * <p> * By default it is {@code false}. * </p> * * <p> * If {@link #setDisableGZipContent(boolean)} is set to false (the default value) then content is * gzipped for direct media upload and resumable media uploads when content length is not known. * Due to a current limitation, content is not gzipped for resumable media uploads when content * length is known; this limitation will be removed in the future. * </p> * * @since 1.13 */ public MediaHttpUploader setDisableGZipContent(boolean disableGZipContent) { this.disableGZipContent = disableGZipContent; return this; } /** * Returns the sleeper. * * @since 1.15 */ public Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public MediaHttpUploader setSleeper(Sleeper sleeper) { this.sleeper = sleeper; return this; } /** * Returns the HTTP method used for the initiation request. * * <p> * The default value is {@link HttpMethods#POST}. * </p> * * @since 1.12 */ public String getInitiationRequestMethod() { return initiationRequestMethod; } /** * Sets the HTTP method used for the initiation request. * * <p> * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media * update). The default value is {@link HttpMethods#POST}. * </p> * * @since 1.12 */ public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) { Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST) || initiationRequestMethod.equals(HttpMethods.PUT)); this.initiationRequestMethod = initiationRequestMethod; return this; } /** Sets the HTTP headers used for the initiation request. */ public MediaHttpUploader setInitiationHeaders(HttpHeaders initiationHeaders) { this.initiationHeaders = initiationHeaders; return this; } /** Returns the HTTP headers used for the initiation request. */ public HttpHeaders getInitiationHeaders() { return initiationHeaders; } /** * Gets the total number of bytes uploaded by this uploader or {@code 0} for direct uploads when * the content length is not known. * * @return the number of bytes uploaded */ public long getNumBytesUploaded() { return bytesUploaded; } /** * Sets the upload state and notifies the progress listener. * * @param uploadState value to set to */ private void updateStateAndNotifyListener(UploadState uploadState) throws IOException { this.uploadState = uploadState; if (progressListener != null) { progressListener.progressChanged(this); } } /** * Gets the current upload state of the uploader. * * @return the upload state */ public UploadState getUploadState() { return uploadState; } /** * Gets the upload progress denoting the percentage of bytes that have been uploaded, represented * between 0.0 (0%) and 1.0 (100%). * * <p> * Do not use if the specified {@link AbstractInputStreamContent} has no content length specified. * Instead, consider using {@link #getNumBytesUploaded} to denote progress. * </p> * * @throws IllegalArgumentException if the specified {@link AbstractInputStreamContent} has no * content length * @return the upload progress */ public double getProgress() throws IOException { Preconditions.checkArgument(getMediaContentLength() >= 0, "Cannot call getProgress() if " + "the specified AbstractInputStreamContent has no content length. Use " + " getNumBytesUploaded() to denote progress instead."); return getMediaContentLength() == 0 ? 0 : (double) bytesUploaded / getMediaContentLength(); } }
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.googleapis.media; import java.io.IOException; /** * An interface for receiving progress notifications for uploads. * * <p> * Sample usage (if media content length is provided, else consider using * {@link MediaHttpUploader#getNumBytesUploaded} instead of {@link MediaHttpUploader#getProgress}: * </p> * * <pre> public static class MyUploadProgressListener implements MediaHttpUploaderProgressListener { public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation Started"); break; case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; } } } * </pre> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface MediaHttpUploaderProgressListener { /** * Called to notify that progress has been changed. * * <p> * This method is called once before and after the initiation request. For media uploads it is * called multiple times depending on how many chunks are uploaded. Once the upload completes it * is called one final time. * </p> * * <p> * The upload state can be queried by calling {@link MediaHttpUploader#getUploadState} and the * progress by calling {@link MediaHttpUploader#getProgress}. * </p> * * @param uploader Media HTTP uploader */ public void progressChanged(MediaHttpUploader uploader) throws IOException; }
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.googleapis.media; import com.google.api.client.http.ExponentialBackOffPolicy; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Extension of {@link ExponentialBackOffPolicy} that calls the Media HTTP Uploader call back method * before backing off requests. * * <p> * Implementation is not thread-safe. * </p> * * @author rmistry@google.com (Ravi Mistry) */ @Beta @Deprecated @SuppressWarnings("deprecation") class MediaUploadExponentialBackOffPolicy extends ExponentialBackOffPolicy { /** The uploader to callback on if there is a server error. */ private final MediaHttpUploader uploader; MediaUploadExponentialBackOffPolicy(MediaHttpUploader uploader) { super(); this.uploader = uploader; } /** * Gets the number of milliseconds to wait before retrying an HTTP request. If {@link #STOP} is * returned, no retries should be made. Calls the Media HTTP Uploader call back method before * backing off requests. * * @return the number of milliseconds to wait when backing off requests, or {@link #STOP} if no * more retries should be made */ @Override public long getNextBackOffMillis() throws IOException { // Call the Media HTTP Uploader to calculate how much data was uploaded before the error and // then adjust the HTTP request before the retry. uploader.serverErrorCallback(); return super.getNextBackOffMillis(); } }
Java
/* * Copyright (c) 2012 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.googleapis.media; import java.io.IOException; /** * An interface for receiving progress notifications for downloads. * * <p> * Sample usage: * </p> * * <pre> public static class MyDownloadProgressListener implements MediaHttpDownloaderProgressListener { public void progressChanged(MediaHttpDownloader downloader) throws IOException { switch (downloader.getDownloadState()) { case MEDIA_IN_PROGRESS: System.out.println("Download in progress"); System.out.println("Download percentage: " + downloader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Download Completed!"); break; } } } * </pre> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface MediaHttpDownloaderProgressListener { /** * Called to notify that progress has been changed. * * <p> * This method is called multiple times depending on how many chunks are downloaded. Once the * download completes it is called one final time. * </p> * * <p> * The download state can be queried by calling {@link MediaHttpDownloader#getDownloadState} and * the progress by calling {@link MediaHttpDownloader#getProgress}. * </p> * * @param downloader Media HTTP downloader */ public void progressChanged(MediaHttpDownloader downloader) throws IOException; }
Java
/* * Copyright (c) 2012 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.googleapis.media; import com.google.api.client.http.ExponentialBackOffPolicy; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffIOExceptionHandler; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpHeaders; 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.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; import com.google.api.client.util.IOUtils; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.OutputStream; /** * Media HTTP Downloader, with support for both direct and resumable media downloads. Documentation * is available <a * href='http://code.google.com/p/google-api-java-client/wiki/MediaDownload'>here</a>. * * <p> * Implementation is not thread-safe. * </p> * * <p> * Back-off is disabled by default. To enable it for an abnormal HTTP response and an I/O exception * you should call {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} instance and * {@link HttpRequest#setIOExceptionHandler} with {@link HttpBackOffIOExceptionHandler}. * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default for an * abnormal HTTP response. Starting with version 1.15 it's disabled by default. * </p> * * @since 1.9 * * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") public final class MediaHttpDownloader { /** * Download state associated with the Media HTTP downloader. */ public enum DownloadState { /** The download process has not started yet. */ NOT_STARTED, /** Set after a media file chunk is downloaded. */ MEDIA_IN_PROGRESS, /** Set after the complete media file is successfully downloaded. */ MEDIA_COMPLETE } /** * Default maximum number of bytes that will be downloaded from the server in any single HTTP * request. Set to 32MB because that is the maximum App Engine request size. */ public static final int MAXIMUM_CHUNK_SIZE = 32 * MediaHttpUploader.MB; /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The transport to use for requests. */ private final HttpTransport transport; /** * Determines whether the back off policy is enabled or disabled. The default value is * {@code false}. */ @Deprecated @Beta private boolean backOffPolicyEnabled = false; /** * Determines whether direct media download is enabled or disabled. If value is set to * {@code true} then a direct download will be done where the whole media content is downloaded in * a single request. If value is set to {@code false} then the download uses the resumable media * download protocol to download in data chunks. Defaults to {@code false}. */ private boolean directDownloadEnabled = false; /** * Progress listener to send progress notifications to or {@code null} for none. */ private MediaHttpDownloaderProgressListener progressListener; /** * Maximum size of individual chunks that will get downloaded by single HTTP requests. The default * value is {@link #MAXIMUM_CHUNK_SIZE}. */ private int chunkSize = MAXIMUM_CHUNK_SIZE; /** * The length of the HTTP media content or {@code 0} before it is initialized in * {@link #setMediaContentLength}. */ private long mediaContentLength; /** The current state of the downloader. */ private DownloadState downloadState = DownloadState.NOT_STARTED; /** The total number of bytes downloaded by this downloader. */ private long bytesDownloaded; /** * The last byte position of the media file we want to download, default value is {@code -1}. * * <p> * If its value is {@code -1} it means there is no upper limit on the byte position. * </p> */ private long lastBytePos = -1; /** * Construct the {@link MediaHttpDownloader}. * * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public MediaHttpDownloader( HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.transport = Preconditions.checkNotNull(transport); this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Executes a direct media download or a resumable media download. * * <p> * This method does not close the given output stream. * </p> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be * instantiated before download called be called again. * </p> * * @param requestUrl The request URL where the download requests will be sent * @param outputStream destination output stream */ public void download(GenericUrl requestUrl, OutputStream outputStream) throws IOException { download(requestUrl, null, outputStream); } /** * Executes a direct media download or a resumable media download. * * <p> * This method does not close the given output stream. * </p> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be * instantiated before download called be called again. * </p> * * @param requestUrl request URL where the download requests will be sent * @param requestHeaders request headers or {@code null} to ignore * @param outputStream destination output stream * @since 1.12 */ public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED); requestUrl.put("alt", "media"); if (directDownloadEnabled) { updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS); HttpResponse response = executeCurrentRequest(lastBytePos, requestUrl, requestHeaders, outputStream); // All required bytes have been downloaded from the server. mediaContentLength = response.getHeaders().getContentLength(); bytesDownloaded = mediaContentLength; updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); return; } // Download the media content in chunks. while (true) { long currentRequestLastBytePos = bytesDownloaded + chunkSize - 1; if (lastBytePos != -1) { // If last byte position has been specified use it iff it is smaller than the chunksize. currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos); } HttpResponse response = executeCurrentRequest( currentRequestLastBytePos, requestUrl, requestHeaders, outputStream); String contentRange = response.getHeaders().getContentRange(); long nextByteIndex = getNextByteIndex(contentRange); setMediaContentLength(contentRange); if (mediaContentLength <= nextByteIndex) { // All required bytes have been downloaded from the server. bytesDownloaded = mediaContentLength; updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); return; } bytesDownloaded = nextByteIndex; updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS); } } /** * Executes the current request. * * @param currentRequestLastBytePos last byte position for current request * @param requestUrl request URL where the download requests will be sent * @param requestHeaders request headers or {@code null} to ignore * @param outputStream destination output stream * @return HTTP response */ private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { // prepare the GET request HttpRequest request = requestFactory.buildGetRequest(requestUrl); // add request headers if (requestHeaders != null) { request.getHeaders().putAll(requestHeaders); } // set Range header (if necessary) if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) { StringBuilder rangeHeader = new StringBuilder(); rangeHeader.append("bytes=").append(bytesDownloaded).append("-"); if (currentRequestLastBytePos != -1) { rangeHeader.append(currentRequestLastBytePos); } request.getHeaders().setRange(rangeHeader.toString()); } // use exponential backoff on server error if (backOffPolicyEnabled) { request.setBackOffPolicy(new ExponentialBackOffPolicy()); } // execute the request and copy into the output stream HttpResponse response = request.execute(); try { IOUtils.copy(response.getContent(), outputStream); } finally { response.disconnect(); } return response; } /** * Returns the next byte index identifying data that the server has not yet sent out, obtained * from the HTTP Content-Range header (E.g a header of "Content-Range: 0-55/1000" would cause 56 * to be returned). <code>null</code> headers cause 0 to be returned. * * @param rangeHeader in the HTTP response * @return the byte index beginning where the server has yet to send out data */ private long getNextByteIndex(String rangeHeader) { if (rangeHeader == null) { return 0L; } return Long.parseLong( rangeHeader.substring(rangeHeader.indexOf('-') + 1, rangeHeader.indexOf('/'))) + 1; } /** * Sets the total number of bytes that have been downloaded of the media resource. * * <p> * If a download was aborted mid-way due to a connection failure then users can resume the * download from the point where it left off. * </p> * * <p> * Use {@link #setContentRange} if you need to specify both the bytes downloaded and the last byte * position. * </p> * * @param bytesDownloaded The total number of bytes downloaded */ public MediaHttpDownloader setBytesDownloaded(long bytesDownloaded) { Preconditions.checkArgument(bytesDownloaded >= 0); this.bytesDownloaded = bytesDownloaded; return this; } /** * Sets the content range of the next download request. Eg: bytes=firstBytePos-lastBytePos. * * <p> * If a download was aborted mid-way due to a connection failure then users can resume the * download from the point where it left off. * </p> * * <p> * Use {@link #setBytesDownloaded} if you only need to specify the first byte position. * </p> * * @param firstBytePos The first byte position in the content range string * @param lastBytePos The last byte position in the content range string. * @since 1.13 */ public MediaHttpDownloader setContentRange(long firstBytePos, int lastBytePos) { Preconditions.checkArgument(lastBytePos >= firstBytePos); setBytesDownloaded(firstBytePos); this.lastBytePos = lastBytePos; return this; } /** * Sets the media content length from the HTTP Content-Range header (E.g a header of * "Content-Range: 0-55/1000" would cause 1000 to be set. <code>null</code> headers do not set * anything. * * @param rangeHeader in the HTTP response */ private void setMediaContentLength(String rangeHeader) { if (rangeHeader == null) { return; } if (mediaContentLength == 0) { mediaContentLength = Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('/') + 1)); } } /** * Returns whether direct media download is enabled or disabled. If value is set to {@code true} * then a direct download will be done where the whole media content is downloaded in a single * request. If value is set to {@code false} then the download uses the resumable media download * protocol to download in data chunks. Defaults to {@code false}. */ public boolean isDirectDownloadEnabled() { return directDownloadEnabled; } /** * Returns whether direct media download is enabled or disabled. If value is set to {@code true} * then a direct download will be done where the whole media content is downloaded in a single * request. If value is set to {@code false} then the download uses the resumable media download * protocol to download in data chunks. Defaults to {@code false}. */ public MediaHttpDownloader setDirectDownloadEnabled(boolean directDownloadEnabled) { this.directDownloadEnabled = directDownloadEnabled; return this; } /** * Sets the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpDownloader setProgressListener( MediaHttpDownloaderProgressListener progressListener) { this.progressListener = progressListener; return this; } /** * Returns the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpDownloaderProgressListener getProgressListener() { return progressListener; } /** * {@link Beta} <br/> * Sets whether the back off policy is enabled or disabled. The default value is {@code false}. * * <p> * Upgrade warning: in prior version 1.14 the default value was {@code true}, but starting with * version 1.15 the default value is {@code false}. * </p> * * @deprecated (scheduled to be removed in the 1.16). Use * {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} in {@link HttpRequestInitializer} * instead. */ @Beta @Deprecated public MediaHttpDownloader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) { this.backOffPolicyEnabled = backOffPolicyEnabled; return this; } /** * {@link Beta} <br/> * Returns whether the back off policy is enabled or disabled. * * @deprecated (scheduled to be removed in the 1.16). Use * {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} in {@link HttpRequestInitializer} * instead. */ @Beta @Deprecated public boolean isBackOffPolicyEnabled() { return backOffPolicyEnabled; } /** Returns the transport to use for requests. */ public HttpTransport getTransport() { return transport; } /** * Sets the maximum size of individual chunks that will get downloaded by single HTTP requests. * The default value is {@link #MAXIMUM_CHUNK_SIZE}. * * <p> * The maximum allowable value is {@link #MAXIMUM_CHUNK_SIZE}. * </p> */ public MediaHttpDownloader setChunkSize(int chunkSize) { Preconditions.checkArgument(chunkSize > 0 && chunkSize <= MAXIMUM_CHUNK_SIZE); this.chunkSize = chunkSize; return this; } /** * Returns the maximum size of individual chunks that will get downloaded by single HTTP requests. * The default value is {@link #MAXIMUM_CHUNK_SIZE}. */ public int getChunkSize() { return chunkSize; } /** * Gets the total number of bytes downloaded by this downloader. * * @return the number of bytes downloaded */ public long getNumBytesDownloaded() { return bytesDownloaded; } /** * Gets the last byte position of the media file we want to download or {@code -1} if there is no * upper limit on the byte position. * * @return the last byte position * @since 1.13 */ public long getLastBytePosition() { return lastBytePos; } /** * Sets the download state and notifies the progress listener. * * @param downloadState value to set to */ private void updateStateAndNotifyListener(DownloadState downloadState) throws IOException { this.downloadState = downloadState; if (progressListener != null) { progressListener.progressChanged(this); } } /** * Gets the current download state of the downloader. * * @return the download state */ public DownloadState getDownloadState() { return downloadState; } /** * Gets the download progress denoting the percentage of bytes that have been downloaded, * represented between 0.0 (0%) and 1.0 (100%). * * @return the download progress */ public double getProgress() { return mediaContentLength == 0 ? 0 : (double) bytesDownloaded / mediaContentLength; } }
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. */ /** * Google's JSON support (see detailed package specification). * * <h2>Package Specification</h2> * * <p> * User-defined Partial JSON data models allow you to defined Plain Old Java Objects (POJO's) to * define how the library should parse/serialize JSON. Each field that should be included must have * an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility * (private, package private, protected, or public) and must not be static. By default, the field * name is used as the JSON key. To override this behavior, simply specify the JSON key use the * optional value parameter of the annotation, for example {@code @Key("name")}. Any unrecognized * keys from the JSON are normally simply ignored and not stored. If the ability to store unknown * keys is important, use {@link com.google.api.client.json.GenericJson}. * </p> * * <p> * Let's take a look at a typical partial JSON-C video feed from the YouTube Data API (as specified * in <a href="http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html">YouTube * Developer's Guide: JSON-C / JavaScript</a>) * </p> * * <pre><code> "data":{ "updated":"2010-01-07T19:58:42.949Z", "totalItems":800, "startIndex":1, "itemsPerPage":1, "items":[ {"id":"hYB0mn5zh2c", "updated":"2010-01-07T13:26:50.000Z", "title":"Google Developers Day US - Maps API Introduction", "description":"Google Maps API Introduction ...", "tags":[ "GDD07","GDD07US","Maps" ], "player":{ "default":"http://www.youtube.com/watch?v\u003dhYB0mn5zh2c" }, ... } ] } </code></pre> * * <p> * Here's one possible way to design the Java data classes for this (each class in its own Java * file): * </p> * * <pre><code> import com.google.api.client.util.*; import java.util.List; public class VideoFeed { &#64;Key public int itemsPerPage; &#64;Key public int startIndex; &#64;Key public int totalItems; &#64;Key public DateTime updated; &#64;Key public List&lt;Video&gt; items; } public class Video { &#64;Key public String id; &#64;Key public String title; &#64;Key public DateTime updated; &#64;Key public String description; &#64;Key public List&lt;String&gt; tags; &#64;Key public Player player; } public class Player { // "default" is a Java keyword, so need to specify the JSON key manually &#64;Key("default") public String defaultUrl; } </code></pre> * * <p> * You can also use the @{@link com.google.api.client.util.Key} annotation to defined query * parameters for a URL. For example: * </p> * * <pre><code> public class YouTubeUrl extends GoogleUrl { &#64;Key public String author; &#64;Key("max-results") public Integer maxResults; public YouTubeUrl(String encodedUrl) { super(encodedUrl); this.alt = "jsonc"; } </code></pre> * * <p> * To work with the YouTube API, you first need to set up the * {@link com.google.api.client.http.HttpTransport}. For example: * </p> * * <pre><code> private static HttpTransport setUpTransport() throws IOException { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); HttpHeaders headers = new HttpHeaders(); headers.setApplicationName("Google-YouTubeSample/1.0"); headers.gdataVersion = "2"; JsonCParser parser = new JsonCParser(); parser.jsonFactory = new JacksonFactory(); transport.addParser(parser); // insert authentication code... return transport; } </code></pre> * * <p> * Now that we have a transport, we can execute a request to the YouTube API and parse the result: * </p> * * <pre><code> public static VideoFeed list(HttpTransport transport, YouTubeUrl url) throws IOException { HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(VideoFeed.class); } </code></pre> * * <p> * If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute} * method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an * {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a * success response inside of a catch block. For example: * </p> * * <pre><code> try { ... } catch (HttpResponseException e) { if (e.response.getParser() != null) { Error error = e.response.parseAs(Error.class); // process error response } else { String errorContentString = e.response.parseAsString(); // process error response as string } throw e; } </code></pre> * * <p> * NOTE: As you might guess, the library uses reflection to populate the user-defined data model. * It's not quite as fast as writing the wire format parsing code yourself can potentially be, but * it's a lot easier. * </p> * * <p> * NOTE: If you prefer to use your favorite JSON parsing library instead (there are many of them * listed for example on <a href="http://json.org">json.org</a>), that's supported as well. Just * call {@link com.google.api.client.http.HttpRequest#execute()} and parse the returned byte stream. * </p> * * @since 1.0 * @author Yaniv Inbar */ package com.google.api.client.googleapis.json;
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.googleapis.json; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.json.CustomizeJsonParser; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.rpc2.JsonRpcRequest; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.Collection; import java.util.List; /** * {@link Beta} <br/> * JSON-RPC 2.0 HTTP transport for RPC requests for Google API's, including both singleton and * batched requests. * * <p> * This implementation is thread-safe. * </p> * * @since 1.3 * @author Yaniv Inbar * @deprecated (scheduled to be removed in 1.16) Use the <a * href="https://code.google.com/p/google-api-java-client/wiki/APIs">Google API * libraries</a> or directly use {@link HttpTransport}. */ @Deprecated @Beta public final class GoogleJsonRpcHttpTransport { private static final String JSON_RPC_CONTENT_TYPE = "application/json-rpc"; /** Encoded RPC server URL. */ private final String rpcServerUrl; /** (REQUIRED) HTTP transport required for building requests. */ private final HttpTransport transport; /** (REQUIRED) JSON factory to use for building requests. */ private final JsonFactory jsonFactory; /** Content type header to use for requests. By default this is {@code "application/json-rpc"}. */ private final String mimeType; /** Accept header to use for requests. By default this is {@code "application/json-rpc"}. */ private final String accept; /** * Creates a new {@link GoogleJsonRpcHttpTransport} with default values for RPC server, and * Content type and Accept headers. * * @param httpTransport HTTP transport required for building requests. * @param jsonFactory JSON factory to use for building requests. * * @since 1.9 */ public GoogleJsonRpcHttpTransport(HttpTransport httpTransport, JsonFactory jsonFactory) { this(Preconditions.checkNotNull(httpTransport), Preconditions.checkNotNull(jsonFactory), Builder.DEFAULT_SERVER_URL.build(), JSON_RPC_CONTENT_TYPE, JSON_RPC_CONTENT_TYPE); } /** * Creates a new {@link GoogleJsonRpcHttpTransport}. * * @param httpTransport HTTP transport required for building requests. * @param jsonFactory JSON factory to use for building requests. * @param rpcServerUrl RPC server URL. * @param mimeType Content type header to use for requests. * @param accept Accept header to use for requests. * * @since 1.9 */ protected GoogleJsonRpcHttpTransport(HttpTransport httpTransport, JsonFactory jsonFactory, String rpcServerUrl, String mimeType, String accept) { this.transport = httpTransport; this.jsonFactory = jsonFactory; this.rpcServerUrl = rpcServerUrl; this.mimeType = mimeType; this.accept = accept; } /** * Returns the HTTP transport used for building requests. * * @since 1.9 */ public final HttpTransport getHttpTransport() { return transport; } /** * Returns the JSON factory used for building requests. * * @since 1.9 */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Returns the RPC server URL. * * @since 1.9 */ public final String getRpcServerUrl() { return rpcServerUrl; } /** * Returns the MIME type header used for requests. * * @since 1.10 */ public final String getMimeType() { return mimeType; } /** * Returns the Accept header used for requests. * * @since 1.9 */ public final String getAccept() { return accept; } /** * {@link Beta} <br/> * {@link GoogleJsonRpcHttpTransport} Builder. * * <p> * Implementation is not thread safe. * </p> * * @since 1.9 * @deprecated (scheduled to be removed in 1.16) */ @Deprecated @Beta public static class Builder { /** Default RPC server URL. */ static final GenericUrl DEFAULT_SERVER_URL = new GenericUrl("https://www.googleapis.com"); /** HTTP transport required for building requests. */ private final HttpTransport httpTransport; /** JSON factory to use for building requests. */ private final JsonFactory jsonFactory; /** RPC server URL. */ private GenericUrl rpcServerUrl = DEFAULT_SERVER_URL; /** MIME type to use for the Content type header for requests. */ private String mimeType = JSON_RPC_CONTENT_TYPE; /** Accept header to use for requests. */ private String accept = mimeType; /** * @param httpTransport HTTP transport required for building requests. * @param jsonFactory JSON factory to use for building requests. */ public Builder(HttpTransport httpTransport, JsonFactory jsonFactory) { this.httpTransport = Preconditions.checkNotNull(httpTransport); this.jsonFactory = Preconditions.checkNotNull(jsonFactory); } /** * Sets the RPC server URL. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param rpcServerUrl RPC server URL. */ protected Builder setRpcServerUrl(GenericUrl rpcServerUrl) { this.rpcServerUrl = Preconditions.checkNotNull(rpcServerUrl); return this; } /** * Sets the MIME type of the Content type header to use for requests. By default this is * {@code "application/json-rpc"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param mimeType MIME type to use for requests. * @since 1.10 */ protected Builder setMimeType(String mimeType) { this.mimeType = Preconditions.checkNotNull(mimeType); return this; } /** * Sets the Accept header to use for requests. By default this is {@code "application/json-rpc"} * . * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param accept Accept header to use for requests. */ protected Builder setAccept(String accept) { this.accept = Preconditions.checkNotNull(accept); return this; } /** * Returns a new {@link GoogleJsonRpcHttpTransport} instance. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ protected GoogleJsonRpcHttpTransport build() { return new GoogleJsonRpcHttpTransport( httpTransport, jsonFactory, rpcServerUrl.build(), mimeType, accept); } /** * Returns the HTTP transport used for building requests. */ public final HttpTransport getHttpTransport() { return httpTransport; } /** * Returns the JSON factory used for building requests. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Returns the RPC server. */ public final GenericUrl getRpcServerUrl() { return rpcServerUrl; } /** * Returns the MIME type used for requests. * * @since 1.10 */ public final String getMimeType() { return mimeType; } /** * Returns the Accept header used for requests. */ public final String getAccept() { return accept; } } /** * Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC * request object. * * <p> * You may use {@link JsonFactory#createJsonParser(java.io.InputStream)} to get the * {@link JsonParser}, and {@link JsonParser#parseAndClose(Class)}. * </p> * * @param request JSON-RPC request object * @return HTTP request */ public HttpRequest buildPostRequest(JsonRpcRequest request) throws IOException { return internalExecute(request); } /** * Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC * request objects. * <p> * Note that the request will always use batching -- i.e. JSON array of requests -- even if there * is only one request. You may use {@link JsonFactory#createJsonParser(java.io.InputStream)} to * get the {@link JsonParser}, and * {@link JsonParser#parseArrayAndClose(Collection, Class, CustomizeJsonParser)} . * </p> * * @param requests JSON-RPC request objects * @return HTTP request */ public HttpRequest buildPostRequest(List<JsonRpcRequest> requests) throws IOException { return internalExecute(requests); } private HttpRequest internalExecute(Object data) throws IOException { JsonHttpContent content = new JsonHttpContent(jsonFactory, data); content.setMediaType(new HttpMediaType(mimeType)); HttpRequest httpRequest; httpRequest = transport.createRequestFactory().buildPostRequest(new GenericUrl(rpcServerUrl), content); httpRequest.getHeaders().setAccept(accept); return httpRequest; } }
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.googleapis.json; import com.google.api.client.http.HttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Data; import com.google.api.client.util.Key; import java.io.IOException; import java.util.Collections; import java.util.List; /** * Data class representing the Google JSON error response content, as documented for example in <a * href="https://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error * responses</a>. * * @since 1.4 * @author Yaniv Inbar */ public class GoogleJsonError extends GenericJson { /** * Parses the given error HTTP response using the given JSON factory. * * @param jsonFactory JSON factory * @param response HTTP response * @return new instance of the Google JSON error information * @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected * {@code "data"} or {@code "error"} key is not found */ public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response) throws IOException { JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys( Collections.singleton("error")).build(); return jsonObjectParser.parseAndClose( response.getContent(), response.getContentCharset(), GoogleJsonError.class); } static { // hack to force ProGuard to consider ErrorInfo used, since otherwise it would be stripped out // see http://code.google.com/p/google-api-java-client/issues/detail?id=527 Data.nullOf(ErrorInfo.class); } /** Detailed error information. */ public static class ErrorInfo extends GenericJson { /** Error classification or {@code null} for none. */ @Key private String domain; /** Error reason or {@code null} for none. */ @Key private String reason; /** Human readable explanation of the error or {@code null} for none. */ @Key private String message; /** * Location in the request that caused the error or {@code null} for none or {@code null} for * none. */ @Key private String location; /** Type of location in the request that caused the error or {@code null} for none. */ @Key private String locationType; /** * Returns the error classification or {@code null} for none. * * @since 1.8 */ public final String getDomain() { return domain; } /** * Sets the error classification or {@code null} for none. * * @since 1.8 */ public final void setDomain(String domain) { this.domain = domain; } /** * Returns the error reason or {@code null} for none. * * @since 1.8 */ public final String getReason() { return reason; } /** * Sets the error reason or {@code null} for none. * * @since 1.8 */ public final void setReason(String reason) { this.reason = reason; } /** * Returns the human readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final String getMessage() { return message; } /** * Sets the human readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final void setMessage(String message) { this.message = message; } /** * Returns the location in the request that caused the error or {@code null} for none or * {@code null} for none. * * @since 1.8 */ public final String getLocation() { return location; } /** * Sets the location in the request that caused the error or {@code null} for none or * {@code null} for none. * * @since 1.8 */ public final void setLocation(String location) { this.location = location; } /** * Returns the type of location in the request that caused the error or {@code null} for none. * * @since 1.8 */ public final String getLocationType() { return locationType; } /** * Sets the type of location in the request that caused the error or {@code null} for none. * * @since 1.8 */ public final void setLocationType(String locationType) { this.locationType = locationType; } @Override public ErrorInfo set(String fieldName, Object value) { return (ErrorInfo) super.set(fieldName, value); } @Override public ErrorInfo clone() { return (ErrorInfo) super.clone(); } } /** List of detailed errors or {@code null} for none. */ @Key private List<ErrorInfo> errors; /** HTTP status code of this response or {@code null} for none. */ @Key private int code; /** Human-readable explanation of the error or {@code null} for none. */ @Key private String message; /** * Returns the list of detailed errors or {@code null} for none. * * @since 1.8 */ public final List<ErrorInfo> getErrors() { return errors; } /** * Sets the list of detailed errors or {@code null} for none. * * @since 1.8 */ public final void setErrors(List<ErrorInfo> errors) { this.errors = errors; } /** * Returns the HTTP status code of this response or {@code null} for none. * * @since 1.8 */ public final int getCode() { return code; } /** * Sets the HTTP status code of this response or {@code null} for none. * * @since 1.8 */ public final void setCode(int code) { this.code = code; } /** * Returns the human-readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final String getMessage() { return message; } /** * Sets the human-readable explanation of the error or {@code null} for none. * * @since 1.8 */ public final void setMessage(String message) { this.message = message; } @Override public GoogleJsonError set(String fieldName, Object value) { return (GoogleJsonError) super.set(fieldName, value); } @Override public GoogleJsonError clone() { return (GoogleJsonError) super.clone(); } }
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.googleapis.json; import com.google.api.client.http.HttpMediaType; 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.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.JsonToken; import com.google.api.client.util.Preconditions; import com.google.api.client.util.StringUtils; import java.io.IOException; /** * Exception thrown when an error status code is detected in an HTTP response to a Google API that * uses the JSON format, using the format specified in <a * href="http://code.google.com/apis/urlshortener/v1/getting_started.html#errors">Error * Responses</a>. * * <p> * To execute a request, call {@link #execute(JsonFactory, HttpRequest)}. This will throw a * {@link GoogleJsonResponseException} on an error response. To get the structured details, use * {@link #getDetails()}. * </p> * * <pre> static void executeShowingError(JsonFactory factory, HttpRequest request) throws IOException { try { GoogleJsonResponseException.execute(factory, request); } catch (GoogleJsonResponseException e) { System.err.println(e.getDetails()); } } * </pre> * * @since 1.6 * @author Yaniv Inbar */ public class GoogleJsonResponseException extends HttpResponseException { private static final long serialVersionUID = 409811126989994864L; /** Google JSON error details or {@code null} for none (for example if response is not JSON). */ private final transient GoogleJsonError details; /** * @param builder builder * @param details Google JSON error details */ GoogleJsonResponseException(Builder builder, GoogleJsonError details) { super(builder); this.details = details; } /** * Returns the Google JSON error details or {@code null} for none (for example if response is not * JSON). */ public final GoogleJsonError getDetails() { return details; } /** * Returns a new instance of {@link GoogleJsonResponseException}. * * <p> * If there is a JSON error response, it is parsed using {@link GoogleJsonError}, which can be * inspected using {@link #getDetails()}. Otherwise, the full response content is read and * included in the exception message. * </p> * * @param jsonFactory JSON factory * @param response HTTP response * @return new instance of {@link GoogleJsonResponseException} */ public static GoogleJsonResponseException from(JsonFactory jsonFactory, HttpResponse response) { HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // details Preconditions.checkNotNull(jsonFactory); GoogleJsonError details = null; String detailString = null; try { if (!response.isSuccessStatusCode() && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, response.getContentType()) && response.getContent() != null) { JsonParser parser = null; try { parser = jsonFactory.createJsonParser(response.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } // check for empty content if (currentToken != null) { // make sure there is an "error" key parser.skipToKey("error"); if (parser.getCurrentToken() != JsonToken.END_OBJECT) { details = parser.parseAndClose(GoogleJsonError.class); detailString = details.toPrettyString(); } } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } finally { if (parser == null) { response.ignore(); } else if (details == null) { parser.close(); } } } else { detailString = response.parseAsString(); } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } // message StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); // result return new GoogleJsonResponseException(builder, details); } /** * Executes an HTTP request using {@link HttpRequest#execute()}, but throws a * {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}. * * <p> * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the * response stream is properly closed. Example usage: * </p> * * <pre> HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request); try { // process the HTTP response object } finally { response.disconnect(); } * </pre> * * @param jsonFactory JSON factory * @param request HTTP request * @return HTTP response for an HTTP success code (or error code if * {@link HttpRequest#getThrowExceptionOnExecuteError()}) * @throws GoogleJsonResponseException for an HTTP error code (only if not * {@link HttpRequest#getThrowExceptionOnExecuteError()}) * @throws IOException some other kind of I/O exception * @since 1.7 */ public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request) throws GoogleJsonResponseException, IOException { Preconditions.checkNotNull(jsonFactory); boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError(); if (originalThrowExceptionOnExecuteError) { request.setThrowExceptionOnExecuteError(false); } HttpResponse response = request.execute(); request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError); if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) { return response; } throw GoogleJsonResponseException.from(jsonFactory, response); } }
Java
/* * Copyright (c) 2012 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.googleapis.json; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Key; /** * Data class representing a container of {@link GoogleJsonError}. * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public class GoogleJsonErrorContainer extends GenericJson { @Key private GoogleJsonError error; /** Returns the {@link GoogleJsonError}. */ public final GoogleJsonError getError() { return error; } /** Sets the {@link GoogleJsonError}. */ public final void setError(GoogleJsonError error) { this.error = error; } @Override public GoogleJsonErrorContainer set(String fieldName, Object value) { return (GoogleJsonErrorContainer) super.set(fieldName, value); } @Override public GoogleJsonErrorContainer clone() { return (GoogleJsonErrorContainer) 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. */ /** * Google APIs. * * @since 1.0 * @author Yaniv Inbar */ package com.google.api.client.googleapis;
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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.RefreshTokenRequest; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.auth.oauth2.TokenResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 request to refresh an access token using a * refresh token as specified in <a href="http://tools.ietf.org/html/rfc6749#section-6">Refreshing * an Access Token</a>. * * <p> * Use {@link GoogleCredential} to access protected resources from the resource server using the * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw * {@link TokenResponseException}. * </p> * * <p> * Sample usage: * </p> * * <pre> static void refreshAccessToken() throws IOException { try { TokenResponse response = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(), "tGzv3JOkF0XG5Qx2TlKWIA", "s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw").execute(); System.out.println("Access token: " + response.getAccessToken()); } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleRefreshTokenRequest extends RefreshTokenRequest { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param refreshToken refresh token issued to the client * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret */ public GoogleRefreshTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String refreshToken, String clientId, String clientSecret) { super(transport, jsonFactory, new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL), refreshToken); setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); } @Override public GoogleRefreshTokenRequest setRequestInitializer( HttpRequestInitializer requestInitializer) { return (GoogleRefreshTokenRequest) super.setRequestInitializer(requestInitializer); } @Override public GoogleRefreshTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { return (GoogleRefreshTokenRequest) super.setTokenServerUrl(tokenServerUrl); } @Override @Beta @Deprecated public GoogleRefreshTokenRequest setScopes(String... scopes) { return (GoogleRefreshTokenRequest) super.setScopes(scopes); } @Override @Beta @Deprecated public GoogleRefreshTokenRequest setScopes(Iterable<String> scopes) { return (GoogleRefreshTokenRequest) super.setScopes(scopes); } @Override public GoogleRefreshTokenRequest setScopes(Collection<String> scopes) { return (GoogleRefreshTokenRequest) super.setScopes(scopes); } @Override public GoogleRefreshTokenRequest setGrantType(String grantType) { return (GoogleRefreshTokenRequest) super.setGrantType(grantType); } @Override public GoogleRefreshTokenRequest setClientAuthentication( HttpExecuteInterceptor clientAuthentication) { return (GoogleRefreshTokenRequest) super.setClientAuthentication(clientAuthentication); } @Override public GoogleRefreshTokenRequest setRefreshToken(String refreshToken) { return (GoogleRefreshTokenRequest) super.setRefreshToken(refreshToken); } @Override public GoogleTokenResponse execute() throws IOException { return executeUnparsed().parseAs(GoogleTokenResponse.class); } @Override public GoogleRefreshTokenRequest set(String fieldName, Object value) { return (GoogleRefreshTokenRequest) super.set(fieldName, value); } }
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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.auth.oauth2.TokenResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 request for an access token based on an * authorization code (as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for Web * Server Applications</a>). * * <p> * Use {@link GoogleCredential} to access protected resources from the resource server using the * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw * {@link TokenResponseException}. * </p> * * <p> * Sample usage: * </p> * * <pre> static void requestAccessToken() throws IOException { try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), "812741506391.apps.googleusercontent.com", "{client_secret}", "4/P7q7W91a-oMsCeLvIaQm6bTrgtp7", "https://oauth2-login-demo.appspot.com/code") .execute(); System.out.println("Access token: " + response.getAccessToken()); } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleAuthorizationCodeTokenRequest extends AuthorizationCodeTokenRequest { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret * @param code authorization code generated by the authorization server * @param redirectUri redirect URL parameter matching the redirect URL parameter in the * authorization request (see {@link #setRedirectUri(String)} */ public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, String code, String redirectUri) { this(transport, jsonFactory, GoogleOAuthConstants.TOKEN_SERVER_URL, clientId, clientSecret, code, redirectUri); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerEncodedUrl token server encoded URL * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret * @param code authorization code generated by the authorization server * @param redirectUri redirect URL parameter matching the redirect URL parameter in the * authorization request (see {@link #setRedirectUri(String)} * * @since 1.12 */ public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String tokenServerEncodedUrl, String clientId, String clientSecret, String code, String redirectUri) { super(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), code); setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); setRedirectUri(redirectUri); } @Override public GoogleAuthorizationCodeTokenRequest setRequestInitializer( HttpRequestInitializer requestInitializer) { return (GoogleAuthorizationCodeTokenRequest) super.setRequestInitializer(requestInitializer); } @Override public GoogleAuthorizationCodeTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { return (GoogleAuthorizationCodeTokenRequest) super.setTokenServerUrl(tokenServerUrl); } @Override @Beta @Deprecated public GoogleAuthorizationCodeTokenRequest setScopes(String... scopes) { return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes); } @Override @Beta @Deprecated public GoogleAuthorizationCodeTokenRequest setScopes(Iterable<String> scopes) { return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeTokenRequest setScopes(Collection<String> scopes) { return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeTokenRequest setGrantType(String grantType) { return (GoogleAuthorizationCodeTokenRequest) super.setGrantType(grantType); } @Override public GoogleAuthorizationCodeTokenRequest setClientAuthentication( HttpExecuteInterceptor clientAuthentication) { Preconditions.checkNotNull(clientAuthentication); return (GoogleAuthorizationCodeTokenRequest) super.setClientAuthentication( clientAuthentication); } @Override public GoogleAuthorizationCodeTokenRequest setCode(String code) { return (GoogleAuthorizationCodeTokenRequest) super.setCode(code); } @Override public GoogleAuthorizationCodeTokenRequest setRedirectUri(String redirectUri) { Preconditions.checkNotNull(redirectUri); return (GoogleAuthorizationCodeTokenRequest) super.setRedirectUri(redirectUri); } @Override public GoogleTokenResponse execute() throws IOException { return executeUnparsed().parseAs(GoogleTokenResponse.class); } @Override public GoogleAuthorizationCodeTokenRequest set(String fieldName, Object value) { return (GoogleAuthorizationCodeTokenRequest) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2012 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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.io.IOException; /** * Google OAuth 2.0 JSON model for a successful access token response as specified in <a * href="http://tools.ietf.org/html/rfc6749#section-5.1">Successful Response</a>, including an ID * token as specified in <a href="http://openid.net/specs/openid-connect-session-1_0.html">OpenID * Connect Session Management 1.0</a>. * * <p> * This response object is the result of {@link GoogleAuthorizationCodeTokenRequest#execute()} and * {@link GoogleRefreshTokenRequest#execute()}. Use {@link #parseIdToken()} to parse the * {@link GoogleIdToken} and then call {@link GoogleIdTokenVerifier#verify(GoogleIdToken)}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleTokenResponse extends TokenResponse { /** ID token. */ @Key("id_token") private String idToken; @Override public GoogleTokenResponse setAccessToken(String accessToken) { return (GoogleTokenResponse) super.setAccessToken(accessToken); } @Override public GoogleTokenResponse setTokenType(String tokenType) { return (GoogleTokenResponse) super.setTokenType(tokenType); } @Override public GoogleTokenResponse setExpiresInSeconds(Long expiresIn) { return (GoogleTokenResponse) super.setExpiresInSeconds(expiresIn); } @Override public GoogleTokenResponse setRefreshToken(String refreshToken) { return (GoogleTokenResponse) super.setRefreshToken(refreshToken); } @Override public GoogleTokenResponse setScope(String scope) { return (GoogleTokenResponse) super.setScope(scope); } /** * {@link Beta} <br/> * Returns the ID token. */ @Beta public final String getIdToken() { return idToken; } /** * {@link Beta} <br/> * Sets the ID token. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public GoogleTokenResponse setIdToken(String idToken) { this.idToken = Preconditions.checkNotNull(idToken); return this; } /** * {@link Beta} <br/> * Parses using {@link GoogleIdToken#parse(JsonFactory, String)} based on the {@link #getFactory() * JSON factory} and {@link #getIdToken() ID token}. */ @Beta public GoogleIdToken parseIdToken() throws IOException { return GoogleIdToken.parse(getFactory(), getIdToken()); } @Override public GoogleTokenResponse set(String fieldName, Object value) { return (GoogleTokenResponse) super.set(fieldName, value); } @Override public GoogleTokenResponse clone() { return (GoogleTokenResponse) super.clone(); } }
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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.DataStoreCredentialRefreshListener; import com.google.api.client.auth.oauth2.TokenRequest; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.json.webtoken.JsonWebToken; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Joiner; import com.google.api.client.util.Lists; import com.google.api.client.util.PemReader; import com.google.api.client.util.Preconditions; import com.google.api.client.util.SecurityUtils; import com.google.api.client.util.store.DataStoreFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Arrays; import java.util.Collection; import java.util.Collections; /** * Thread-safe Google-specific implementation of the OAuth 2.0 helper for accessing protected * resources using an access token, as well as optionally refreshing the access token when it * expires using a refresh token. * * <p> * There are three modes supported: access token only, refresh token flow, and service account flow * (with or without impersonating a user). * </p> * * <p> * If all you have is an access token, you simply pass the {@link TokenResponse} to the credential * using {@link Builder#setFromTokenResponse(TokenResponse)}. Google credential uses * {@link BearerToken#authorizationHeaderAccessMethod()} as the access method. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialWithAccessTokenOnly( HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return new GoogleCredential().setFromTokenResponse(tokenResponse); } * </pre> * * <p> * If you have a refresh token, it is similar to the case of access token only, but you additionally * need to pass the credential the client secrets using * {@link Builder#setClientSecrets(GoogleClientSecrets)} or * {@link Builder#setClientSecrets(String, String)}. Google credential uses * {@link GoogleOAuthConstants#TOKEN_SERVER_URL} as the token server URL, and * {@link ClientParametersAuthentication} with the client ID and secret as the client * authentication. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setClientSecrets(clientSecrets) .build() .setFromTokenResponse(tokenResponse); } * </pre> * * <p> * The <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount">service account * flow</a> is used when you want to access data owned by your client application. You download the * private key in a {@code .p12} file from the Google APIs Console. Use * {@link Builder#setServiceAccountId(String)}, * {@link Builder#setServiceAccountPrivateKeyFromP12File(File)}, and * {@link Builder#setServiceAccountScopes(Collection)}. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialForServiceAccount( HttpTransport transport, JsonFactory jsonFactory, String serviceAccountId, Collection&lt;String&gt; serviceAccountScopes, File p12File) throws GeneralSecurityException, IOException { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(serviceAccountId) .setServiceAccountScopes(serviceAccountScopes) .setServiceAccountPrivateKeyFromP12File(p12File) .build(); } * </pre> * * <p> * You can also use the service account flow to impersonate a user in a domain that you own. This is * very similar to the service account flow above, but you additionally call * {@link Builder#setServiceAccountUser(String)}. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialForServiceAccountImpersonateUser( HttpTransport transport, JsonFactory jsonFactory, String serviceAccountId, Collection&lt;String&gt; serviceAccountScopes, File p12File, String serviceAccountUser) throws GeneralSecurityException, IOException { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(serviceAccountId) .setServiceAccountScopes(serviceAccountScopes) .setServiceAccountPrivateKeyFromP12File(p12File) .setServiceAccountUser(serviceAccountUser) .build(); } * </pre> * * <p> * If you need to persist the access token in a data store, use {@link DataStoreFactory} and * {@link Builder#addRefreshListener(CredentialRefreshListener)} with * {@link DataStoreCredentialRefreshListener}. * </p> * * <p> * If you have a custom request initializer, request execute interceptor, or unsuccessful response * handler, take a look at the sample usage for {@link HttpExecuteInterceptor} and * {@link HttpUnsuccessfulResponseHandler}, which are interfaces that this class also implements. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleCredential extends Credential { /** * Service account ID (typically an e-mail address) or {@code null} if not using the service * account flow. */ private String serviceAccountId; /** * Collection of OAuth scopes to use with the the service account flow or {@code null} if not * using the service account flow. */ private Collection<String> serviceAccountScopes; /** * Private key to use with the the service account flow or {@code null} if not using the service * account flow. */ private PrivateKey serviceAccountPrivateKey; /** * Email address of the user the application is trying to impersonate in the service account flow * or {@code null} for none or if not using the service account flow. */ private String serviceAccountUser; /** * Constructor with the ability to access protected resources, but not refresh tokens. * * <p> * To use with the ability to refresh tokens, use {@link Builder}. * </p> */ public GoogleCredential() { this(new Builder()); } /** * @param builder Google credential builder * * @since 1.14 */ protected GoogleCredential(Builder builder) { super(builder); if (builder.serviceAccountPrivateKey == null) { Preconditions.checkArgument(builder.serviceAccountId == null && builder.serviceAccountScopes == null && builder.serviceAccountUser == null); } else { serviceAccountId = Preconditions.checkNotNull(builder.serviceAccountId); serviceAccountScopes = Collections.unmodifiableCollection(builder.serviceAccountScopes); serviceAccountPrivateKey = builder.serviceAccountPrivateKey; serviceAccountUser = builder.serviceAccountUser; } } @Override public GoogleCredential setAccessToken(String accessToken) { return (GoogleCredential) super.setAccessToken(accessToken); } @Override public GoogleCredential setRefreshToken(String refreshToken) { if (refreshToken != null) { Preconditions.checkArgument( getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null, "Please use the Builder and call setJsonFactory, setTransport and setClientSecrets"); } return (GoogleCredential) super.setRefreshToken(refreshToken); } @Override public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) { return (GoogleCredential) super.setExpirationTimeMilliseconds(expirationTimeMilliseconds); } @Override public GoogleCredential setExpiresInSeconds(Long expiresIn) { return (GoogleCredential) super.setExpiresInSeconds(expiresIn); } @Override public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse) { return (GoogleCredential) super.setFromTokenResponse(tokenResponse); } @Override @Beta protected TokenResponse executeRefreshToken() throws IOException { if (serviceAccountPrivateKey == null) { return super.executeRefreshToken(); } // service accounts: no refresh token; instead use private key to request new access token JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = getClock().currentTimeMillis(); payload.setIssuer(serviceAccountId); payload.setAudience(getTokenServerEncodedUrl()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(serviceAccountScopes)); try { String assertion = JsonWebSignature.signUsingRsaSha256( serviceAccountPrivateKey, getJsonFactory(), header, payload); TokenRequest request = new TokenRequest( getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer"); request.put("assertion", assertion); return request.execute(); } catch (GeneralSecurityException exception) { IOException e = new IOException(); e.initCause(exception); throw e; } } /** * {@link Beta} <br/> * Returns the service account ID (typically an e-mail address) or {@code null} if not using the * service account flow. */ @Beta public final String getServiceAccountId() { return serviceAccountId; } /** * {@link Beta} <br/> * Returns a collection of OAuth scopes to use with the the service account flow or {@code null} * if not using the service account flow. * * <p> * Upgrade warning: in prior version 1.14 this method returned a {@link String}, but starting with * version 1.15 it returns a {@link Collection}. Use {@link #getServiceAccountScopesAsString} to * retrieve a {@link String} with space-separated list of scopes. * </p> */ @Beta public final Collection<String> getServiceAccountScopes() { return serviceAccountScopes; } /** * {@link Beta} <br/> * Returns the space-separated OAuth scopes to use with the the service account flow or * {@code null} if not using the service account flow. * * @since 1.15 */ @Beta public final String getServiceAccountScopesAsString() { return serviceAccountScopes == null ? null : Joiner.on(' ').join(serviceAccountScopes); } /** * {@link Beta} <br/> * Returns the private key to use with the the service account flow or {@code null} if not using * the service account flow. */ @Beta public final PrivateKey getServiceAccountPrivateKey() { return serviceAccountPrivateKey; } /** * {@link Beta} <br/> * Returns the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none or if not using the service account flow. */ @Beta public final String getServiceAccountUser() { return serviceAccountUser; } /** * Google credential builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder extends Credential.Builder { /** Service account ID (typically an e-mail address) or {@code null} for none. */ String serviceAccountId; /** * Collection of OAuth scopes to use with the the service account flow or {@code null} for none. */ Collection<String> serviceAccountScopes; /** Private key to use with the the service account flow or {@code null} for none. */ PrivateKey serviceAccountPrivateKey; /** * Email address of the user the application is trying to impersonate in the service account * flow or {@code null} for none. */ String serviceAccountUser; public Builder() { super(BearerToken.authorizationHeaderAccessMethod()); setTokenServerEncodedUrl(GoogleOAuthConstants.TOKEN_SERVER_URL); } @Override public GoogleCredential build() { return new GoogleCredential(this); } @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(transport); } @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(jsonFactory); } /** * @since 1.9 */ @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } /** * Sets the client identifier and secret. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setClientSecrets(String clientId, String clientSecret) { setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); return this; } /** * Sets the client secrets. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setClientSecrets(GoogleClientSecrets clientSecrets) { Details details = clientSecrets.getDetails(); setClientAuthentication( new ClientParametersAuthentication(details.getClientId(), details.getClientSecret())); return this; } /** * {@link Beta} <br/> * Returns the service account ID (typically an e-mail address) or {@code null} for none. */ @Beta public final String getServiceAccountId() { return serviceAccountId; } /** * {@link Beta} <br/> * Sets the service account ID (typically an e-mail address) or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountId(String serviceAccountId) { this.serviceAccountId = serviceAccountId; return this; } /** * {@link Beta} <br/> * Returns a collection of OAuth scopes to use with the the service account flow or {@code null} * for none. * * <p> * Upgrade warning: in prior version 1.14 this method returned a {@link String}, but starting * with version 1.15 it returns a {@link Collection}. * </p> */ @Beta public final Collection<String> getServiceAccountScopes() { return serviceAccountScopes; } /** * {@link Beta} <br/> * Sets the space-separated OAuth scopes to use with the the service account flow or * {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param serviceAccountScopes list of scopes to be joined by a space separator (or a single * value containing multiple space-separated scopes) * @deprecated (scheduled to be removed in 1.16) Use * {@link #setServiceAccountScopes(Collection)} instead. */ @Deprecated @Beta public Builder setServiceAccountScopes(String... serviceAccountScopes) { return setServiceAccountScopes( serviceAccountScopes == null ? null : Arrays.asList(serviceAccountScopes)); } /** * {@link Beta} <br/> * Sets the space-separated OAuth scopes to use with the the service account flow or * {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param serviceAccountScopes list of scopes to be joined by a space separator (or a single * value containing multiple space-separated scopes) * @deprecated (scheduled to be removed in 1.16) Use * {@link #setServiceAccountScopes(Collection)} instead. */ @Deprecated @Beta public Builder setServiceAccountScopes(Iterable<String> serviceAccountScopes) { this.serviceAccountScopes = serviceAccountScopes == null ? null : Lists.newArrayList(serviceAccountScopes); return this; } /** * {@link Beta} <br/> * Sets the space-separated OAuth scopes to use with the the service account flow or * {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param serviceAccountScopes collection of scopes to be joined by a space separator (or a * single value containing multiple space-separated scopes) * @since 1.15 */ @Beta public Builder setServiceAccountScopes(Collection<String> serviceAccountScopes) { this.serviceAccountScopes = serviceAccountScopes; return this; } /** * {@link Beta} <br/> * Returns the private key to use with the the service account flow or {@code null} for none. */ @Beta public final PrivateKey getServiceAccountPrivateKey() { return serviceAccountPrivateKey; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountPrivateKey(PrivateKey serviceAccountPrivateKey) { this.serviceAccountPrivateKey = serviceAccountPrivateKey; return this; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param p12File input stream to the p12 file (closed at the end of this method in a finally * block) */ @Beta public Builder setServiceAccountPrivateKeyFromP12File(File p12File) throws GeneralSecurityException, IOException { serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), new FileInputStream(p12File), "notasecret", "privatekey", "notasecret"); return this; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param pemFile input stream to the PEM file (closed at the end of this method in a finally * block) * @since 1.13 */ @Beta public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile) throws GeneralSecurityException, IOException { byte[] bytes = PemReader.readFirstSectionAndClose(new FileReader(pemFile), "PRIVATE KEY") .getBase64DecodedBytes(); serviceAccountPrivateKey = SecurityUtils.getRsaKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(bytes)); return this; } /** * {@link Beta} <br/> * Returns the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none. */ @Beta public final String getServiceAccountUser() { return serviceAccountUser; } /** * {@link Beta} <br/> * Sets the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountUser(String serviceAccountUser) { this.serviceAccountUser = serviceAccountUser; return this; } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(tokenServerUrl); } @Override public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { return (Builder) super.setTokenServerEncodedUrl(tokenServerEncodedUrl); } @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { return (Builder) super.setClientAuthentication(clientAuthentication); } } }
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.googleapis.auth.oauth2; import com.google.api.client.util.Beta; /** * Constants for Google's OAuth 2.0 implementation. * * @since 1.7 * @author Yaniv Inbar */ public class GoogleOAuthConstants { /** Encoded URL of Google's end-user authorization server. */ public static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth"; /** Encoded URL of Google's token server. */ public static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token"; /** * {@link Beta} <br/> * Encoded URL of Google's public certificates. * * @since 1.15 */ @Beta public static final String DEFAULT_PUBLIC_CERTS_ENCODED_URL = "https://www.googleapis.com/oauth2/v1/certs"; /** * Redirect URI to use for an installed application as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2InstalledApp.html">Using OAuth 2.0 for * Installed Applications</a>. */ public static final String OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; private GoogleOAuthConstants() { } }
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. */ /** * Google's additions to OAuth 2.0 authorization as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2.html">Using OAuth 2.0 to Access Google * APIs</a>. * * <p> * Before using this library, you must register your application at the <a * href="https://code.google.com/apis/console#access">APIs Console</a>. The result of this * registration process is a set of values that are known to both Google and your application, such * as the "Client ID", "Client Secret", and "Redirect URIs". * </p> * * <p> * These are the typical steps of the web server flow based on an authorization code, as specified * in <a href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for * Web Server Applications</a>: * <ul> * <li>Redirect the end user in the browser to the authorization page using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl} to grant * your application access to the end user's protected data.</li> * <li>Process the authorization response using * {@link com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl} to parse the authorization * code.</li> * <li>Request an access token and possibly a refresh token using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest}.</li> * <li>Access protected resources using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleCredential}. Expired access tokens will * automatically be refreshed using the refresh token (if applicable).</li> * </ul> * </p> * * <p> * These are the typical steps of the the browser-based client flow specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html">Using OAuth 2.0 for * Client-side Applications</a>: * <ul> * <li>Redirect the end user in the browser to the authorization page using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleBrowserClientRequestUrl} to grant your * browser application access to the end user's protected data.</li> * <li>Use the <a href="http://code.google.com/p/google-api-javascript-client/">Google API Client * library for JavaScript</a> to process the access token found in the URL fragment at the redirect * URI registered at the <a href="https://code.google.com/apis/console#access">APIs Console</a>. * </li> * </ul> * </p> * * @since 1.7 * @author Yaniv Inbar */ package com.google.api.client.googleapis.auth.oauth2;
Java
/* * Copyright (c) 2012 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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.Credential.AccessMethod; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.CredentialStore; import com.google.api.client.auth.oauth2.StoredCredential; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.util.Collection; /** * Thread-safe Google OAuth 2.0 authorization code flow that manages and persists end-user * credentials. * * <p> * This is designed to simplify the flow in which an end-user authorizes the application to access * their protected data, and then the application has access to their data based on an access token * and a refresh token to refresh that access token when it expires. * </p> * * <p> * The first step is to call {@link #loadCredential(String)} based on the known user ID to check if * the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and * direct the end-user's browser to an authorization page. The web browser will then redirect to the * redirect URL with a {@code "code"} query parameter which can then be used to request an access * token using {@link #newTokenRequest(String)}. Finally, use * {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for * accessing protected resources. * </p> * * <p> * The default for the {@code approval_prompt} and {@code access_type} parameters is {@code null}. * For web applications that means {@code "approval_prompt=auto&access_type=online"} and for * installed applications that means {@code "approval_prompt=force&access_type=offline"}. To * override the default, you need to explicitly call {@link Builder#setApprovalPrompt(String)} and * {@link Builder#setAccessType(String)}. * </p> * * @author Yaniv Inbar * @since 1.7 */ @SuppressWarnings("deprecation") public class GoogleAuthorizationCodeFlow extends AuthorizationCodeFlow { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ private final String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request offline * access) or {@code null} for the default behavior. */ private final String accessType; /** * {@link Beta} <br/> * Constructs a new {@link GoogleAuthorizationCodeFlow}. * * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes list of scopes to be joined by a space separator (or a single value containing * multiple space-separated scopes) * @deprecated (scheduled to be removed in 1.16) Use {@link * #GoogleAuthorizationCodeFlow(HttpTransport, JsonFactory, String, String, * Collection)} instead. * * @since 1.14 */ @Beta @Deprecated public GoogleAuthorizationCodeFlow(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Iterable<String> scopes) { this(new Builder(transport, jsonFactory, clientId, clientSecret, scopes)); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes collection of scopes to be joined by a space separator * * @since 1.15 */ public GoogleAuthorizationCodeFlow(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Collection<String> scopes) { this(new Builder(transport, jsonFactory, clientId, clientSecret, scopes)); } /** * @param builder Google authorization code flow builder * * @since 1.14 */ protected GoogleAuthorizationCodeFlow(Builder builder) { super(builder); accessType = builder.accessType; approvalPrompt = builder.approvalPrompt; } @Override public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { // don't need to specify clientId & clientSecret because specifying clientAuthentication // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(), getTokenServerEncodedUrl(), "", "", authorizationCode, "").setClientAuthentication( getClientAuthentication()) .setRequestInitializer(getRequestInitializer()).setScopes(getScopes()); } @Override public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() { // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeRequestUrl( getAuthorizationServerEncodedUrl(), getClientId(), "", getScopes()).setAccessType( accessType).setApprovalPrompt(approvalPrompt); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } /** * Google authorization code flow builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder extends AuthorizationCodeFlow.Builder { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request * offline access) or {@code null} for the default behavior. */ String accessType; /** * {@link Beta} <br/> * Constructs a new {@link Builder}. * * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes list of scopes to be joined by a space separator (or a single value containing * multiple space-separated scopes) * @deprecated (scheduled to be removed in 1.16) Use {@link #GoogleAuthorizationCodeFlow.Builder * (HttpTransport, JsonFactory, String, String, Collection)} instead. */ @Beta @Deprecated public Builder(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Iterable<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientId, clientSecret), clientId, GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(Preconditions.checkNotNull(scopes)); } /** * * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes collection of scopes to be joined by a space separator (or a single value * containing multiple space-separated scopes) * * @since 1.15 */ public Builder(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Collection<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientId, clientSecret), clientId, GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(scopes); } /** * {@link Beta} <br/> * Constructs a new {@link Builder}. * * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientSecrets Google client secrets * @param scopes list of scopes to be joined by a space separator (or a single value containing * multiple space-separated scopes) * @deprecated (scheduled to be removed in 1.16) Use * {@link #GoogleAuthorizationCodeFlow.Builder(HttpTransport, JsonFactory, * GoogleClientSecrets, Collection)} instead. */ @Beta @Deprecated public Builder(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, Iterable<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret()), clientSecrets.getDetails().getClientId(), GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(Preconditions.checkNotNull(scopes)); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientSecrets Google client secrets * @param scopes collection of scopes to be joined by a space separator * * @since 1.15 */ public Builder(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, Collection<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret()), clientSecrets.getDetails().getClientId(), GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(scopes); } @Override public GoogleAuthorizationCodeFlow build() { return new GoogleAuthorizationCodeFlow(this); } @Override public Builder setDataStoreFactory(DataStoreFactory dataStore) throws IOException { return (Builder) super.setDataStoreFactory(dataStore); } @Override public Builder setCredentialDataStore(DataStore<StoredCredential> typedDataStore) { return (Builder) super.setCredentialDataStore(typedDataStore); } @Override public Builder setCredentialCreatedListener( CredentialCreatedListener credentialCreatedListener) { return (Builder) super.setCredentialCreatedListener(credentialCreatedListener); } @Beta @Override @Deprecated public Builder setCredentialStore(CredentialStore credentialStore) { return (Builder) super.setCredentialStore(credentialStore); } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder setScopes(Collection<String> scopes) { Preconditions.checkState(!scopes.isEmpty()); return (Builder) super.setScopes(scopes); } @Override @Beta @Deprecated public Builder setScopes(Iterable<String> scopes) { return (Builder) super.setScopes(scopes); } @Override @Beta @Deprecated public Builder setScopes(String... scopes) { return (Builder) super.setScopes(scopes); } /** * @since 1.11 */ @Override public Builder setMethod(AccessMethod method) { return (Builder) super.setMethod(method); } /** * @since 1.11 */ @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(transport); } /** * @since 1.11 */ @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(jsonFactory); } /** * @since 1.11 */ @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(tokenServerUrl); } /** * @since 1.11 */ @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { return (Builder) super.setClientAuthentication(clientAuthentication); } /** * @since 1.11 */ @Override public Builder setClientId(String clientId) { return (Builder) super.setClientId(clientId); } /** * @since 1.11 */ @Override public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) { return (Builder) super.setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl); } /** * @since 1.11 */ @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior ({@code "auto"} * for web applications and {@code "force"} for installed applications). * * <p> * By default this has the value {@code null}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior ({@code "online"} for web * applications and {@code "offline"} for installed applications). * * <p> * By default this has the value {@code null}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setAccessType(String accessType) { this.accessType = accessType; return this; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } } }
Java
/* * Copyright (c) 2012 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.googleapis.auth.oauth2; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import java.io.IOException; import java.security.GeneralSecurityException; /** * {@link Beta} <br/> * Google ID tokens. * * <p> * Google ID tokens contain useful information about the authorized end user. Google ID tokens are * signed and the signature must be verified using {@link #verify(GoogleIdTokenVerifier)}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ @SuppressWarnings("javadoc") @Beta public class GoogleIdToken extends IdToken { /** * Parses the given ID token string and returns the parsed {@link GoogleIdToken}. * * @param jsonFactory JSON factory * @param idTokenString ID token string * @return parsed Google ID token */ public static GoogleIdToken parse(JsonFactory jsonFactory, String idTokenString) throws IOException { JsonWebSignature jws = JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString); return new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()); } /** * @param header header * @param payload payload * @param signatureBytes bytes of the signature * @param signedContentBytes bytes of the signature content */ public GoogleIdToken( Header header, Payload payload, byte[] signatureBytes, byte[] signedContentBytes) { super(header, payload, signatureBytes, signedContentBytes); } /** * Verifies that this ID token is valid using {@link GoogleIdTokenVerifier#verify(GoogleIdToken)}. */ public boolean verify(GoogleIdTokenVerifier verifier) throws GeneralSecurityException, IOException { return verifier.verify(this); } @Override public Payload getPayload() { return (Payload) super.getPayload(); } /** * {@link Beta} <br/> * Google ID token payload. */ @Beta public static class Payload extends IdToken.Payload { /** Obfuscated Google user ID or {@code null} for none. */ @Key("id") private String userId; /** Client ID of issuee or {@code null} for none. */ @Key("cid") private String issuee; /** Hash of access token or {@code null} for none. */ @Key("token_hash") private String accessTokenHash; /** Hosted domain name if asserted user is a domain managed user or {@code null} for none. */ @Key("hd") private String hostedDomain; /** E-mail of the user or {@code null} if not requested. */ @Key("email") private String email; /** {@code true} if the email is verified. */ @Key("verified_email") private boolean emailVerified; public Payload() { } /** Returns the obfuscated Google user id or {@code null} for none. */ public String getUserId() { return userId; } /** Sets the obfuscated Google user id or {@code null} for none. */ public Payload setUserId(String userId) { this.userId = userId; return this; } /** Returns the client ID of issuee or {@code null} for none. */ public String getIssuee() { return issuee; } /** Sets the client ID of issuee or {@code null} for none. */ public Payload setIssuee(String issuee) { this.issuee = issuee; return this; } /** Returns the hash of access token or {@code null} for none. */ public String getAccessTokenHash() { return accessTokenHash; } /** Sets the hash of access token or {@code null} for none. */ public Payload setAccessTokenHash(String accessTokenHash) { this.accessTokenHash = accessTokenHash; return this; } /** * Returns the hosted domain name if asserted user is a domain managed user or {@code null} for * none. */ public String getHostedDomain() { return hostedDomain; } /** * Sets the hosted domain name if asserted user is a domain managed user or {@code null} for * none. */ public Payload setHostedDomain(String hostedDomain) { this.hostedDomain = hostedDomain; return this; } /** * Returns the e-mail address of the user or {@code null} if it was not requested. * * <p> * Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public String getEmail() { return email; } /** * Sets the e-mail address of the user or {@code null} if it was not requested. * * <p> * Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public Payload setEmail(String email) { this.email = email; return this; } /** * Returns {@code true} if the users e-mail address has been verified by Google. * * <p> * Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public boolean getEmailVerified() { return emailVerified; } /** * Sets whether the users e-mail address has been verified by Google or not. * * <p> * Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public Payload setEmailVerified(boolean emailVerified) { this.emailVerified = emailVerified; return this; } @Override public Payload set(String fieldName, Object value) { return (Payload) super.set(fieldName, value); } @Override public Payload clone() { return (Payload) super.clone(); } } }
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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.BrowserClientRequestUrl; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to * allow the end user to authorize the application to access their protected resources and that * returns the access token to a browser client using a scripting language such as JavaScript, as * specified in <a href="https://developers.google.com/accounts/docs/OAuth2UserAgent">Using OAuth * 2.0 for Client-side Applications</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "token"}. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com", "https://oauth2-login-demo.appspot.com/oauthcallback", Arrays.asList( "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleBrowserClientRequestUrl extends BrowserClientRequestUrl { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ @Key("approval_prompt") private String approvalPrompt; /** * {@link Beta} <br/> * Constructs a new {@link GoogleBrowserClientRequestUrl}. * * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Iterable)}) * * @deprecated (scheduled to be removed in 1.16) Use * {@link #GoogleBrowserClientRequestUrl(String, String, Collection)} instead. */ @Beta @Deprecated public GoogleBrowserClientRequestUrl( String clientId, String redirectUri, Iterable<String> scopes) { super(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleBrowserClientRequestUrl( String clientId, String redirectUri, Collection<String> scopes) { super(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * {@link Beta} <br/> * Constructs a new {@link GoogleBrowserClientRequestUrl}. * * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Iterable)}) * * @deprecated (scheduled to be removed in 1.16) Use * {@link #GoogleBrowserClientRequestUrl(GoogleClientSecrets, String, Collection)} * instead. */ @Beta @Deprecated public GoogleBrowserClientRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Iterable<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleBrowserClientRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Collection<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleBrowserClientRequestUrl setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } @Override public GoogleBrowserClientRequestUrl setResponseTypes(Collection<String> responseTypes) { return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes); } @Override @Beta @Deprecated public GoogleBrowserClientRequestUrl setResponseTypes(String... responseTypes) { return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes); } @Override @Beta @Deprecated public GoogleBrowserClientRequestUrl setResponseTypes(Iterable<String> responseTypes) { return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes); } @Override public GoogleBrowserClientRequestUrl setRedirectUri(String redirectUri) { return (GoogleBrowserClientRequestUrl) super.setRedirectUri(redirectUri); } @Override public GoogleBrowserClientRequestUrl setScopes(Collection<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleBrowserClientRequestUrl) super.setScopes(scopes); } @Override @Beta @Deprecated public GoogleBrowserClientRequestUrl setScopes(String... scopes) { Preconditions.checkArgument(scopes.length != 0); return (GoogleBrowserClientRequestUrl) super.setScopes(scopes); } @Override @Beta @Deprecated public GoogleBrowserClientRequestUrl setScopes(Iterable<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleBrowserClientRequestUrl) super.setScopes(scopes); } @Override public GoogleBrowserClientRequestUrl setClientId(String clientId) { return (GoogleBrowserClientRequestUrl) super.setClientId(clientId); } @Override public GoogleBrowserClientRequestUrl setState(String state) { return (GoogleBrowserClientRequestUrl) super.setState(state); } @Override public GoogleBrowserClientRequestUrl set(String fieldName, Object value) { return (GoogleBrowserClientRequestUrl) super.set(fieldName, value); } @Override public GoogleBrowserClientRequestUrl clone() { return (GoogleBrowserClientRequestUrl) super.clone(); } }
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.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl; import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to * allow the end user to authorize the application to access their protected resources and that * returns an authorization code, as specified in <a * href="https://developers.google.com/accounts/docs/OAuth2WebServer">Using OAuth 2.0 for Web Server * Applications</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "code"}. Use * {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user * grants/denies the request. Using the authorization code in this response, use * {@link GoogleAuthorizationCodeTokenRequest} to request the access token. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new GoogleAuthorizationCodeRequestUrl("812741506391.apps.googleusercontent.com", "https://oauth2-login-demo.appspot.com/code", Arrays.asList( "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleAuthorizationCodeRequestUrl extends AuthorizationCodeRequestUrl { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ @Key("approval_prompt") private String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request offline * access) or {@code null} for the default behavior. */ @Key("access_type") private String accessType; /** * {@link Beta} <br/> * Constructs a new {@link GoogleAuthorizationCodeRequestUrl}. * * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Iterable)}) * * @deprecated (scheduled to be removed in 1.16) Use * {@link #GoogleAuthorizationCodeRequestUrl(String, String, Collection)} instead. */ @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl( String clientId, String redirectUri, Iterable<String> scopes) { this(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId, redirectUri, scopes); } /** * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl( String clientId, String redirectUri, Collection<String> scopes) { this(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId, redirectUri, scopes); } /** * {@link Beta} <br/> * Constructs a new {@link GoogleAuthorizationCodeRequestUrl}. * * @param authorizationServerEncodedUrl authorization server encoded URL * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Iterable)}) * * @deprecated (scheduled to be removed in 1.16) Use * {@link #GoogleAuthorizationCodeRequestUrl(String, String, String, Collection)} * instead. * * @since 1.12 */ @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId, String redirectUri, Iterable<String> scopes) { super(authorizationServerEncodedUrl, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * @param authorizationServerEncodedUrl authorization server encoded URL * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId, String redirectUri, Collection<String> scopes) { super(authorizationServerEncodedUrl, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * {@link Beta} <br/> * Constructs a new {@link GoogleAuthorizationCodeRequestUrl}. * * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Iterable)}) * * @deprecated (scheduled to be removed in 1.16) Use {@link * #GoogleAuthorizationCodeRequestUrl(GoogleClientSecrets, String, Collection)} * instead. */ @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Iterable<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Collection<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleAuthorizationCodeRequestUrl setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } /** * Sets the access type ({@code "online"} to request online access or {@code "offline"} to request * offline access) or {@code null} for the default behavior of {@code "online"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleAuthorizationCodeRequestUrl setAccessType(String accessType) { this.accessType = accessType; return this; } @Override @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl setResponseTypes(String... responseTypes) { return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl setResponseTypes(Iterable<String> responseTypes) { return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override public GoogleAuthorizationCodeRequestUrl setResponseTypes(Collection<String> responseTypes) { return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override public GoogleAuthorizationCodeRequestUrl setRedirectUri(String redirectUri) { Preconditions.checkNotNull(redirectUri); return (GoogleAuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri); } @Override @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl setScopes(String... scopes) { Preconditions.checkArgument(scopes.length != 0); return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override @Beta @Deprecated public GoogleAuthorizationCodeRequestUrl setScopes(Iterable<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeRequestUrl setScopes(Collection<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeRequestUrl setClientId(String clientId) { return (GoogleAuthorizationCodeRequestUrl) super.setClientId(clientId); } @Override public GoogleAuthorizationCodeRequestUrl setState(String state) { return (GoogleAuthorizationCodeRequestUrl) super.setState(state); } @Override public GoogleAuthorizationCodeRequestUrl set(String fieldName, Object value) { return (GoogleAuthorizationCodeRequestUrl) super.set(fieldName, value); } @Override public GoogleAuthorizationCodeRequestUrl clone() { return (GoogleAuthorizationCodeRequestUrl) super.clone(); } }
Java
/* * Copyright (c) 2012 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.googleapis.auth.oauth2; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.JsonToken; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import com.google.api.client.util.SecurityUtils; import com.google.api.client.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * {@link Beta} <br/> * Thread-safe Google ID token verifier. * * <p> * The public keys are loaded from the public certificates endpoint at * {@link #getPublicCertsEncodedUrl} and cached in this instance. Therefore, for maximum efficiency, * applications should use a single globally-shared instance of the {@link GoogleIdTokenVerifier}. * </p> * * <p> * Use {@link #verify(GoogleIdToken)} to verify a Google ID token, and then * {@link GoogleIdToken#verifyAudience} to verify the client ID. <br/> * Samples usage: * </p> * * <pre> public static GoogleIdTokenVerifier verifier; public static void initVerifier(HttpTransport transport, JsonFactory jsonFactory) { verifier = new GoogleIdTokenVerifier(transport, jsonFactory); } public static boolean verifyToken(GoogleIdToken idToken, Collection<String> trustedClientIds) throws GeneralSecurityException, IOException { return verifier.verify(idToken) && idToken.verifyAudience(trustedClientIds); } * </pre> * @since 1.7 */ @Beta public class GoogleIdTokenVerifier { /** Pattern for the max-age header element of Cache-Control. */ private static final Pattern MAX_AGE_PATTERN = Pattern.compile("\\s*max-age\\s*=\\s*(\\d+)\\s*"); /** Seconds of time skew to accept. */ private static final long TIME_SKEW_SECONDS = 300; /** JSON factory. */ private final JsonFactory jsonFactory; /** Public keys or {@code null} for none. */ private List<PublicKey> publicKeys; /** * Expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} or {@code 0} * for none. */ private long expirationTimeMilliseconds; /** HTTP transport. */ private final HttpTransport transport; /** Lock on the public keys. */ private final Lock lock = new ReentrantLock(); /** Clock to use for expiration checks. */ private final Clock clock; /** Public certificates encoded URL. */ private final String publicCertsEncodedUrl; /** * Constructor with required parameters. * * <p> * Use {@link GoogleIdTokenVerifier.Builder} to specify client IDs. * </p> * * @param transport HTTP transport * @param jsonFactory JSON factory */ public GoogleIdTokenVerifier(HttpTransport transport, JsonFactory jsonFactory) { this(new Builder(transport, jsonFactory)); } /** * @param builder builder * * @since 1.14 */ protected GoogleIdTokenVerifier(Builder builder) { transport = builder.transport; jsonFactory = builder.jsonFactory; clock = builder.clock; publicCertsEncodedUrl = builder.publicCertsEncodedUrl; } /** * Returns the HTTP transport. * * @since 1.14 */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Returns the public certificates encoded URL. * * @since 1.15 */ public final String getPublicCertsEncodedUrl() { return publicCertsEncodedUrl; } /** Returns the public keys or {@code null} for none. */ public final List<PublicKey> getPublicKeys() { return publicKeys; } /** * Returns the expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} * or {@code 0} for none. */ public final long getExpirationTimeMilliseconds() { return expirationTimeMilliseconds; } /** * Verifies that the given ID token is valid using the cached public keys. * * It verifies: * * <ul> * <li>The RS256 signature, which uses RSA and SHA-256 based on the public keys downloaded from * the public certificate endpoint.</li> * <li>The current time against the issued at and expiration time (allowing for a 5 minute clock * skew).</li> * <li>The issuer is {@code "accounts.google.com"}.</li> * </ul> * * @param idToken Google ID token * @return {@code true} if verified successfully or {@code false} if failed */ public boolean verify(GoogleIdToken idToken) throws GeneralSecurityException, IOException { // check the payload if (!idToken.verifyIssuer("accounts.google.com") || !idToken.verifyTime(clock.currentTimeMillis(), TIME_SKEW_SECONDS)) { return false; } // verify signature lock.lock(); try { // load public keys; expire 5 minutes (300 seconds) before actual expiration time if (publicKeys == null || clock.currentTimeMillis() + TIME_SKEW_SECONDS * 1000 > expirationTimeMilliseconds) { loadPublicCerts(); } for (PublicKey publicKey : publicKeys) { if (idToken.verifySignature(publicKey)) { return true; } } } finally { lock.unlock(); } return false; } /** * Verifies that the given ID token is valid using {@link #verify(GoogleIdToken)} and returns the * ID token if succeeded. * * @param idTokenString Google ID token string * @return Google ID token if verified successfully or {@code null} if failed * @since 1.9 */ public GoogleIdToken verify(String idTokenString) throws GeneralSecurityException, IOException { GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, idTokenString); return verify(idToken) ? idToken : null; } /** * Downloads the public keys from the public certificates endpoint at * {@link #getPublicCertsEncodedUrl}. * * <p> * This method is automatically called if the public keys have not yet been initialized or if the * expiration time is very close, so normally this doesn't need to be called. Only call this * method explicitly to force the public keys to be updated. * </p> */ public GoogleIdTokenVerifier loadPublicCerts() throws GeneralSecurityException, IOException { lock.lock(); try { publicKeys = new ArrayList<PublicKey>(); // HTTP request to public endpoint CertificateFactory factory = SecurityUtils.getX509CertificateFactory(); HttpResponse certsResponse = transport.createRequestFactory() .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute(); expirationTimeMilliseconds = clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000; // parse each public key in the JSON response JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT); try { while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); String certValue = parser.getText(); X509Certificate x509Cert = (X509Certificate) factory.generateCertificate( new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue))); publicKeys.add(x509Cert.getPublicKey()); } publicKeys = Collections.unmodifiableList(publicKeys); } finally { parser.close(); } return this; } finally { lock.unlock(); } } /** * Gets the cache time in seconds. "max-age" in "Cache-Control" header and "Age" header are * considered. * * @param httpHeaders the http header of the response * @return the cache time in seconds or zero if the response should not be cached */ long getCacheTimeInSec(HttpHeaders httpHeaders) { long cacheTimeInSec = 0; if (httpHeaders.getCacheControl() != null) { for (String arg : httpHeaders.getCacheControl().split(",")) { Matcher m = MAX_AGE_PATTERN.matcher(arg); if (m.matches()) { cacheTimeInSec = Long.valueOf(m.group(1)); break; } } } if (httpHeaders.getAge() != null) { cacheTimeInSec -= httpHeaders.getAge(); } return Math.max(0, cacheTimeInSec); } /** * {@link Beta} <br/> * Builder for {@link GoogleIdTokenVerifier}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.9 */ @Beta public static class Builder { /** HTTP transport. */ final HttpTransport transport; /** JSON factory. */ final JsonFactory jsonFactory; /** Public certificates encoded URL. */ String publicCertsEncodedUrl = GoogleOAuthConstants.DEFAULT_PUBLIC_CERTS_ENCODED_URL; /** Clock. */ Clock clock = Clock.SYSTEM; /** * Returns an instance of a new builder. * * @param transport HTTP transport * @param jsonFactory JSON factory */ public Builder(HttpTransport transport, JsonFactory jsonFactory) { this.transport = Preconditions.checkNotNull(transport); this.jsonFactory = Preconditions.checkNotNull(jsonFactory); } /** Builds a new instance of {@link GoogleIdTokenVerifier}. */ public GoogleIdTokenVerifier build() { return new GoogleIdTokenVerifier(this); } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Returns the public certificates encoded URL. * * @since 1.15 */ public final String getPublicCertsEncodedUrl() { return publicCertsEncodedUrl; } /** * Sets the public certificates encoded URL. * * <p> * The default value is {@link GoogleOAuthConstants#DEFAULT_PUBLIC_CERTS_ENCODED_URL}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.15 */ public Builder setPublicCertsEncodedUrl(String publicCertsEncodedUrl) { this.publicCertsEncodedUrl = Preconditions.checkNotNull(publicCertsEncodedUrl); return this; } /** * Returns the clock. * * @since 1.14 */ public final Clock getClock() { return clock; } /** * Sets the clock. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setClock(Clock clock) { this.clock = Preconditions.checkNotNull(clock); return this; } } }
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.googleapis.auth.oauth2; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.List; /** * OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets">client_secrets.json * file format</a>. * * <p> * Sample usage: * </p> * * <pre> static GoogleClientSecrets loadClientSecretsResource(JsonFactory jsonFactory) throws IOException { return GoogleClientSecrets.load( jsonFactory, SampleClass.class.getResourceAsStream("/client_secrets.json")); } * </pre> * * @since 1.7 * @author Yaniv Inbar */ public final class GoogleClientSecrets extends GenericJson { /** Details for installed applications. */ @Key private Details installed; /** Details for web applications. */ @Key private Details web; /** Returns the details for installed applications. */ public Details getInstalled() { return installed; } /** Sets the details for installed applications. */ public GoogleClientSecrets setInstalled(Details installed) { this.installed = installed; return this; } /** Returns the details for web applications. */ public Details getWeb() { return web; } /** Sets the details for web applications. */ public GoogleClientSecrets setWeb(Details web) { this.web = web; return this; } /** Returns the details for either installed or web applications. */ public Details getDetails() { // that web or installed, but not both Preconditions.checkArgument((web == null) != (installed == null)); return web == null ? installed : web; } /** Client credential details. */ public static final class Details extends GenericJson { /** Client ID. */ @Key("client_id") private String clientId; /** Client secret. */ @Key("client_secret") private String clientSecret; /** Redirect URIs. */ @Key("redirect_uris") private List<String> redirectUris; /** Authorization server URI. */ @Key("auth_uri") private String authUri; /** Token server URI. */ @Key("token_uri") private String tokenUri; /** Returns the client ID. */ public String getClientId() { return clientId; } /** Sets the client ID. */ public Details setClientId(String clientId) { this.clientId = clientId; return this; } /** Returns the client secret. */ public String getClientSecret() { return clientSecret; } /** Sets the client secret. */ public Details setClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } /** Returns the redirect URIs. */ public List<String> getRedirectUris() { return redirectUris; } /** Sets the redirect URIs. */ public Details setRedirectUris(List<String> redirectUris) { this.redirectUris = redirectUris; return this; } /** Returns the authorization server URI. */ public String getAuthUri() { return authUri; } /** Sets the authorization server URI. */ public Details setAuthUri(String authUri) { this.authUri = authUri; return this; } /** Returns the token server URI. */ public String getTokenUri() { return tokenUri; } /** Sets the token server URI. */ public Details setTokenUri(String tokenUri) { this.tokenUri = tokenUri; return this; } @Override public Details set(String fieldName, Object value) { return (Details) super.set(fieldName, value); } @Override public Details clone() { return (Details) super.clone(); } } @Override public GoogleClientSecrets set(String fieldName, Object value) { return (GoogleClientSecrets) super.set(fieldName, value); } @Override public GoogleClientSecrets clone() { return (GoogleClientSecrets) super.clone(); } /** * {@link Beta} <br/> * Loads the {@code client_secrets.json} file from the given input stream. * * @deprecated (scheduled to be removed in 1.16) Use {@link #load(JsonFactory, Reader)} instead. */ @Deprecated @Beta public static GoogleClientSecrets load(JsonFactory jsonFactory, InputStream inputStream) throws IOException { return jsonFactory.fromInputStream(inputStream, GoogleClientSecrets.class); } /** * Loads the {@code client_secrets.json} file from the given reader. * * @since 1.15 */ public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException { return jsonFactory.fromReader(reader, GoogleClientSecrets.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.googleapis.auth.clientlogin; 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.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.UrlEncodedContent; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.StringUtils; import com.google.api.client.util.Strings; import java.io.IOException; /** * {@link Beta} <br/> * Client Login authentication method as described in <a * href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html" >ClientLogin for * Installed Applications</a>. * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class ClientLogin { /** * HTTP transport required for executing request in {@link #authenticate()}. * * @since 1.3 */ public HttpTransport transport; /** * URL for the Client Login authorization server. * * <p> * By default this is {@code "https://www.google.com"}, but it may be overridden for testing * purposes. * </p> * * @since 1.3 */ public GenericUrl serverUrl = new GenericUrl("https://www.google.com"); /** * Short string identifying your application for logging purposes of the form: * "companyName-applicationName-versionID". */ @Key("source") public String applicationName; /** * Name of the Google service you're requesting authorization for, for example {@code "cl"} for * Google Calendar. */ @Key("service") public String authTokenType; /** User's full email address. */ @Key("Email") public String username; /** User's password. */ @Key("Passwd") public String password; /** * Type of account to request authorization for. Possible values are: * * <ul> * <li>GOOGLE (get authorization for a Google account only)</li> * <li>HOSTED (get authorization for a hosted account only)</li> * <li>HOSTED_OR_GOOGLE (get authorization first for a hosted account; if attempt fails, get * authorization for a Google account)</li> * </ul> * * Use HOSTED_OR_GOOGLE if you're not sure which type of account you want authorization for. If * the user information matches both a hosted and a Google account, only the hosted account is * authorized. * * @since 1.1 */ @Key public String accountType; /** (optional) Token representing the specific CAPTCHA challenge. */ @Key("logintoken") public String captchaToken; /** (optional) String entered by the user as an answer to a CAPTCHA challenge. */ @Key("logincaptcha") public String captchaAnswer; /** * Key/value data to parse a success response. * * <p> * Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, Response response) { return transport.createRequestFactory(response); } * </pre> * * <p> * If you have a custom request initializer, take a look at the sample usage for * {@link HttpExecuteInterceptor}, which this class also implements. * </p> */ public static final class Response implements HttpExecuteInterceptor, HttpRequestInitializer { /** Authentication token. */ @Key("Auth") public String auth; /** Returns the authorization header value to use based on the authentication token. */ public String getAuthorizationHeaderValue() { return ClientLogin.getAuthorizationHeaderValue(auth); } public void initialize(HttpRequest request) { request.setInterceptor(this); } public void intercept(HttpRequest request) { request.getHeaders().setAuthorization(getAuthorizationHeaderValue()); } } /** Key/value data to parse an error response. */ public static final class ErrorInfo { @Key("Error") public String error; @Key("Url") public String url; @Key("CaptchaToken") public String captchaToken; @Key("CaptchaUrl") public String captchaUrl; } /** * Authenticates based on the provided field values. * * @throws ClientLoginResponseException if the authentication response has an error code, such as * for a CAPTCHA challenge. */ public Response authenticate() throws IOException { GenericUrl url = serverUrl.clone(); url.appendRawPath("/accounts/ClientLogin"); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this)); request.setParser(AuthKeyValueParser.INSTANCE); request.setContentLoggingLimit(0); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); // check for an HTTP success response (2xx) if (response.isSuccessStatusCode()) { return response.parseAs(Response.class); } HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // On error, throw a ClientLoginResponseException with the parsed error details ErrorInfo details = response.parseAs(ErrorInfo.class); String detailString = details.toString(); StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); throw new ClientLoginResponseException(builder, details); } /** * Returns Google Login {@code "Authorization"} header value based on the given authentication * token. * * @since 1.13 */ public static String getAuthorizationHeaderValue(String authToken) { return "GoogleLogin auth=" + authToken; } }
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.googleapis.auth.clientlogin; import com.google.api.client.googleapis.auth.clientlogin.ClientLogin.ErrorInfo; import com.google.api.client.http.HttpResponseException; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Exception thrown when an error status code is detected in an HTTP response to a Google * ClientLogin request in {@link ClientLogin} . * * <p> * To get the structured details, use {@link #getDetails()}. * </p> * * @since 1.7 * @author Yaniv Inbar */ @Beta public class ClientLoginResponseException extends HttpResponseException { private static final long serialVersionUID = 4974317674023010928L; /** Error details or {@code null} for none. */ private final transient ErrorInfo details; /** * @param builder builder * @param details error details or {@code null} for none */ ClientLoginResponseException(Builder builder, ErrorInfo details) { super(builder); this.details = details; } /** Return the error details or {@code null} for none. */ public final ErrorInfo getDetails() { return details; } }
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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Google's legacy ClientLogin authentication method as described in <a * href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html">ClientLogin for * Installed Applications</a>. * * @since 1.0 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.auth.clientlogin;
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.googleapis.auth.clientlogin; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.GenericData; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Types; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.Map; /** * {@link Beta} <br/> * HTTP parser for Google response to an Authorization request. * * @since 1.10 * @author Yaniv Inbar */ @Beta final class AuthKeyValueParser implements ObjectParser { /** Singleton instance. */ public static final AuthKeyValueParser INSTANCE = new AuthKeyValueParser(); public String getContentType() { return "text/plain"; } public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException { response.setContentLoggingLimit(0); InputStream content = response.getContent(); try { return parse(content, dataClass); } finally { content.close(); } } public <T> T parse(InputStream content, Class<T> dataClass) throws IOException { ClassInfo classInfo = ClassInfo.of(dataClass); T newInstance = Types.newInstance(dataClass); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); while (true) { String line = reader.readLine(); if (line == null) { break; } int equals = line.indexOf('='); String key = line.substring(0, equals); String value = line.substring(equals + 1); // get the field from the type information Field field = classInfo.getField(key); if (field != null) { Class<?> fieldClass = field.getType(); Object fieldValue; if (fieldClass == boolean.class || fieldClass == Boolean.class) { fieldValue = Boolean.valueOf(value); } else { fieldValue = value; } FieldInfo.setFieldValue(field, newInstance, fieldValue); } else if (GenericData.class.isAssignableFrom(dataClass)) { GenericData data = (GenericData) newInstance; data.set(key, value); } else if (Map.class.isAssignableFrom(dataClass)) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance; map.put(key, value); } } return newInstance; } private AuthKeyValueParser() { } public <T> T parseAndClose(InputStream in, Charset charset, Class<T> dataClass) throws IOException { Reader reader = new InputStreamReader(in, charset); return parseAndClose(reader, dataClass); } public Object parseAndClose(InputStream in, Charset charset, Type dataType) { throw new UnsupportedOperationException( "Type-based parsing is not yet supported -- use Class<T> instead"); } public <T> T parseAndClose(Reader reader, Class<T> dataClass) throws IOException { try { ClassInfo classInfo = ClassInfo.of(dataClass); T newInstance = Types.newInstance(dataClass); BufferedReader breader = new BufferedReader(reader); while (true) { String line = breader.readLine(); if (line == null) { break; } int equals = line.indexOf('='); String key = line.substring(0, equals); String value = line.substring(equals + 1); // get the field from the type information Field field = classInfo.getField(key); if (field != null) { Class<?> fieldClass = field.getType(); Object fieldValue; if (fieldClass == boolean.class || fieldClass == Boolean.class) { fieldValue = Boolean.valueOf(value); } else { fieldValue = value; } FieldInfo.setFieldValue(field, newInstance, fieldValue); } else if (GenericData.class.isAssignableFrom(dataClass)) { GenericData data = (GenericData) newInstance; data.set(key, value); } else if (Map.class.isAssignableFrom(dataClass)) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance; map.put(key, value); } } return newInstance; } finally { reader.close(); } } public Object parseAndClose(Reader reader, Type dataType) { throw new UnsupportedOperationException( "Type-based parsing is not yet supported -- use Class<T> instead"); } }
Java
/* * Copyright (c) 2013 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.googleapis; import com.google.api.client.util.SecurityUtils; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utility class for the Google API Client Library. * * @since 1.12 * @author rmistry@google.com (Ravi Mistry) */ public final class GoogleUtils { // NOTE: Integer instead of int so compiler thinks it isn't a constant, so it won't inline it /** * Major part of the current release version. * * @since 1.14 */ public static final Integer MAJOR_VERSION = 1; /** * Minor part of the current release version. * * @since 1.14 */ public static final Integer MINOR_VERSION = 16; /** * Bug fix part of the current release version. * * @since 1.14 */ public static final Integer BUGFIX_VERSION = 0; /** Current release version. */ // NOTE: toString() so compiler thinks it isn't a constant, so it won't inline it public static final String VERSION = (MAJOR_VERSION + "." + MINOR_VERSION + "." + BUGFIX_VERSION + "-rc-SNAPSHOT").toString(); /** Cached value for {@link #getCertificateTrustStore()}. */ static KeyStore certTrustStore; /** * Returns the key store for trusted root certificates to use for Google APIs. * * <p> * Value is cached, so subsequent access is fast. * </p> * * @since 1.14 */ public static synchronized KeyStore getCertificateTrustStore() throws IOException, GeneralSecurityException { if (certTrustStore == null) { certTrustStore = SecurityUtils.getJavaKeyStore(); InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks"); SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret"); } return certTrustStore; } private GoogleUtils() { } }
Java
/* * Copyright (c) 2013 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.googleapis.batch; import com.google.api.client.http.AbstractHttpContent; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; /** * HTTP request wrapped as a content part of a multipart/mixed request. * * @author Yaniv Inbar */ class HttpRequestContent extends AbstractHttpContent { static final String NEWLINE = "\r\n"; /** HTTP request. */ private final HttpRequest request; HttpRequestContent(HttpRequest request) { super("application/http"); this.request = request; } public void writeTo(OutputStream out) throws IOException { Writer writer = new OutputStreamWriter(out, getCharset()); // write method and URL writer.write(request.getRequestMethod()); writer.write(" "); writer.write(request.getUrl().build()); writer.write(NEWLINE); // write headers HttpHeaders headers = new HttpHeaders(); headers.fromHttpHeaders(request.getHeaders()); headers.setAcceptEncoding(null).setUserAgent(null) .setContentEncoding(null).setContentType(null).setContentLength(null); // analyze the content HttpContent content = request.getContent(); if (content != null) { headers.setContentType(content.getType()); // NOTE: batch does not support gzip encoding long contentLength = content.getLength(); if (contentLength != -1) { headers.setContentLength(contentLength); } } HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer); // write content if (content != null) { writer.write(NEWLINE); writer.flush(); content.writeTo(out); } } }
Java
/* * Copyright (c) 2012 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.googleapis.batch; import com.google.api.client.http.BackOffPolicy; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpHeaders; 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.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.http.MultipartContent; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * An instance of this class represents a single batch of requests. * * <p> * Sample use: * </p> * * <pre> BatchRequest batch = new BatchRequest(transport, httpRequestInitializer); batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); batch.execute(); * </pre> * * <p> * The content of each individual response is stored in memory. There is thus a potential of * encountering an {@link OutOfMemoryError} for very large responses. * </p> * * <p> * Redirects are currently not followed in {@link BatchRequest}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * <p> * Note: When setting an {@link HttpUnsuccessfulResponseHandler} by calling to * {@link HttpRequest#setUnsuccessfulResponseHandler}, the handler is called for each unsuccessful * part. As a result it's not recommended to use {@link HttpBackOffUnsuccessfulResponseHandler} on a * batch request, since the back-off policy is invoked for each unsuccessful part. * </p> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") public final class BatchRequest { /** The URL where batch requests are sent. */ private GenericUrl batchUrl = new GenericUrl("https://www.googleapis.com/batch"); /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The list of queued request infos. */ List<RequestInfo<?, ?>> requestInfos = new ArrayList<RequestInfo<?, ?>>(); /** Sleeper. */ private Sleeper sleeper = Sleeper.DEFAULT; /** A container class used to hold callbacks and data classes. */ static class RequestInfo<T, E> { final BatchCallback<T, E> callback; final Class<T> dataClass; final Class<E> errorClass; final HttpRequest request; RequestInfo(BatchCallback<T, E> callback, Class<T> dataClass, Class<E> errorClass, HttpRequest request) { this.callback = callback; this.dataClass = dataClass; this.errorClass = errorClass; this.request = request; } } /** * Construct the {@link BatchRequest}. * * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public BatchRequest(HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Sets the URL that will be hit when {@link #execute()} is called. The default value is * {@code https://www.googleapis.com/batch}. */ public BatchRequest setBatchUrl(GenericUrl batchUrl) { this.batchUrl = batchUrl; return this; } /** Returns the URL that will be hit when {@link #execute()} is called. */ public GenericUrl getBatchUrl() { return batchUrl; } /** * Returns the sleeper. * * @since 1.15 */ public Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public BatchRequest setSleeper(Sleeper sleeper) { this.sleeper = Preconditions.checkNotNull(sleeper); return this; } /** * Queues the specified {@link HttpRequest} for batched execution. Batched requests are executed * when {@link #execute()} is called. * * @param <T> destination class type * @param <E> error class type * @param httpRequest HTTP Request * @param dataClass Data class the response will be parsed into or {@code Void.class} to ignore * the content * @param errorClass Data class the unsuccessful response will be parsed into or * {@code Void.class} to ignore the content * @param callback Batch Callback * @return this Batch request * @throws IOException If building the HTTP Request fails */ public <T, E> BatchRequest queue(HttpRequest httpRequest, Class<T> dataClass, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkNotNull(httpRequest); // TODO(rmistry): Add BatchUnparsedCallback with onResponse(InputStream content, HttpHeaders). Preconditions.checkNotNull(callback); Preconditions.checkNotNull(dataClass); Preconditions.checkNotNull(errorClass); requestInfos.add(new RequestInfo<T, E>(callback, dataClass, errorClass, httpRequest)); return this; } /** * Returns the number of queued requests in this batch request. */ public int size() { return requestInfos.size(); } /** * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks. * * <p> * Calling {@link #execute()} executes and clears the queued requests. This means that the * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests * again. * </p> */ public void execute() throws IOException { boolean retryAllowed; Preconditions.checkState(!requestInfos.isEmpty()); HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null); // NOTE: batch does not support gzip encoding HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor(); batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor)); int retriesRemaining = batchRequest.getNumberOfRetries(); BackOffPolicy backOffPolicy = batchRequest.getBackOffPolicy(); if (backOffPolicy != null) { // Reset the BackOffPolicy at the start of each execute. backOffPolicy.reset(); } do { retryAllowed = retriesRemaining > 0; MultipartContent batchContent = new MultipartContent(); batchContent.getMediaType().setSubType("mixed"); int contentId = 1; for (RequestInfo<?, ?> requestInfo : requestInfos) { batchContent.addPart(new MultipartContent.Part( new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request))); } batchRequest.setContent(batchContent); HttpResponse response = batchRequest.execute(); BatchUnparsedResponse batchResponse; try { // Find the boundary from the Content-Type header. String boundary = "--" + response.getMediaType().getParameter("boundary"); // Parse the content stream. InputStream contentStream = response.getContent(); batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed); while (batchResponse.hasNext) { batchResponse.parseNextResponse(); } } finally { response.disconnect(); } List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos; if (!unsuccessfulRequestInfos.isEmpty()) { requestInfos = unsuccessfulRequestInfos; // backOff if required. if (batchResponse.backOffRequired && backOffPolicy != null) { long backOffTime = backOffPolicy.getNextBackOffMillis(); if (backOffTime != BackOffPolicy.STOP) { try { sleeper.sleep(backOffTime); } catch (InterruptedException exception) { // ignore } } } } else { break; } retriesRemaining--; } while (retryAllowed); requestInfos.clear(); } /** * Batch HTTP request execute interceptor that loops through all individual HTTP requests and runs * their interceptors. */ class BatchInterceptor implements HttpExecuteInterceptor { private HttpExecuteInterceptor originalInterceptor; BatchInterceptor(HttpExecuteInterceptor originalInterceptor) { this.originalInterceptor = originalInterceptor; } public void intercept(HttpRequest batchRequest) throws IOException { if (originalInterceptor != null) { originalInterceptor.intercept(batchRequest); } for (RequestInfo<?, ?> requestInfo : requestInfos) { HttpExecuteInterceptor interceptor = requestInfo.request.getInterceptor(); if (interceptor != null) { interceptor.intercept(requestInfo.request); } } } } }
Java
/* * Copyright (c) 2012 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. */ /** * JSON batch for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.batch.json;
Java
/* * Copyright (c) 2012 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.googleapis.batch.json; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; import com.google.api.client.http.HttpHeaders; import java.io.IOException; /** * Callback for an individual batch JSON response. * * <p> * Sample use: * </p> * * <pre> batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class, new JsonBatchCallback&lt;Volumes&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * @param <T> Type of the data model class * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public abstract class JsonBatchCallback<T> implements BatchCallback<T, GoogleJsonErrorContainer> { public final void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) throws IOException { onFailure(e.getError(), responseHeaders); } /** * Called if the individual batch response is unsuccessful. * * @param e Google JSON error response content * @param responseHeaders Headers of the batch response */ public abstract void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException; }
Java
/* * Copyright (c) 2012 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. */ /** * Batch for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.batch;
Java
/* * Copyright (c) 2012 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.googleapis.batch; import com.google.api.client.googleapis.batch.BatchRequest.RequestInfo; import com.google.api.client.http.BackOffPolicy; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.util.StringUtils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * The unparsed batch response. * * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") final class BatchUnparsedResponse { /** The boundary used in the batch response to separate individual responses. */ private final String boundary; /** List of request infos. */ private final List<RequestInfo<?, ?>> requestInfos; /** Buffers characters from the input stream. */ private final BufferedReader bufferedReader; /** Determines whether there are any responses to be parsed. */ boolean hasNext = true; /** List of unsuccessful HTTP requests that can be retried. */ List<RequestInfo<?, ?>> unsuccessfulRequestInfos = new ArrayList<RequestInfo<?, ?>>(); /** Indicates if back off is required before the next retry. */ boolean backOffRequired; /** The content Id the response is currently at. */ private int contentId = 0; /** Whether unsuccessful HTTP requests can be retried. */ private final boolean retryAllowed; /** * Construct the {@link BatchUnparsedResponse}. * * @param inputStream Input stream that contains the batch response * @param boundary The boundary of the batch response * @param requestInfos List of request infos * @param retryAllowed Whether unsuccessful HTTP requests can be retried */ BatchUnparsedResponse(InputStream inputStream, String boundary, List<RequestInfo<?, ?>> requestInfos, boolean retryAllowed) throws IOException { this.boundary = boundary; this.requestInfos = requestInfos; this.retryAllowed = retryAllowed; this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); // First line in the stream will be the boundary. checkForFinalBoundary(bufferedReader.readLine()); } /** * Parses the next response in the queue if a data class and a {@link BatchCallback} is specified. * * <p> * This method closes the input stream if there are no more individual responses left. * </p> */ void parseNextResponse() throws IOException { contentId++; // Extract the outer headers. String line; while ((line = bufferedReader.readLine()) != null && !line.equals("")) { // Do nothing. } // Extract the status code. String statusLine = bufferedReader.readLine(); String[] statusParts = statusLine.split(" "); int statusCode = Integer.parseInt(statusParts[1]); // Extract and store the inner headers. // TODO(rmistry): Handle inner headers that span multiple lines. More details here: // http://tools.ietf.org/html/rfc2616#section-2.2 List<String> headerNames = new ArrayList<String>(); List<String> headerValues = new ArrayList<String>(); while ((line = bufferedReader.readLine()) != null && !line.equals("")) { String[] headerParts = line.split(": ", 2); headerNames.add(headerParts[0]); headerValues.add(headerParts[1]); } // Extract the response part content. // TODO(rmistry): Investigate a way to use the stream directly. This is to reduce the chance of // an OutOfMemoryError and will make parsing more efficient. StringBuilder partContent = new StringBuilder(); while ((line = bufferedReader.readLine()) != null && !line.startsWith(boundary)) { partContent.append(line); } HttpResponse response = getFakeResponse(statusCode, partContent.toString(), headerNames, headerValues); parseAndCallback(requestInfos.get(contentId - 1), statusCode, contentId, response); checkForFinalBoundary(line); } /** * Parse an object into a new instance of the data class using * {@link HttpResponse#parseAs(java.lang.reflect.Type)}. */ private <T, E> void parseAndCallback( RequestInfo<T, E> requestInfo, int statusCode, int contentID, HttpResponse response) throws IOException { BatchCallback<T, E> callback = requestInfo.callback; HttpHeaders responseHeaders = response.getHeaders(); HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler = requestInfo.request.getUnsuccessfulResponseHandler(); BackOffPolicy backOffPolicy = requestInfo.request.getBackOffPolicy(); // Reset backOff flag. backOffRequired = false; if (HttpStatusCodes.isSuccess(statusCode)) { if (callback == null) { // No point in parsing if there is no callback. return; } T parsed = getParsedDataClass( requestInfo.dataClass, response, requestInfo, responseHeaders.getContentType()); callback.onSuccess(parsed, responseHeaders); } else { HttpContent content = requestInfo.request.getContent(); boolean retrySupported = retryAllowed && (content == null || content.retrySupported()); boolean errorHandled = false; boolean redirectRequest = false; if (unsuccessfulResponseHandler != null) { errorHandled = unsuccessfulResponseHandler.handleResponse( requestInfo.request, response, retrySupported); } if (!errorHandled) { if (requestInfo.request.handleRedirect(response.getStatusCode(), response.getHeaders())) { redirectRequest = true; } else if (retrySupported && backOffPolicy != null && backOffPolicy.isBackOffRequired(response.getStatusCode())) { backOffRequired = true; } } if (retrySupported && (errorHandled || backOffRequired || redirectRequest)) { unsuccessfulRequestInfos.add(requestInfo); } else { if (callback == null) { // No point in parsing if there is no callback. return; } E parsed = getParsedDataClass( requestInfo.errorClass, response, requestInfo, responseHeaders.getContentType()); callback.onFailure(parsed, responseHeaders); } } } private <A, T, E> A getParsedDataClass( Class<A> dataClass, HttpResponse response, RequestInfo<T, E> requestInfo, String contentType) throws IOException { // TODO(yanivi): Remove the HttpResponse reference and directly parse the InputStream if (dataClass == Void.class) { return null; } return requestInfo.request.getParser().parseAndClose( response.getContent(), response.getContentCharset(), dataClass); } /** Create a fake HTTP response object populated with the partContent and the statusCode. */ private HttpResponse getFakeResponse(final int statusCode, final String partContent, List<String> headerNames, List<String> headerValues) throws IOException { HttpRequest request = new FakeResponseHttpTransport( statusCode, partContent, headerNames, headerValues).createRequestFactory() .buildPostRequest(new GenericUrl("http://google.com/"), null); request.setLoggingEnabled(false); request.setThrowExceptionOnExecuteError(false); return request.execute(); } /** * If the boundary line consists of the boundary and "--" then there are no more individual * responses left to be parsed and the input stream is closed. */ private void checkForFinalBoundary(String boundaryLine) throws IOException { if (boundaryLine.equals(boundary + "--")) { hasNext = false; bufferedReader.close(); } } private static class FakeResponseHttpTransport extends HttpTransport { private int statusCode; private String partContent; private List<String> headerNames; private List<String> headerValues; FakeResponseHttpTransport( int statusCode, String partContent, List<String> headerNames, List<String> headerValues) { super(); this.statusCode = statusCode; this.partContent = partContent; this.headerNames = headerNames; this.headerValues = headerValues; } @Override protected LowLevelHttpRequest buildRequest(String method, String url) { return new FakeLowLevelHttpRequest(partContent, statusCode, headerNames, headerValues); } } private static class FakeLowLevelHttpRequest extends LowLevelHttpRequest { // TODO(rmistry): Read in partContent as bytes instead of String for efficiency. private String partContent; private int statusCode; private List<String> headerNames; private List<String> headerValues; FakeLowLevelHttpRequest( String partContent, int statusCode, List<String> headerNames, List<String> headerValues) { this.partContent = partContent; this.statusCode = statusCode; this.headerNames = headerNames; this.headerValues = headerValues; } @Override public void addHeader(String name, String value) { } @Override public LowLevelHttpResponse execute() { FakeLowLevelHttpResponse response = new FakeLowLevelHttpResponse(new ByteArrayInputStream( StringUtils.getBytesUtf8(partContent)), statusCode, headerNames, headerValues); return response; } } private static class FakeLowLevelHttpResponse extends LowLevelHttpResponse { private InputStream partContent; private int statusCode; private List<String> headerNames = new ArrayList<String>(); private List<String> headerValues = new ArrayList<String>(); FakeLowLevelHttpResponse(InputStream partContent, int statusCode, List<String> headerNames, List<String> headerValues) { this.partContent = partContent; this.statusCode = statusCode; this.headerNames = headerNames; this.headerValues = headerValues; } @Override public InputStream getContent() { return partContent; } @Override public int getStatusCode() { return statusCode; } @Override public String getContentEncoding() { return null; } @Override public long getContentLength() { return 0; } @Override public String getContentType() { return null; } @Override public String getStatusLine() { return null; } @Override public String getReasonPhrase() { return null; } @Override public int getHeaderCount() { return headerNames.size(); } @Override public String getHeaderName(int index) { return headerNames.get(index); } @Override public String getHeaderValue(int index) { return headerValues.get(index); } } }
Java
/* * Copyright (c) 2012 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.googleapis.batch; import com.google.api.client.http.HttpHeaders; import java.io.IOException; /** * Callback for an individual batch response. * * <p> * Sample use: * </p> * * <pre> batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); * </pre> * * @param <T> Type of the data model class * @param <E> Type of the error data model class * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface BatchCallback<T, E> { /** * Called if the individual batch response is successful. * * @param t instance of the parsed data model class * @param responseHeaders Headers of the batch response */ void onSuccess(T t, HttpHeaders responseHeaders) throws IOException; /** * Called if the individual batch response is unsuccessful. * * @param e instance of data class representing the error response content * @param responseHeaders Headers of the batch response */ void onFailure(E e, HttpHeaders responseHeaders) throws IOException; }
Java
/* * 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.googleapis.testing.services; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; /** * {@link Beta} <br/> * Thread-safe mock Google client. * * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleClient extends AbstractGoogleClient { /** * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none * * @since 1.14 */ public MockGoogleClient(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, rootUrl, servicePath, objectParser, httpRequestInitializer)); } /** * @param builder builder * * @since 1.14 */ protected MockGoogleClient(Builder builder) { super(builder); } /** * Builder for {@link MockGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleClient.Builder { /** * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public Builder(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, objectParser, httpRequestInitializer); } @Override public MockGoogleClient build() { return new MockGoogleClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.json} package. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services.json;
Java
/* * 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.googleapis.testing.services.json; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google JSON request. * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleJsonClientRequest<T> extends AbstractGoogleJsonClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param content A POJO that can be serialized into JSON or {@code null} for none */ public MockGoogleJsonClientRequest(AbstractGoogleJsonClient client, String method, String uriTemplate, Object content, Class<T> responseClass) { super(client, method, uriTemplate, content, responseClass); } @Override public MockGoogleJsonClient getAbstractGoogleClient() { return (MockGoogleJsonClient) super.getAbstractGoogleClient(); } @Override public MockGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleJsonClientRequest<T>) super.setRequestHeaders(headers); } }
Java
/* * 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.googleapis.testing.services.json; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google JSON client. * * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleJsonClient extends AbstractGoogleJsonClient { /** * @param builder builder * * @since 1.14 */ protected MockGoogleJsonClient(Builder builder) { super(builder); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ public MockGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { this(new Builder( transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer, legacyDataWrapper)); } /** * {@link Beta} <br/> * Builder for {@link MockGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleJsonClient.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ public Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { super( transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer, legacyDataWrapper); } @Override public MockGoogleJsonClient build() { return new MockGoogleJsonClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis} package. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services;
Java
/* * 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.googleapis.testing.services; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google request. * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ @Beta public class MockGoogleClientRequest<T> extends AbstractGoogleClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param content HTTP content or {@code null} for none * @param responseClass response class to parse into */ public MockGoogleClientRequest(AbstractGoogleClient client, String method, String uriTemplate, HttpContent content, Class<T> responseClass) { super(client, method, uriTemplate, content, responseClass); } @Override public MockGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleClientRequest<T>) super.setRequestHeaders(headers); } @Override public MockGoogleClientRequest<T> set(String fieldName, Object value) { return (MockGoogleClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2013 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.googleapis.testing.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.googleapis.notifications.UnparsedNotification; import com.google.api.client.googleapis.notifications.UnparsedNotificationCallback; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Mock for the {@link UnparsedNotificationCallback} class. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @SuppressWarnings("rawtypes") @Beta public class MockUnparsedNotificationCallback implements UnparsedNotificationCallback { private static final long serialVersionUID = 0L; /** Whether this handler was called. */ private boolean wasCalled; /** Returns whether this handler was called. */ public boolean wasCalled() { return wasCalled; } public MockUnparsedNotificationCallback() { } @SuppressWarnings("unused") public void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException { wasCalled = true; } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the Subscriptions extension package. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.notifications;
Java
/* * Copyright (c) 2012 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the Subscriptions extension package. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.subscriptions;
Java
/* * Copyright (c) 2012 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.googleapis.testing.subscriptions; import com.google.api.client.googleapis.subscriptions.NotificationCallback; import com.google.api.client.googleapis.subscriptions.StoredSubscription; import com.google.api.client.googleapis.subscriptions.UnparsedNotification; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Mock for the {@link NotificationCallback} class. * * @author Matthias Linder (mlinder) * @since 1.14 */ @SuppressWarnings("rawtypes") @Beta public class MockNotificationCallback implements NotificationCallback { private static final long serialVersionUID = 0L; /** True if this handler was called. */ private boolean wasCalled = false; /** Returns {@code true} if this handler was called. */ public boolean wasCalled() { return wasCalled; } public MockNotificationCallback() { } public void handleNotification( StoredSubscription subscription, UnparsedNotification notification) { wasCalled = true; } }
Java
/* * Copyright (c) 2012 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.googleapis.extensions.android.accounts; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; /** * {@link Beta} <br/> * Account manager wrapper for Google accounts. * * @since 1.11 * @author Yaniv Inbar */ @Beta public final class GoogleAccountManager { /** Google account type. */ public static final String ACCOUNT_TYPE = "com.google"; /** Account manager. */ private final AccountManager manager; /** * @param accountManager account manager */ public GoogleAccountManager(AccountManager accountManager) { this.manager = Preconditions.checkNotNull(accountManager); } /** * @param context context from which to retrieve the account manager */ public GoogleAccountManager(Context context) { this(AccountManager.get(context)); } /** * Returns the account manager. * * @since 1.8 */ public AccountManager getAccountManager() { return manager; } /** * Returns all Google accounts. * * @return array of Google accounts */ public Account[] getAccounts() { return manager.getAccountsByType("com.google"); } /** * Returns the Google account of the given {@link Account#name}. * * @param accountName Google account name or {@code null} for {@code null} result * @return Google account or {@code null} for none found or for {@code null} input */ public Account getAccountByName(String accountName) { if (accountName != null) { for (Account account : getAccounts()) { if (accountName.equals(account.name)) { return account; } } } return null; } /** * Invalidates the given Google auth token by removing it from the account manager's cache (if * necessary) for example if the auth token has expired or otherwise become invalid. * * @param authToken auth token */ public void invalidateAuthToken(String authToken) { manager.invalidateAuthToken(ACCOUNT_TYPE, authToken); } }
Java
/* * Copyright (c) 2012 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities for Account Manager for Google accounts on Android Eclair (SDK 2.1) and later. * * @since 1.11 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.android.accounts;
Java
/* * 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.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GoogleAuthException; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link GoogleAuthException} into an {@link IOException} so it can be caught directly. * * <p> * Use {@link #getCause()} to get the wrapped {@link GoogleAuthException}. * </p> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GoogleAuthIOException extends IOException { private static final long serialVersionUID = 1L; /** * @param wrapped wrapped {@link GoogleAuthException} */ GoogleAuthIOException(GoogleAuthException wrapped) { initCause(Preconditions.checkNotNull(wrapped)); } @Override public GoogleAuthException getCause() { return (GoogleAuthException) super.getCause(); } }
Java
/* * 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities based on <a href="https://developers.google.com/android/google-play-services/">Google * Play services</a>. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.android.gms.auth;
Java
/* * 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.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.api.client.util.Beta; import android.app.Activity; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link GooglePlayServicesAvailabilityException} into an {@link IOException} so it can be * caught directly. * * <p> * Use {@link #getConnectionStatusCode()} to display the error dialog. Alternatively, use * {@link #getCause()} to get the wrapped {@link GooglePlayServicesAvailabilityException}. Example * usage: * </p> * * <pre> } catch (final GooglePlayServicesAvailabilityIOException availabilityException) { myActivity.runOnUiThread(new Runnable() { public void run() { Dialog dialog = GooglePlayServicesUtil.getErrorDialog( availabilityException.getConnectionStatusCode(), myActivity, MyActivity.REQUEST_GOOGLE_PLAY_SERVICES); dialog.show(); } }); * </pre> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GooglePlayServicesAvailabilityIOException extends UserRecoverableAuthIOException { private static final long serialVersionUID = 1L; GooglePlayServicesAvailabilityIOException(GooglePlayServicesAvailabilityException wrapped) { super(wrapped); } @Override public GooglePlayServicesAvailabilityException getCause() { return (GooglePlayServicesAvailabilityException) super.getCause(); } /** * Returns the error code to use with * {@link GooglePlayServicesUtil#getErrorDialog(int, Activity, int)}. */ public final int getConnectionStatusCode() { return getCause().getConnectionStatusCode(); } }
Java
/* * 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.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.util.Beta; import android.app.Activity; import android.content.Intent; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link UserRecoverableAuthException} into an {@link IOException} so it can be caught * directly. * * <p> * Use {@link #getIntent()} to allow user interaction to recover. Alternatively, use * {@link #getCause()} to get the wrapped {@link UserRecoverableAuthException}. Example usage: * </p> * * <pre> } catch (UserRecoverableAuthIOException userRecoverableException) { myActivity.startActivityForResult( userRecoverableException.getIntent(), MyActivity.REQUEST_AUTHORIZATION); } * </pre> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class UserRecoverableAuthIOException extends GoogleAuthIOException { private static final long serialVersionUID = 1L; UserRecoverableAuthIOException(UserRecoverableAuthException wrapped) { super(wrapped); } @Override public UserRecoverableAuthException getCause() { return (UserRecoverableAuthException) super.getCause(); } /** * Returns the {@link Intent} that when supplied to * {@link Activity#startActivityForResult(Intent, int)} will allow user intervention. */ public final Intent getIntent() { return getCause().getIntent(); } }
Java
/* * 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.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.extensions.android.accounts.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.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Beta; import com.google.api.client.util.ExponentialBackOff; import com.google.api.client.util.Joiner; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import android.accounts.Account; import android.content.Context; import android.content.Intent; import java.io.IOException; import java.util.Collection; /** * {@link Beta} <br/> * Manages authorization and account selection for Google accounts. * * <p> * When fetching a token, any thrown {@link GoogleAuthException} would be wrapped: * <ul> * <li>{@link GooglePlayServicesAvailabilityException} would be wrapped inside of * {@link GooglePlayServicesAvailabilityIOException}</li> * <li>{@link UserRecoverableAuthException} would be wrapped inside of * {@link UserRecoverableAuthIOException}</li> * <li>{@link GoogleAuthException} when be wrapped inside of {@link GoogleAuthIOException}</li> * </ul> * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default when I/O * exception was thrown inside {@link #getToken}, but starting with version 1.15 you need to call * {@link #setBackOff} with {@link ExponentialBackOff} to enable it. * </p> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GoogleAccountCredential implements HttpRequestInitializer { /** Context. */ final Context context; /** Scope to use on {@link GoogleAuthUtil#getToken}. */ final String scope; /** Google account manager. */ private final GoogleAccountManager accountManager; /** * Selected Google account name (e-mail address), for example {@code "johndoe@gmail.com"}, or * {@code null} for none. */ private String accountName; /** Selected Google account or {@code null} for none. */ private Account selectedAccount; /** Sleeper. */ private Sleeper sleeper = Sleeper.DEFAULT; /** * Back-off policy which is used when an I/O exception is thrown inside {@link #getToken} or * {@code null} for none. */ private BackOff backOff; /** * @param context context * @param scope scope to use on {@link GoogleAuthUtil#getToken} */ public GoogleAccountCredential(Context context, String scope) { accountManager = new GoogleAccountManager(context); this.context = context; this.scope = scope; } /** * {@link Beta} <br/> * Constructs a new instance using OAuth 2.0 scopes. * * @param context context * @param scope first OAuth 2.0 scope * @param extraScopes any additional OAuth 2.0 scopes * @return new instance * @deprecated (scheduled to be removed in 1.16) Use {@link #usingOAuth2(Context, Collection)} * instead. */ @Beta @Deprecated public static GoogleAccountCredential usingOAuth2( Context context, String scope, String... extraScopes) { StringBuilder scopeBuilder = new StringBuilder("oauth2:").append(scope); for (String extraScope : extraScopes) { scopeBuilder.append(' ').append(extraScope); } return new GoogleAccountCredential(context, scopeBuilder.toString()); } /** * Constructs a new instance using OAuth 2.0 scopes. * * @param context context * @param scopes non empty OAuth 2.0 scope list * @return new instance * * @since 1.15 */ public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); } /** * Sets the audience scope to use with Google Cloud Endpoints. * * @param context context * @param audience audience * @return new instance */ public static GoogleAccountCredential usingAudience(Context context, String audience) { Preconditions.checkArgument(audience.length() != 0); return new GoogleAccountCredential(context, "audience:" + audience); } /** * Sets the selected Google account name (e-mail address) -- for example * {@code "johndoe@gmail.com"} -- or {@code null} for none. */ public final GoogleAccountCredential setSelectedAccountName(String accountName) { selectedAccount = accountManager.getAccountByName(accountName); // check if account has been deleted this.accountName = selectedAccount == null ? null : accountName; return this; } public void initialize(HttpRequest request) { RequestHandler handler = new RequestHandler(); request.setInterceptor(handler); request.setUnsuccessfulResponseHandler(handler); } /** Returns the context. */ public final Context getContext() { return context; } /** Returns the scope to use on {@link GoogleAuthUtil#getToken}. */ public final String getScope() { return scope; } /** Returns the Google account manager. */ public final GoogleAccountManager getGoogleAccountManager() { return accountManager; } /** Returns all Google accounts or {@code null} for none. */ public final Account[] getAllAccounts() { return accountManager.getAccounts(); } /** Returns the selected Google account or {@code null} for none. */ public final Account getSelectedAccount() { return selectedAccount; } /** * Returns the back-off policy which is used when an I/O exception is thrown inside * {@link #getToken} or {@code null} for none. * * @since 1.15 */ public BackOff getBackOff() { return backOff; } /** * Sets the back-off policy which is used when an I/O exception is thrown inside {@link #getToken} * or {@code null} for none. * * @since 1.15 */ public GoogleAccountCredential setBackOff(BackOff backOff) { this.backOff = backOff; return this; } /** * Returns the sleeper. * * @since 1.15 */ public final Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public final GoogleAccountCredential setSleeper(Sleeper sleeper) { this.sleeper = Preconditions.checkNotNull(sleeper); return this; } /** * Returns the selected Google account name (e-mail address), for example * {@code "johndoe@gmail.com"}, or {@code null} for none. */ public final String getSelectedAccountName() { return accountName; } /** * Returns an intent to show the user to select a Google account, or create a new one if there are * none on the device yet. * * <p> * Must be run from the main UI thread. * </p> */ public final Intent newChooseAccountIntent() { return AccountPicker.newChooseAccountIntent(selectedAccount, null, new String[] {GoogleAccountManager.ACCOUNT_TYPE}, true, null, null, null, null); } /** * Returns an OAuth 2.0 access token. * * <p> * Must be run from a background thread, not the main UI thread. * </p> */ public String getToken() throws IOException, GoogleAuthException { if (backOff != null) { backOff.reset(); } while (true) { try { return GoogleAuthUtil.getToken(context, accountName, scope); } catch (IOException e) { // network or server error, so retry using back-off policy try { if (backOff == null || !BackOffUtils.next(sleeper, backOff)) { throw e; } } catch (InterruptedException e2) { // ignore } } } } @Beta class RequestHandler implements HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { /** Whether we've received a 401 error code indicating the token is invalid. */ boolean received401; String token; public void intercept(HttpRequest request) throws IOException { try { token = getToken(); request.getHeaders().setAuthorization("Bearer " + token); } catch (GooglePlayServicesAvailabilityException e) { throw new GooglePlayServicesAvailabilityIOException(e); } catch (UserRecoverableAuthException e) { throw new UserRecoverableAuthIOException(e); } catch (GoogleAuthException e) { throw new GoogleAuthIOException(e); } } public boolean handleResponse( HttpRequest request, HttpResponse response, boolean supportsRetry) { if (response.getStatusCode() == 401 && !received401) { received401 = true; GoogleAuthUtil.invalidateToken(context, token); return true; } return false; } } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.appengine.notifications;
Java
/* * Copyright (c) 2013 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.googleapis.extensions.appengine.notifications; import com.google.api.client.extensions.appengine.datastore.AppEngineDataStoreFactory; import com.google.api.client.googleapis.extensions.servlet.notifications.WebhookUtils; import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Thread-safe Webhook App Engine Servlet to receive notifications. * * <p> * In order to use this servlet you need to register the servlet in your web.xml. You may optionally * extend {@link AppEngineNotificationServlet} with custom behavior. * </p> * * <p> * It is a simple wrapper around {@link WebhookUtils#processWebhookNotification(HttpServletRequest, * HttpServletResponse, DataStoreFactory)} that uses * {@link AppEngineDataStoreFactory#getDefaultInstance()}, so you may alternatively call that method * instead from your {@link HttpServlet#doPost} with no loss of functionality. * </p> * * <b>Sample web.xml setup:</b> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}AppEngineNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.google.api.client.googleapis.extensions.appengine.notifications.AppEngineNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}AppEngineNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * @author Yaniv Inbar * @since 1.16 */ @Beta public class AppEngineNotificationServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebhookUtils.processWebhookNotification( req, resp, AppEngineDataStoreFactory.getDefaultInstance()); } }
Java
/* * Copyright (c) 2012 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for creating subscriptions and receiving notifications on AppEngine. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.appengine.subscriptions;
Java
/* * Copyright (c) 2012 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.googleapis.extensions.appengine.subscriptions; import com.google.api.client.googleapis.subscriptions.StoredSubscription; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.util.Beta; import com.google.appengine.api.memcache.Expiration; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import java.io.IOException; /** * {@link Beta} <br/> * Implementation of a persistent {@link SubscriptionStore} making use of native DataStore and * the Memcache API on AppEngine. * * <p> * Implementation is thread-safe. * </p> * * <p> * On AppEngine you should prefer this SubscriptionStore over others due to performance and quota * reasons. * </p> * * <b>Example usage:</b> * <pre> service.setSubscriptionStore(new CachedAppEngineSubscriptionStore()); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class CachedAppEngineSubscriptionStore extends AppEngineSubscriptionStore { /** Cache expiration time in seconds. */ private static final int EXPIRATION_TIME = 3600; /** The service instance used to access the Memcache API. */ private MemcacheService memCache = MemcacheServiceFactory.getMemcacheService( CachedAppEngineSubscriptionStore.class.getCanonicalName()); @Override public void removeSubscription(StoredSubscription subscription) throws IOException { super.removeSubscription(subscription); memCache.delete(subscription.getId()); } @Override public void storeSubscription(StoredSubscription subscription) throws IOException { super.storeSubscription(subscription); memCache.put(subscription.getId(), subscription); } @Override public StoredSubscription getSubscription(String subscriptionId) throws IOException { if (memCache.contains(subscriptionId)) { return (StoredSubscription) memCache.get(subscriptionId); } StoredSubscription subscription = super.getSubscription(subscriptionId); memCache.put(subscriptionId, subscription, Expiration.byDeltaSeconds(EXPIRATION_TIME)); return subscription; } }
Java
/* * Copyright (c) 2012 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.googleapis.extensions.appengine.subscriptions; import com.google.api.client.googleapis.subscriptions.StoredSubscription; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.util.Beta; import com.google.api.client.util.Lists; import com.google.appengine.api.datastore.Blob; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; /** * {@link Beta} <br/> * Persistent {@link SubscriptionStore} making use of native DataStore on AppEngine. * * <p> * Implementation is thread-safe. * </p> * * <b>Example usage:</b> * * <pre> service.setSubscriptionStore(new AppEngineSubscriptionStore()); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public class AppEngineSubscriptionStore implements SubscriptionStore { /** Name of the table in the AppEngine datastore. */ private static final String KIND = AppEngineSubscriptionStore.class.getName(); /** Name of the field in which the subscription is stored. */ private static final String FIELD_SUBSCRIPTION = "serializedSubscription"; /** * Creates a new {@link AppEngineSubscriptionStore}. */ public AppEngineSubscriptionStore() { } /** Serializes the specified object into a Blob using an {@link ObjectOutputStream}. */ private Blob serialize(Object obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { new ObjectOutputStream(baos).writeObject(obj); return new Blob(baos.toByteArray()); } finally { baos.close(); } } /** Deserializes the specified object from a Blob using an {@link ObjectInputStream}. */ @SuppressWarnings("unchecked") private <T> T deserialize(Blob data, Class<T> dataType) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes()); try { Object obj = new ObjectInputStream(bais).readObject(); if (!dataType.isAssignableFrom(obj.getClass())) { return null; } return (T) obj; } catch (ClassNotFoundException exception) { throw new IOException("Failed to deserialize object", exception); } finally { bais.close(); } } /** Parses the specified Entity and returns the contained Subscription object. */ private StoredSubscription getSubscriptionFromEntity(Entity entity) throws IOException { Blob serializedSubscription = (Blob) entity.getProperty(FIELD_SUBSCRIPTION); return deserialize(serializedSubscription, StoredSubscription.class); } @Override public void storeSubscription(StoredSubscription subscription) throws IOException { DatastoreService service = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(KIND, subscription.getId()); entity.setProperty(FIELD_SUBSCRIPTION, serialize(subscription)); service.put(entity); } @Override public void removeSubscription(StoredSubscription subscription) throws IOException { if (subscription == null) { return; } DatastoreService service = DatastoreServiceFactory.getDatastoreService(); service.delete(KeyFactory.createKey(KIND, subscription.getId())); } @Override public List<StoredSubscription> listSubscriptions() throws IOException { List<StoredSubscription> list = Lists.newArrayList(); DatastoreService service = DatastoreServiceFactory.getDatastoreService(); PreparedQuery results = service.prepare(new Query(KIND)); for (Entity entity : results.asIterable()) { list.add(getSubscriptionFromEntity(entity)); } return list; } @Override public StoredSubscription getSubscription(String subscriptionId) throws IOException { try { DatastoreService service = DatastoreServiceFactory.getDatastoreService(); Entity entity = service.get(KeyFactory.createKey(KIND, subscriptionId)); return getSubscriptionFromEntity(entity); } catch (EntityNotFoundException exception) { return null; } } }
Java
/* * Copyright (c) 2012 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. */ /** * Google App Engine utilities for OAuth 2.0 for Google APIs. * * @since 1.7 * @author Yaniv Inbar */ package com.google.api.client.googleapis.extensions.appengine.auth.oauth2;
Java
/* * Copyright (c) 2012 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.googleapis.extensions.appengine.auth.oauth2; import com.google.api.client.auth.oauth2.BearerToken; 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.util.Beta; import com.google.api.client.util.Lists; import com.google.appengine.api.appidentity.AppIdentityService; import com.google.appengine.api.appidentity.AppIdentityServiceFactory; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * OAuth 2.0 credential in which a client Google App Engine application needs to access data that it * owns, based on <a href="http://code.google.com/appengine/docs/java/appidentity/overview.html * #Asserting_Identity_to_Google_APIs">Asserting Identity to Google APIs</a>. * * <p> * Intercepts the request by using the access token obtained from * {@link AppIdentityService#getAccessToken(Iterable)}. * </p> * * <p> * Sample usage: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return transport.createRequestFactory( new AppIdentityCredential("https://www.googleapis.com/auth/urlshortener")); } * </pre> * * <p> * Implementation is immutable and thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AppIdentityCredential implements HttpRequestInitializer, HttpExecuteInterceptor { /** App Identity Service that provides the access token. */ private final AppIdentityService appIdentityService; /** OAuth scopes (unmodifiable). */ private final Collection<String> scopes; /** * @param scopes OAuth scopes * @since 1.15 */ public AppIdentityCredential(Collection<String> scopes) { this(new Builder(scopes)); } /** * {@link Beta} <br/> * Constructs a new {@link AppIdentityCredential}. * * @param scopes OAuth scopes * @deprecated (scheduled to be removed in 1.16) Use {@link #AppIdentityCredential(Collection)} * instead. */ @Beta @Deprecated public AppIdentityCredential(Iterable<String> scopes) { this(new Builder(scopes)); } /** * {@link Beta} <br/> * Constructs a new {@link AppIdentityCredential}. * * @param scopes OAuth scopes * @deprecated (scheduled to be removed in 1.16) Use {@link #AppIdentityCredential(Collection)} * instead. */ @Beta @Deprecated public AppIdentityCredential(String... scopes) { this(new Builder(scopes)); } /** * @param builder builder * * @since 1.14 */ protected AppIdentityCredential(Builder builder) { // Lazily retrieved rather than setting as the default value in order to not add runtime // dependencies on AppIdentityServiceFactory unless it is actually being used. appIdentityService = builder.appIdentityService == null ? AppIdentityServiceFactory.getAppIdentityService() : builder.appIdentityService; scopes = builder.scopes; } @Override public void initialize(HttpRequest request) throws IOException { request.setInterceptor(this); } @Override public void intercept(HttpRequest request) throws IOException { String accessToken = appIdentityService.getAccessToken(scopes).getAccessToken(); BearerToken.authorizationHeaderAccessMethod().intercept(request, accessToken); } /** * Gets the App Identity Service that provides the access token. * * @since 1.12 */ public final AppIdentityService getAppIdentityService() { return appIdentityService; } /** * Gets the OAuth scopes (unmodifiable). * * <p> * Upgrade warning: in prior version 1.14 this method returned a {@link List}, but starting with * version 1.15 it returns a {@link Collection}. * </p> * * @since 1.12 */ public final Collection<String> getScopes() { return scopes; } /** * Builder for {@link AppIdentityCredential}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.12 */ public static class Builder { /** * App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. */ AppIdentityService appIdentityService; /** OAuth scopes (unmodifiable). */ final Collection<String> scopes; /** * Returns an instance of a new builder. * * @param scopes OAuth scopes * @since 1.15 */ public Builder(Collection<String> scopes) { this.scopes = Collections.unmodifiableCollection(scopes); } /** * {@link Beta} <br/> * Returns an instance of a new builder. * * @param scopes OAuth scopes * @deprecated (scheduled to be removed in 1.16) Use * {@link #AppIdentityCredential.Builder(Collection)} instead. */ @Beta @Deprecated public Builder(Iterable<String> scopes) { this.scopes = Collections.unmodifiableList(Lists.newArrayList(scopes)); } /** * {@link Beta} <br/> * Returns an instance of a new builder. * * @param scopes OAuth scopes * @deprecated (scheduled to be removed in 1.16) Use * {@link #AppIdentityCredential.Builder(Collection)} instead. */ @Beta @Deprecated public Builder(String... scopes) { this(Arrays.asList(scopes)); } /** * Returns the App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. * * @since 1.14 */ public final AppIdentityService getAppIdentityService() { return appIdentityService; } /** * Sets the App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setAppIdentityService(AppIdentityService appIdentityService) { this.appIdentityService = appIdentityService; return this; } /** * Returns a new {@link AppIdentityCredential}. */ public AppIdentityCredential build() { return new AppIdentityCredential(this); } /** * Returns the OAuth scopes (unmodifiable). * * <p> * Upgrade warning: in prior version 1.14 this method returned a {@link List}, but starting with * version 1.15 it returns a {@link Collection}. * </p> * * @since 1.14 */ public final Collection<String> getScopes() { return scopes; } } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Notification channel handling based on the <a * href="http://code.google.com/p/google-gson/">GSON</a> JSON library. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json.gson;
Java
/* * Copyright (c) 2013 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.googleapis.notifications.json.gson; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.googleapis.notifications.json.JsonNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding with * {@link GsonFactory#getDefaultInstance()}. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends GsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class GsonNotificationCallback<T> extends JsonNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected JsonFactory getJsonFactory() { return GsonFactory.getDefaultInstance(); } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Notification channel handling based on the <a * href="http://wiki.fasterxml.com/JacksonRelease20">Jackson 2</a> JSON library. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json.jackson2;
Java
/* * Copyright (c) 2013 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.googleapis.notifications.json.jackson2; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.googleapis.notifications.json.JsonNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding with * {@link JacksonFactory#getDefaultInstance()}. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends GsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class JacksonNotificationCallback<T> extends JsonNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected JsonFactory getJsonFactory() { return JacksonFactory.getDefaultInstance(); } }
Java
/* * Copyright (c) 2013 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.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer client request initializer implementation for setting properties like key * and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyKeyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeProtoRequest( AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.16 * @author Yaniv Inbar */ @Beta public class CommonGoogleProtoClientRequestInitializer extends CommonGoogleClientRequestInitializer { public CommonGoogleProtoClientRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException { super.initialize(request); initializeProtoRequest((AbstractGoogleProtoClientRequest<?>) request); } /** * Initializes a Google protocol buffer client request. * * <p> * Default implementation does nothing. Called from * {@link #initialize(AbstractGoogleClientRequest)}. * </p> * * @throws IOException I/O exception */ protected void initializeProtoRequest(AbstractGoogleProtoClientRequest<?> request) throws IOException { } }
Java
/* * Copyright (c) 2013 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.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.protobuf.ProtoObjectParser; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClient extends AbstractGoogleClient { /** * @param builder builder */ protected AbstractGoogleProtoClient(Builder builder) { super(builder); } @Override public ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } /** * {@link Beta} <br/> * Builder for {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * @since 1.16 */ @Beta public abstract static class Builder extends AbstractGoogleClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ protected Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, new ProtoObjectParser(), httpRequestInitializer); } @Override public final ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } @Override public abstract AbstractGoogleProtoClient build(); @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Contains the basis for the generated service-specific libraries based on the Protobuf format. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.services.protobuf;
Java
/* * Copyright (c) 2013 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.googleapis.services.protobuf; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.http.protobuf.ProtoHttpContent; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer request for a {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClientRequest<T> extends AbstractGoogleClientRequest<T> { /** Message to serialize or {@code null} for none. */ private final MessageLite message; /** * @param abstractGoogleProtoClient Google protocol buffer client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleProtoClientRequest(AbstractGoogleProtoClient abstractGoogleProtoClient, String requestMethod, String uriTemplate, MessageLite message, Class<T> responseClass) { super(abstractGoogleProtoClient, requestMethod, uriTemplate, message == null ? null : new ProtoHttpContent(message), responseClass); this.message = message; } @Override public AbstractGoogleProtoClient getAbstractGoogleClient() { return (AbstractGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public AbstractGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (AbstractGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public AbstractGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (AbstractGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } /** * Queues the request into the specified batch request container. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * <p> * Example usage: * </p> * * <pre> * request.queue(batchRequest, new BatchCallback{@literal <}SomeResponseType, Void{@literal >}() { public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) { log("Success"); } public void onFailure(Void unused, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * * @param batchRequest batch request container * @param callback batch callback */ public final void queue(BatchRequest batchRequest, BatchCallback<T, Void> callback) throws IOException { super.queue(batchRequest, Void.class, callback); } /** Returns the message to serialize or {@code null} for none. */ public Object getMessage() { return message; } @Override public AbstractGoogleProtoClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleProtoClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2013 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.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClient extends AbstractGoogleProtoClient { /** * @param builder builder */ protected MockGoogleProtoClient(Builder builder) { super(builder); } /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public MockGoogleProtoClient(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, rootUrl, servicePath, httpRequestInitializer)); } /** * {@link Beta} <br/> * Builder for {@link MockGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleProtoClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, httpRequestInitializer); } @Override public MockGoogleProtoClient build() { return new MockGoogleProtoClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.protobuf} package. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services.protobuf;
Java
/* * Copyright (c) 2013 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.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer request. * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClientRequest<T> extends AbstractGoogleProtoClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ public MockGoogleProtoClientRequest(AbstractGoogleProtoClient client, String method, String uriTemplate, MessageLite message, Class<T> responseClass) { super(client, method, uriTemplate, message, responseClass); } @Override public MockGoogleProtoClient getAbstractGoogleClient() { return (MockGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public MockGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } }
Java
/* * Copyright (c) 2012 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. */ /** * Google OAuth 2.0 utilities that help simplify the authorization flow on Java 6. * * @since 1.11 * @author Yaniv Inbar */ package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
Java
/* * Copyright (c) 2012 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.googleapis.extensions.java6.auth.oauth2; import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; import java.io.IOException; /** * Google OAuth 2.0 abstract verification code receiver that prompts user to paste the code copied * from the browser. * * <p> * Implementation is thread-safe. * </p> * * @since 1.11 * @author Yaniv Inbar */ public class GooglePromptReceiver extends AbstractPromptReceiver { @Override public String getRedirectUri() throws IOException { return GoogleOAuthConstants.OOB_REDIRECT_URI; } }
Java
/* * Copyright (c) 2013 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.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.googleapis.notifications.UnparsedNotification; import com.google.api.client.googleapis.notifications.UnparsedNotificationCallback; import com.google.api.client.util.Beta; import com.google.api.client.util.LoggingInputStream; import com.google.api.client.util.Preconditions; import com.google.api.client.util.StringUtils; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Utilities for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookUtils { static final Logger LOGGER = Logger.getLogger(WebhookUtils.class.getName()); /** Webhook notification channel type to use in the watch request. */ public static final String TYPE = "web_hook"; /** * Utility method to process the webhook notification from {@link HttpServlet#doPost} by finding * the notification channel in the given data store factory. * * <p> * It is a wrapper around * {@link #processWebhookNotification(HttpServletRequest, HttpServletResponse, DataStore)} that * uses the data store from {@link StoredChannel#getDefaultDataStore(DataStoreFactory)}. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param dataStoreFactory data store factory * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStoreFactory dataStoreFactory) throws ServletException, IOException { processWebhookNotification(req, resp, StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Utility method to process the webhook notification from {@link HttpServlet#doPost}. * * <p> * The {@link HttpServletRequest#getInputStream()} is closed in a finally block inside this * method. If it is not detected to be a webhook notification, an * {@link HttpServletResponse#SC_BAD_REQUEST} error will be displayed. If the notification channel * is found in the given notification channel data store, it will call * {@link UnparsedNotificationCallback#onNotification} for the registered notification callback * method. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param channelDataStore notification channel data store * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStore<StoredChannel> channelDataStore) throws ServletException, IOException { Preconditions.checkArgument("POST".equals(req.getMethod())); InputStream contentStream = req.getInputStream(); try { // log headers if (LOGGER.isLoggable(Level.CONFIG)) { StringBuilder builder = new StringBuilder(); Enumeration<?> e = req.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { Object nameObj = e.nextElement(); if (nameObj instanceof String) { String name = (String) nameObj; Enumeration<?> ev = req.getHeaders(name); if (ev != null) { while (ev.hasMoreElements()) { builder.append(name) .append(": ").append(ev.nextElement()).append(StringUtils.LINE_SEPARATOR); } } } } } LOGGER.config(builder.toString()); contentStream = new LoggingInputStream(contentStream, LOGGER, Level.CONFIG, 0x4000); // TODO(yanivi): allow to override logging content limit } // parse the relevant headers, and create a notification Long messageNumber; try { messageNumber = Long.valueOf(req.getHeader(WebhookHeaders.MESSAGE_NUMBER)); } catch (NumberFormatException e) { messageNumber = null; } String resourceState = req.getHeader(WebhookHeaders.RESOURCE_STATE); String resourceId = req.getHeader(WebhookHeaders.RESOURCE_ID); String resourceUri = req.getHeader(WebhookHeaders.RESOURCE_URI); String channelId = req.getHeader(WebhookHeaders.CHANNEL_ID); String channelExpiration = req.getHeader(WebhookHeaders.CHANNEL_EXPIRATION); String channelToken = req.getHeader(WebhookHeaders.CHANNEL_TOKEN); String changed = req.getHeader(WebhookHeaders.CHANGED); if (messageNumber == null || resourceState == null || resourceId == null || resourceUri == null || channelId == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notification did not contain all required information."); return; } UnparsedNotification notification = new UnparsedNotification(messageNumber, resourceState, resourceId, resourceUri, channelId).setChannelExpiration(channelExpiration) .setChannelToken(channelToken) .setChanged(changed) .setContentType(req.getContentType()) .setContentStream(contentStream); // check if we know about the channel, hand over the notification to the notification callback StoredChannel storedChannel = channelDataStore.get(notification.getChannelId()); if (storedChannel != null) { storedChannel.getNotificationCallback().onNotification(storedChannel, notification); } } finally { contentStream.close(); } } private WebhookUtils() { } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.servlet.notifications;
Java
/* * Copyright (c) 2013 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.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.MemoryDataStoreFactory; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Thread-safe Webhook Servlet to receive notifications. * * <p> * In order to use this servlet you should create a class inheriting from * {@link NotificationServlet} and register the servlet in your web.xml. * </p> * * <p> * It is a simple wrapper around {@link WebhookUtils#processWebhookNotification}, so if you you may * alternatively call that method instead from your {@link HttpServlet#doPost} with no loss of * functionality. * </p> * * <b>Example usage:</b> * * <pre> public class MyNotificationServlet extends NotificationServlet { private static final long serialVersionUID = 1L; public MyNotificationServlet() throws IOException { super(new SomeDataStoreFactory()); } } * </pre> * * <b>Sample web.xml setup:</b> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.mypackage.MyNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * <p> * WARNING: by default it uses {@link MemoryDataStoreFactory#getDefaultInstance()} which means it * will NOT persist the notification channels when the servlet process dies, so it is a BAD CHOICE * for a production application. But it is a convenient choice when testing locally, in which case * you don't need to override it, and can simply reference it directly in your web.xml file. For * example: * </p> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.google.api.client.googleapis.extensions.servlet.notificationsNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * @author Yaniv Inbar * @since 1.16 */ @Beta public class NotificationServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** Notification channel data store. */ private final transient DataStore<StoredChannel> channelDataStore; /** * Constructor to be used for testing and demo purposes that uses * {@link MemoryDataStoreFactory#getDefaultInstance()} which means it will NOT persist the * notification channels when the servlet process dies, so it is a bad choice for a production * application. */ public NotificationServlet() throws IOException { this(MemoryDataStoreFactory.getDefaultInstance()); } /** * Constructor which uses {@link StoredChannel#getDefaultDataStore(DataStoreFactory)} on the given * data store factory, which is the normal use case. * * @param dataStoreFactory data store factory */ protected NotificationServlet(DataStoreFactory dataStoreFactory) throws IOException { this(StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Constructor that allows a specific notification data store to be specified. * * @param channelDataStore notification channel data store */ protected NotificationServlet(DataStore<StoredChannel> channelDataStore) { this.channelDataStore = channelDataStore; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebhookUtils.processWebhookNotification(req, resp, channelDataStore); } }
Java
/* * Copyright (c) 2013 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.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.ResourceStates; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Headers for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookHeaders { /** Name of header for the message number (a monotonically increasing value starting with 1). */ public static final String MESSAGE_NUMBER = "X-Goog-Message-Number"; /** Name of header for the {@link ResourceStates resource state}. */ public static final String RESOURCE_STATE = "X-Goog-Resource-State"; /** * Name of header for the opaque ID for the watched resource that is stable across API versions. */ public static final String RESOURCE_ID = "X-Goog-Resource-ID"; /** * Name of header for the opaque ID (in the form of a canonicalized URI) for the watched resource * that is sensitive to the API version. */ public static final String RESOURCE_URI = "X-Goog-Resource-URI"; /** * Name of header for the notification channel UUID provided by the client in the watch request. */ public static final String CHANNEL_ID = "X-Goog-Channel-ID"; /** Name of header for the notification channel expiration time. */ public static final String CHANNEL_EXPIRATION = "X-Goog-Channel-Expiration"; /** * Name of header for the notification channel token (an opaque string) provided by the client in * the watch request. */ public static final String CHANNEL_TOKEN = "X-Goog-Channel-Token"; /** Name of header for the type of change performed on the resource. */ public static final String CHANGED = "X-Goog-Changed"; private WebhookHeaders() { } }
Java
/* * Copyright (c) 2012 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.servlet.subscriptions;
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.googleapis.extensions.servlet.subscriptions; import com.google.api.client.googleapis.subscriptions.StoredSubscription; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.util.Beta; import com.google.api.client.util.Lists; import com.google.api.client.util.Preconditions; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * {@link Beta} <br/> * {@link SubscriptionStore} making use of JDO. * * <p> * Implementation is thread-safe. * </p> * * <b>Example usage:</b> * * <pre> service.setSubscriptionStore(new JdoSubscriptionStore()); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class JdoSubscriptionStore implements SubscriptionStore { /** Persistence manager factory. */ private final PersistenceManagerFactory persistenceManagerFactory; /** * @param persistenceManagerFactory persistence manager factory */ public JdoSubscriptionStore(PersistenceManagerFactory persistenceManagerFactory) { this.persistenceManagerFactory = persistenceManagerFactory; } /** Container class for storing subscriptions in the JDO DataStore. */ @PersistenceCapable @Beta private static final class JdoStoredSubscription { @Persistent(serialized = "true") private StoredSubscription subscription; @Persistent @PrimaryKey private String subscriptionId; @SuppressWarnings("unused") JdoStoredSubscription() { } /** * Creates a stored subscription from an existing subscription. * * @param s subscription to store */ public JdoStoredSubscription(StoredSubscription s) { setSubscription(s); } /** * Returns the stored subscription. */ public StoredSubscription getSubscription() { return subscription; } /** * Returns the subscription ID. */ @SuppressWarnings("unused") public String getSubscriptionId() { return subscriptionId; } /** * Changes the subscription stored in this database entry. * * @param subscription The new subscription to store */ public void setSubscription(StoredSubscription subscription) { this.subscription = subscription; this.subscriptionId = subscription.getId(); } } public void storeSubscription(StoredSubscription subscription) { Preconditions.checkNotNull(subscription); JdoStoredSubscription dbEntry = getStoredSubscription(subscription.getId()); PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { // Check if this subscription is being updated or newly created if (dbEntry != null) { // Existing entry dbEntry.setSubscription(subscription); } else { // New entry dbEntry = new JdoStoredSubscription(subscription); persistenceManager.makePersistent(dbEntry); } } finally { persistenceManager.close(); } } public void removeSubscription(StoredSubscription subscription) { JdoStoredSubscription dbEntry = getStoredSubscription(subscription.getId()); if (dbEntry != null) { PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { persistenceManager.deletePersistent(dbEntry); } finally { persistenceManager.close(); } } } @SuppressWarnings("unchecked") public List<StoredSubscription> listSubscriptions() { // Copy the results into a db-detached list. List<StoredSubscription> list = Lists.newArrayList(); PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { Query listQuery = persistenceManager.newQuery(JdoStoredSubscription.class); Iterable<JdoStoredSubscription> resultList = (Iterable<JdoStoredSubscription>) listQuery.execute(); for (JdoStoredSubscription dbEntry : resultList) { list.add(dbEntry.getSubscription()); } } finally { persistenceManager.close(); } return list; } @SuppressWarnings("unchecked") private JdoStoredSubscription getStoredSubscription(String subscriptionID) { Iterable<JdoStoredSubscription> results = null; PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { Query getByIDQuery = persistenceManager.newQuery(JdoStoredSubscription.class); getByIDQuery.setFilter("subscriptionId == idParam"); getByIDQuery.declareParameters("String idParam"); getByIDQuery.setRange(0, 1); results = (Iterable<JdoStoredSubscription>) getByIDQuery.execute(subscriptionID); // return the first result for (JdoStoredSubscription dbEntry : results) { return dbEntry; } return null; } finally { persistenceManager.close(); } } public StoredSubscription getSubscription(String subscriptionID) { JdoStoredSubscription dbEntry = getStoredSubscription(subscriptionID); return dbEntry == null ? null : dbEntry.getSubscription(); } }
Java
/* * Copyright (c) 2012 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.googleapis.extensions.servlet.subscriptions; import com.google.api.client.googleapis.subscriptions.NotificationHeaders; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.googleapis.subscriptions.UnparsedNotification; import com.google.api.client.util.Beta; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * WebHook Servlet to receive {@link UnparsedNotification}. * * <p> * In order to use this servlet you should create a class inheriting from * {@link AbstractWebHookServlet} and register the servlet in your web.xml. * </p> * * <p> * Implementation is thread-safe. * </p> * * <b>Example usage:</b> * * <pre> public class NotificationServlet extends AbstractWebHookServlet { private static final long serialVersionUID = 1L; {@literal @}Override protected SubscriptionStore createSubscriptionStore() { return new CachedAppEngineSubscriptionStore(); } } * </pre> * * <b>web.xml setup:</b> * * <pre> &lt;servlet&gt; &lt;servlet-name&gt;NotificationServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;com.mypackage.NotificationServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;NotificationServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/notificiations&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;security-constraint&gt; &lt;!-- Lift any ACL imposed upon the servlet --&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;any&lt;/web-resource-name&gt; &lt;url-pattern&gt;/notifications&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;/security-constraint&gt; * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @SuppressWarnings("serial") @Beta public abstract class AbstractWebHookServlet extends HttpServlet { /** * Name of header for the ID of the subscription for which you no longer wish to receive * notifications (used in the response to a WebHook notification). */ public static final String UNSUBSCRIBE_HEADER = "X-Goog-Unsubscribe"; /** Subscription store or {@code null} before initialized in {@link #getSubscriptionStore()}. */ private static SubscriptionStore subscriptionStore; /** * Used to get access to the subscription store in order to handle incoming notifications. */ protected abstract SubscriptionStore createSubscriptionStore(); /** Returns the (cached) subscription store. */ public final synchronized SubscriptionStore getSubscriptionStore() { if (subscriptionStore == null) { subscriptionStore = createSubscriptionStore(); } return subscriptionStore; } /** * Responds to a notification with a 200 OK response with the X-Unsubscribe header which causes * the subscription to be removed. */ protected void sendUnsubscribeResponse( HttpServletResponse resp, UnparsedNotification notification) { // Subscriptions can be removed by sending an 200 OK with the X-Unsubscribe header. resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader(UNSUBSCRIBE_HEADER, notification.getSubscriptionId()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Parse the relevant headers and create an unparsed notification. String subscriptionId = req.getHeader(NotificationHeaders.SUBSCRIPTION_ID); String topicId = req.getHeader(NotificationHeaders.TOPIC_ID); String topicUri = req.getHeader(NotificationHeaders.TOPIC_URI); String eventType = req.getHeader(NotificationHeaders.EVENT_TYPE_HEADER); String clientToken = req.getHeader(NotificationHeaders.CLIENT_TOKEN); String messageNumber = req.getHeader(NotificationHeaders.MESSAGE_NUMBER_HEADER); String changeType = req.getHeader(NotificationHeaders.CHANGED_HEADER); if (subscriptionId == null || topicId == null || topicUri == null || eventType == null || messageNumber == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notification did not contain all required information."); return; } // Hand over the unparsed notification to the subscription manager. InputStream contentStream = req.getInputStream(); try { UnparsedNotification notification = new UnparsedNotification(subscriptionId, topicId, topicUri, clientToken, Long.valueOf(messageNumber), eventType, changeType, req.getContentType(), contentStream); if (!notification.deliverNotification(getSubscriptionStore())) { sendUnsubscribeResponse(resp, notification); } } finally { contentStream.close(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_ordenes.java * * Created on 10/04/2011, 05:29:28 PM */ package vistas; import controladores.controlador_ordenes; import controladores.controlador_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class vista_ordenes extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); /** Creates new form vista_producto */ public vista_ordenes() { initComponents(); jTable_ordenes.setModel(modelo_tabla); Vector<String> a = new Vector<String>(); a.add("producto"); a.add("cantidad"); a.add("precio"); modelo_tabla.setColumnIdentifiers(a); listen_botones(); cancelar(); } public void cancelar() { modelo_tabla.setRowCount(0); jtxt_nombre.setText(""); } public void listen_botones() { controlador_ordenes co = new controlador_ordenes(this); co.cargar_producto(); boton_mas.addActionListener (co); boton_mas.setActionCommand("mas"); boton_menos.addActionListener(co); boton_menos.setActionCommand("menos"); boton_registrar.addActionListener(co); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_mas() { return boton_mas; } public void setBoton_mas(JButton boton_mas) { this.boton_mas = boton_mas; } public JButton getBoton_menos() { return boton_menos; } public void setBoton_menos(JButton boton_menos) { this.boton_menos = boton_menos; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JComboBox getCmb_producto() { return cmb_producto; } public void setCmb_producto(JComboBox cmb_producto) { this.cmb_producto = cmb_producto; } public JTable getjTable_ordenes() { return jTable_ordenes; } public void setjTable_ordenes(JTable jTable_ordenes) { this.jTable_ordenes = jTable_ordenes; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public JTextField getJtxt_total() { return jtxt_total; } public void setJtxt_total(JTextField jtxt_total) { this.jtxt_total = jtxt_total; } public JSpinner getJtxtcantidad() { return jtxtcantidad; } public void setJtxtcantidad(JSpinner jtxtcantidad) { this.jtxtcantidad = jtxtcantidad; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); cmb_producto = new javax.swing.JComboBox(); boton_mas = new javax.swing.JButton(); boton_menos = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_ordenes = new javax.swing.JTable(); boton_registrar = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jtxtcantidad = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jtxt_total = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel2.setText("Cliente"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 90, 90, 18); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(100, 80, 240, 28); jLabel6.setText("producto"); getContentPane().add(jLabel6); jLabel6.setBounds(10, 120, 120, 20); cmb_producto.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); cmb_producto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmb_productoActionPerformed(evt); } }); getContentPane().add(cmb_producto); cmb_producto.setBounds(100, 120, 410, 30); boton_mas.setText("+"); boton_mas.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_masActionPerformed(evt); } }); getContentPane().add(boton_mas); boton_mas.setBounds(530, 120, 40, 30); boton_menos.setText("-"); getContentPane().add(boton_menos); boton_menos.setBounds(580, 120, 40, 30); jTable_ordenes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "producto", "precio", "cantidad" } )); jScrollPane1.setViewportView(jTable_ordenes); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(10, 160, 780, 330); boton_registrar.setText("registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(310, 500, 150, 40); jLabel9.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Registrar Ordenes"); getContentPane().add(jLabel9); jLabel9.setBounds(250, 10, 290, 40); getContentPane().add(jtxtcantidad); jtxtcantidad.setBounds(710, 120, 40, 28); jLabel8.setText("cantidad"); getContentPane().add(jLabel8); jLabel8.setBounds(630, 120, 120, 20); jLabel1.setText("Total a pagar"); getContentPane().add(jLabel1); jLabel1.setBounds(470, 520, 280, 18); jtxt_total.setEditable(false); getContentPane().add(jtxt_total); jtxt_total.setBounds(600, 510, 160, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents private void cmb_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_productoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmb_productoActionPerformed private void boton_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_masActionPerformed // TODO add your handling code here: }//GEN-LAST:event_boton_masActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_ordenes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_mas; private javax.swing.JButton boton_menos; private javax.swing.JButton boton_registrar; private javax.swing.JComboBox cmb_producto; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_ordenes; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_total; private javax.swing.JSpinner jtxtcantidad; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_ingredientes.java * * Created on 08/04/2011, 10:46:47 AM */ package vistas; import controladores.controlador_ingredientes; import javax.swing.JButton; import javax.swing.JTextField; public class vista_ingredientes extends javax.swing.JFrame { /** Creates new form vista_ingredientes */ public vista_ingredientes() { initComponents(); cancenlar(); listen_botones(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jtxt_stock = new javax.swing.JTextField(); jtxt_id = new javax.swing.JTextField(); boton_cancelar = new javax.swing.JButton(); boton_modificar = new javax.swing.JButton(); boton_buscar = new javax.swing.JButton(); boton_registrar = new javax.swing.JButton(); boton_grabar = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel1.setText("ID Ingrediente"); getContentPane().add(jLabel1); jLabel1.setBounds(50, 110, 100, 18); jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Registrar Ingredientes"); getContentPane().add(jLabel2); jLabel2.setBounds(270, 20, 290, 60); jLabel3.setText("Nombre"); getContentPane().add(jLabel3); jLabel3.setBounds(50, 160, 60, 20); jLabel4.setText("Descripcion"); getContentPane().add(jLabel4); jLabel4.setBounds(380, 110, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(480, 110, 230, 120); getContentPane().add(jtxt_stock); jtxt_stock.setBounds(170, 200, 190, 30); getContentPane().add(jtxt_id); jtxt_id.setBounds(170, 110, 190, 30); boton_cancelar.setText("Cancelar"); boton_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_cancelarActionPerformed(evt); } }); getContentPane().add(boton_cancelar); boton_cancelar.setBounds(570, 320, 160, 40); boton_modificar.setText("Modificar"); getContentPane().add(boton_modificar); boton_modificar.setBounds(400, 320, 160, 40); boton_buscar.setText("Buscar"); getContentPane().add(boton_buscar); boton_buscar.setBounds(60, 320, 160, 40); boton_registrar.setText("Registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(230, 320, 160, 40); boton_grabar.setText("Grabar"); getContentPane().add(boton_grabar); boton_grabar.setBounds(400, 270, 160, 40); jLabel5.setText("stock"); getContentPane().add(jLabel5); jLabel5.setBounds(50, 210, 70, 20); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(170, 160, 190, 30); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-430)/2, 802, 430); }// </editor-fold>//GEN-END:initComponents private void boton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_cancelarActionPerformed // TODO add your handling code here: cancenlar(); }//GEN-LAST:event_boton_cancelarActionPerformed /** * @param args the command line arguments */ public void cancenlar() { boton_grabar.setEnabled(false); boton_modificar.setEnabled(false); boton_registrar.setEnabled(false); boton_buscar.setEnabled(true); jtxt_id.setEnabled(true); jtxt_nombre.setEnabled(false); jtxt_stock.setEnabled(false); jtxt_descripcion.setEnabled(false); jtxt_id.setText(""); jtxt_nombre.setText(""); jtxt_descripcion.setText(""); jtxt_stock.setText(""); } public void modificar() { jtxt_descripcion.setEnabled(true); jtxt_nombre.setEnabled(true); jtxt_stock.setEnabled(true); jtxt_id.setEnabled(false); boton_modificar.setEnabled(false); boton_grabar.setEnabled(true); } public void listen_botones() { controlador_ingredientes ci = new controlador_ingredientes(this); boton_buscar.addActionListener (ci); boton_buscar.setActionCommand("buscar"); boton_grabar.addActionListener(ci); boton_grabar.setActionCommand("grabar"); boton_modificar.addActionListener(ci); boton_modificar.setActionCommand("modificar"); boton_registrar.addActionListener(ci); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_buscar() { return boton_buscar; } public void setBoton_buscar(JButton boton_buscar) { this.boton_buscar = boton_buscar; } public JButton getBoton_cancelar() { return boton_cancelar; } public void setBoton_cancelar(JButton boton_cancelar) { this.boton_cancelar = boton_cancelar; } public JButton getBoton_grabar() { return boton_grabar; } public void setBoton_grabar(JButton boton_grabar) { this.boton_grabar = boton_grabar; } public JButton getBoton_modificar() { return boton_modificar; } public void setBoton_modificar(JButton boton_modificar) { this.boton_modificar = boton_modificar; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JTextField getJtxt_stock() { return jtxt_stock; } public void setJtxt_stock(JTextField jtxt_stock) { this.jtxt_stock = jtxt_stock; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_id() { return jtxt_id; } public void setJtxt_id(JTextField jtxt_id) { this.jtxt_id = jtxt_id; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_ingredientes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_buscar; private javax.swing.JButton boton_cancelar; private javax.swing.JButton boton_grabar; private javax.swing.JButton boton_modificar; private javax.swing.JButton boton_registrar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_id; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_stock; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_producto.java * * Created on 10/04/2011, 12:21:37 PM */ package vistas; import controladores.controlador_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class vista_producto extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); /** Creates new form vista_producto */ public vista_producto() { initComponents(); jTable_producto.setModel(modelo_tabla); Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); modelo_tabla.setColumnIdentifiers(a); listen_botones(); cancelar(); } public void cancelar() { modelo_tabla.setRowCount(0); jtxt_codigo.setText(""); jtxt_descripcion.setText(""); jtxt_nombre.setText(""); jtxt_precio.setText(""); jtxtcantidad.setValue(0); } public void listen_botones() { controlador_productos cp = new controlador_productos(this); cp.cargar_categoria(); cp.cargar_ingredientes(); boton_mas.addActionListener (cp); boton_mas.setActionCommand("mas"); boton_menos.addActionListener(cp); boton_menos.setActionCommand("menos"); boton_registrar.addActionListener(cp); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_mas() { return boton_mas; } public void setBoton_mas(JButton boton_mas) { this.boton_mas = boton_mas; } public JButton getBoton_menos() { return boton_menos; } public void setBoton_menos(JButton boton_menos) { this.boton_menos = boton_menos; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JComboBox getCmb_categoria() { return cmb_categoria; } public void setCmb_categoria(JComboBox cmb_categoria) { this.cmb_categoria = cmb_categoria; } public JComboBox getCmb_ingrediente() { return cmb_ingrediente; } public void setCmb_ingrediente(JComboBox cmb_ingrediente) { this.cmb_ingrediente = cmb_ingrediente; } public JTable getjTable_producto() { return jTable_producto; } public void setjTable_producto(JTable jTable_producto) { this.jTable_producto = jTable_producto; } public JTextField getJtxt_codigo() { return jtxt_codigo; } public void setJtxt_codigo(JTextField jtxt_codigo) { this.jtxt_codigo = jtxt_codigo; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public JTextField getJtxt_precio() { return jtxt_precio; } public void setJtxt_precio(JTextField jtxt_precio) { this.jtxt_precio = jtxt_precio; } public JSpinner getJtxtcantidad() { return jtxtcantidad; } public void setJtxtcantidad(JSpinner jtxtcantidad) { this.jtxtcantidad = jtxtcantidad; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel3 = new javax.swing.JLabel(); jtxt_codigo = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jtxt_precio = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); cmb_categoria = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); cmb_ingrediente = new javax.swing.JComboBox(); boton_mas = new javax.swing.JButton(); boton_menos = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jtxtcantidad = new javax.swing.JSpinner(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_producto = new javax.swing.JTable(); jLabel9 = new javax.swing.JLabel(); boton_registrar = new javax.swing.JButton(); getContentPane().setLayout(null); jLabel3.setText("Codigo"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 70, 60, 30); jtxt_codigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtxt_codigoActionPerformed(evt); } }); getContentPane().add(jtxt_codigo); jtxt_codigo.setBounds(110, 80, 160, 28); jLabel2.setText("nombre"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 120, 90, 18); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(110, 120, 240, 30); jLabel4.setText("precio"); getContentPane().add(jLabel4); jLabel4.setBounds(10, 220, 44, 18); getContentPane().add(jtxt_precio); jtxt_precio.setBounds(110, 210, 160, 30); jLabel5.setText("Categoria"); getContentPane().add(jLabel5); jLabel5.setBounds(10, 170, 110, 20); cmb_categoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); getContentPane().add(cmb_categoria); cmb_categoria.setBounds(110, 170, 240, 28); jLabel1.setText("descripcion"); getContentPane().add(jLabel1); jLabel1.setBounds(10, 260, 100, 18); jLabel6.setText("Ingrediente"); getContentPane().add(jLabel6); jLabel6.setBounds(390, 70, 120, 20); cmb_ingrediente.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); cmb_ingrediente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmb_ingredienteActionPerformed(evt); } }); getContentPane().add(cmb_ingrediente); cmb_ingrediente.setBounds(480, 70, 190, 30); boton_mas.setText("+"); boton_mas.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_masActionPerformed(evt); } }); getContentPane().add(boton_mas); boton_mas.setBounds(680, 70, 40, 30); boton_menos.setText("-"); getContentPane().add(boton_menos); boton_menos.setBounds(730, 70, 40, 30); jLabel7.setText("Bs.F"); getContentPane().add(jLabel7); jLabel7.setBounds(280, 220, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(110, 260, 240, 90); jLabel8.setText("cantidad"); getContentPane().add(jLabel8); jLabel8.setBounds(390, 110, 120, 20); getContentPane().add(jtxtcantidad); jtxtcantidad.setBounds(480, 110, 40, 28); jTable_producto.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "nombre", "cantidad" } )); jScrollPane1.setViewportView(jTable_producto); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(390, 160, 400, 190); jLabel9.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Registrar Productos"); getContentPane().add(jLabel9); jLabel9.setBounds(250, 10, 290, 40); boton_registrar.setText("registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(390, 360, 150, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-447)/2, 802, 447); }// </editor-fold>//GEN-END:initComponents private void jtxt_codigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxt_codigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jtxt_codigoActionPerformed private void cmb_ingredienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_ingredienteActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmb_ingredienteActionPerformed private void boton_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_masActionPerformed // TODO add your handling code here: }//GEN-LAST:event_boton_masActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_producto().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_mas; private javax.swing.JButton boton_menos; private javax.swing.JButton boton_registrar; private javax.swing.JComboBox cmb_categoria; private javax.swing.JComboBox cmb_ingrediente; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_producto; private javax.swing.JTextField jtxt_codigo; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_precio; private javax.swing.JSpinner jtxtcantidad; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_categorias.java * * Created on 08/04/2011, 10:46:59 AM */ package vistas; import controladores.controlador_categorias; import javax.swing.JButton; import javax.swing.JTextField; public class vista_categorias extends javax.swing.JFrame { /** Creates new form vista_categorias */ public vista_categorias() { initComponents(); cancenlar(); listen_botones(); } public void cancenlar() { boton_grabar.setEnabled(false); boton_modificar.setEnabled(false); boton_registrar.setEnabled(false); boton_buscar.setEnabled(true); jtxt_id.setEnabled(true); jtxt_nombre.setEnabled(false); jtxt_descripcion.setEnabled(false); jtxt_id.setText(""); jtxt_nombre.setText(""); jtxt_descripcion.setText(""); } public void modificar() { jtxt_descripcion.setEnabled(true); jtxt_nombre.setEnabled(true); jtxt_id.setEnabled(false); boton_modificar.setEnabled(false); boton_grabar.setEnabled(true); } public void listen_botones() { controlador_categorias cc = new controlador_categorias(this); boton_buscar.addActionListener (cc); boton_buscar.setActionCommand("buscar"); boton_grabar.addActionListener(cc); boton_grabar.setActionCommand("grabar"); boton_modificar.addActionListener(cc); boton_modificar.setActionCommand("modificar"); boton_registrar.addActionListener(cc); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_buscar() { return boton_buscar; } public void setBoton_buscar(JButton boton_buscar) { this.boton_buscar = boton_buscar; } public JButton getBoton_cancelar() { return boton_cancelar; } public void setBoton_cancelar(JButton boton_cancelar) { this.boton_cancelar = boton_cancelar; } public JButton getBoton_grabar() { return boton_grabar; } public void setBoton_grabar(JButton boton_grabar) { this.boton_grabar = boton_grabar; } public JButton getBoton_modificar() { return boton_modificar; } public void setBoton_modificar(JButton boton_modificar) { this.boton_modificar = boton_modificar; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_id() { return jtxt_id; } public void setJtxt_id(JTextField jtxt_id) { this.jtxt_id = jtxt_id; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jtxt_id = new javax.swing.JTextField(); boton_cancelar = new javax.swing.JButton(); boton_modificar = new javax.swing.JButton(); boton_buscar = new javax.swing.JButton(); boton_registrar = new javax.swing.JButton(); boton_grabar = new javax.swing.JButton(); jtxt_nombre = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel1.setText("ID Categoria"); getContentPane().add(jLabel1); jLabel1.setBounds(50, 110, 100, 18); jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Registrar Categorias"); getContentPane().add(jLabel2); jLabel2.setBounds(270, 20, 290, 60); jLabel3.setText("Nombre"); getContentPane().add(jLabel3); jLabel3.setBounds(50, 160, 60, 20); jLabel4.setText("Descripcion"); getContentPane().add(jLabel4); jLabel4.setBounds(380, 110, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(480, 110, 230, 120); getContentPane().add(jtxt_id); jtxt_id.setBounds(170, 110, 190, 30); boton_cancelar.setText("Cancelar"); boton_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_cancelarActionPerformed(evt); } }); getContentPane().add(boton_cancelar); boton_cancelar.setBounds(570, 320, 160, 40); boton_modificar.setText("Modificar"); getContentPane().add(boton_modificar); boton_modificar.setBounds(400, 320, 160, 40); boton_buscar.setText("Buscar"); getContentPane().add(boton_buscar); boton_buscar.setBounds(60, 320, 160, 40); boton_registrar.setText("Registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(230, 320, 160, 40); boton_grabar.setText("Grabar"); getContentPane().add(boton_grabar); boton_grabar.setBounds(400, 270, 160, 40); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(170, 160, 190, 30); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-430)/2, 802, 430); }// </editor-fold>//GEN-END:initComponents private void boton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_cancelarActionPerformed // TODO add your handling code here: cancenlar(); }//GEN-LAST:event_boton_cancelarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_categorias().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_buscar; private javax.swing.JButton boton_cancelar; private javax.swing.JButton boton_grabar; private javax.swing.JButton boton_modificar; private javax.swing.JButton boton_registrar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_id; private javax.swing.JTextField jtxt_nombre; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_listado_ingredientes.java * * Created on 10/04/2011, 07:59:25 PM */ package vistas; import controladores.controlador_listado_ingredientes; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class vista_listado_ingredientes extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); controlador_listado_ingredientes cli; /** Creates new form vista_listado_ingredientes */ public vista_listado_ingredientes() { Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); modelo_tabla.setColumnIdentifiers(a); initComponents(); listen_botones(); } void listen_botones() { cli = new controlador_listado_ingredientes(this); jTable_productos.setModel(modelo_tabla); boton_consultar.addActionListener(cli); boton_consultar.setActionCommand("consultar"); } public JButton getBoton_consultar() { return boton_consultar; } public void setBoton_consultar(JButton boton_consultar) { this.boton_consultar = boton_consultar; } public controlador_listado_ingredientes getCli() { return cli; } public void setCli(controlador_listado_ingredientes cli) { this.cli = cli; } public JLabel getjLabel1() { return jLabel1; } public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; } public JScrollPane getjScrollPane1() { return jScrollPane1; } public void setjScrollPane1(JScrollPane jScrollPane1) { this.jScrollPane1 = jScrollPane1; } public JTable getjTable_productos() { return jTable_productos; } public void setjTable_productos(JTable jTable_productos) { this.jTable_productos = jTable_productos; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { boton_consultar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_productos = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); boton_consultar.setText("Consultar"); getContentPane().add(boton_consultar); boton_consultar.setBounds(620, 80, 140, 40); jTable_productos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable_productos); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(20, 150, 740, 430); jLabel1.setText("consultar cantidad de ingredientes"); getContentPane().add(jLabel1); jLabel1.setBounds(220, 20, 400, 18); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_listado_ingredientes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_consultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_productos; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_listado_productos.java * * Created on 10/04/2011, 07:59:07 PM */ package vistas; import controladores.controlador_listado_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class vista_listado_productos extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); controlador_listado_productos clp; /** Creates new form vista_listado_productos */ public vista_listado_productos() { Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); a.add("precio"); modelo_tabla.setColumnIdentifiers(a); initComponents(); listen_botones(); } void listen_botones() { clp = new controlador_listado_productos(this); jTable_productos.setModel(modelo_tabla); boton_consultar.addActionListener(clp); boton_consultar.setActionCommand("consultar"); } public JButton getBoton_consultar() { return boton_consultar; } public void setBoton_consultar(JButton boton_consultar) { this.boton_consultar = boton_consultar; } public controlador_listado_productos getClp() { return clp; } public void setClp(controlador_listado_productos clp) { this.clp = clp; } public JLabel getjLabel1() { return jLabel1; } public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; } public JScrollPane getjScrollPane1() { return jScrollPane1; } public void setjScrollPane1(JScrollPane jScrollPane1) { this.jScrollPane1 = jScrollPane1; } public JTable getjTable_productos() { return jTable_productos; } public void setjTable_productos(JTable jTable_productos) { this.jTable_productos = jTable_productos; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable_productos = new javax.swing.JTable(); boton_consultar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jTable_productos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable_productos); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(20, 150, 740, 430); boton_consultar.setText("Consultar"); getContentPane().add(boton_consultar); boton_consultar.setBounds(620, 80, 140, 40); jLabel1.setText("Consultar ventas de productos"); getContentPane().add(jLabel1); jLabel1.setBounds(220, 20, 400, 18); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_listado_productos().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_consultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_productos; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; import modelos.*; import vistas.vista_producto; public class controlador_productos implements ActionListener { vista_producto v_pro; modelo_productos m_pro; modelo_categorias m_cat; modelo_ingredientes m_ing; ArrayList<modelo_ingredientes> lista_ingredientes; ArrayList<modelo_ingredientes> lista_ingredientes_guardar; ArrayList<modelo_categorias> lista_categorias; modelo_ingredientes m_ing_guardar; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("mas")) mas(); else if (comando.equals("menos")) menos(); else if (comando.equals("registrar")) registrar(); } public controlador_productos(vista_producto v_pro) { this.v_pro = v_pro; m_cat = new modelo_categorias(); m_ing = new modelo_ingredientes(); m_pro = new modelo_productos(); lista_ingredientes_guardar =new ArrayList<modelo_ingredientes>(); } void mas() { Vector<String> fila = new Vector<String>(); m_ing_guardar = new modelo_ingredientes(); int posi_ingrediente=v_pro.getCmb_ingrediente().getSelectedIndex(); m_ing_guardar.setId(lista_ingredientes.get(posi_ingrediente).getId().toString()); m_ing_guardar.setNombre(lista_ingredientes.get(posi_ingrediente).getNombre().toString()); m_ing_guardar.setStock(Float.parseFloat(v_pro.getJtxtcantidad().getValue().toString())); fila.add(m_ing_guardar.getNombre()); fila.add(String.valueOf(m_ing_guardar.getStock())); v_pro.getModelo_tabla().addRow(fila); lista_ingredientes_guardar.add(m_ing_guardar); } void menos() { if(v_pro.getModelo_tabla().getRowCount()>0) { v_pro.getModelo_tabla().removeRow(v_pro.getjTable_producto().getSelectedRow()); lista_ingredientes_guardar.remove(v_pro.getjTable_producto().getSelectedRow()); } } void registrar() { if(hayVacio()) { m_pro.insertar(v_pro.getJtxt_codigo().getText(),v_pro.getJtxt_nombre().getText(),v_pro.getJtxt_descripcion().getText(),lista_categorias.get(v_pro.getCmb_categoria().getSelectedIndex()).getId(),v_pro.getJtxt_precio().getText(),lista_ingredientes_guardar); aviso("se ha registrado el producto exitosamente"); v_pro.cancelar(); } else { aviso("verifique, faltan por llenar datos"); } } public void cargar_categoria() { lista_categorias = m_cat.lista(); for (int i = 0; i < lista_categorias.size(); i++) { v_pro.getCmb_categoria().addItem(lista_categorias.get(i).getNombre()); } } public void cargar_ingredientes() { lista_ingredientes = m_ing.lista(); for (int i = 0; i < lista_ingredientes.size(); i++) { v_pro.getCmb_ingrediente().addItem(lista_ingredientes.get(i).getNombre()); } } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_pro, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_pro, mensaje); return i; } public boolean hayVacio() { if(v_pro.getJtxt_codigo().getText().isEmpty() || v_pro.getJtxt_nombre().getText().isEmpty() || v_pro.getJtxt_descripcion().getText().isEmpty() || v_pro.getJtxt_precio().getText().isEmpty()) return false; else return true; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import modelos.modelo_ingredientes; import modelos.modelo_listado_ingredientes; import vistas.vista_listado_ingredientes; public class controlador_listado_ingredientes implements ActionListener{ vista_listado_ingredientes v_l_i; modelo_ingredientes m_ing = new modelo_ingredientes(); ArrayList<modelo_ingredientes> listado_ingredientes = new ArrayList<modelo_ingredientes>(); public controlador_listado_ingredientes (vista_listado_ingredientes v_l_i) { this.v_l_i = v_l_i; } public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("consultar")) { consultar(); } } void consultar() { v_l_i.getModelo_tabla().setRowCount(0); listado_ingredientes=m_ing.lista(); Vector<String> a; for (int i = 0; i < listado_ingredientes.size(); i++) { a = new Vector<String>(); a.add(listado_ingredientes.get(i).getNombre()); a.add(String.valueOf(listado_ingredientes.get(i).getStock())); v_l_i.getModelo_tabla().addRow(a); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import modelos.*; import vistas.*; public class controlador_ingredientes implements ActionListener { vista_ingredientes v_ing; modelo_ingredientes m_ing; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("buscar")) buscar(); else if (comando.equals("grabar")) grabar(); else if (comando.equals("modificar")) modificar(); else if (comando.equals("registrar")) registrar(); } public controlador_ingredientes(vista_ingredientes v_ing ) { this.v_ing = v_ing; m_ing = new modelo_ingredientes(); } void buscar() { if(v_ing.getJtxt_id().getText().isEmpty()) { aviso("introduzca una ID"); } else { if(m_ing.buscar(v_ing.getJtxt_id().getText())) { v_ing.getJtxt_id().setEnabled(false); v_ing.getBoton_modificar().setEnabled(true); v_ing.getBoton_buscar().setEnabled(false); v_ing.getJtxt_nombre().setText(m_ing.getNombre()); v_ing.getJtxt_descripcion().setText(m_ing.getDescripcion()); v_ing.getJtxt_stock().setText(String.valueOf(m_ing.getStock())); } else { int seleccion=pregunta("el usuario no existe, desea registrarlo?"); System.out.print(seleccion); if(seleccion ==0) { v_ing.getBoton_registrar().setEnabled(true); v_ing.getBoton_buscar().setEnabled(false); v_ing.getJtxt_id().setEnabled(false); v_ing.getJtxt_nombre().setEnabled(true); v_ing.getJtxt_descripcion().setEnabled(true); v_ing.getJtxt_stock().setEnabled(true); } else v_ing.cancenlar(); } } } void modificar() { if (v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { JOptionPane.showMessageDialog(v_ing, " verifique, no hay un id, ni un nombre"); } else { v_ing.modificar(); } } void grabar() { if(v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_ing.modificar(v_ing.getJtxt_id().getText(),v_ing.getJtxt_nombre().getText(),v_ing.getJtxt_descripcion().getText(),v_ing.getJtxt_stock().getText()); aviso("se ha guardado exitosamente"); } v_ing.cancenlar(); } void registrar() { if(v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_ing.insertar(v_ing.getJtxt_id().getText(),v_ing.getJtxt_nombre().getText(),v_ing.getJtxt_descripcion().getText(),v_ing.getJtxt_stock().getText()); aviso("se ha registrado exitosamente"); } v_ing.cancenlar(); } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_ing, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_ing, mensaje); return i; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import modelos.*; import vistas.*; public class controlador_categorias implements ActionListener { vista_categorias v_cat; modelo_categorias m_cat; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("buscar")) buscar(); else if (comando.equals("grabar")) grabar(); else if (comando.equals("modificar")) modificar(); else if (comando.equals("registrar")) registrar(); } public controlador_categorias(vista_categorias v_cat ) { this.v_cat = v_cat; m_cat = new modelo_categorias(); } void buscar() { if(v_cat.getJtxt_id().getText().isEmpty()) { aviso("introduzca una ID"); } else { if(m_cat.buscar(v_cat.getJtxt_id().getText())) { v_cat.getJtxt_id().setEnabled(false); v_cat.getBoton_modificar().setEnabled(true); v_cat.getBoton_buscar().setEnabled(false); v_cat.getJtxt_nombre().setText(m_cat.getNombre()); v_cat.getJtxt_descripcion().setText(m_cat.getDescripcion()); } else { int seleccion=pregunta("la categoria no existe, desea registrarlo?"); System.out.print(seleccion); if(seleccion ==0) { v_cat.getBoton_registrar().setEnabled(true); v_cat.getBoton_buscar().setEnabled(false); v_cat.getJtxt_id().setEnabled(false); v_cat.getJtxt_nombre().setEnabled(true); v_cat.getJtxt_descripcion().setEnabled(true); } else v_cat.cancenlar(); } } } void modificar() { if (v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { JOptionPane.showMessageDialog(v_cat, " verifique, no hay un id, ni un nombre"); } else { v_cat.modificar(); } } void grabar() { if(v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_cat.modificar(v_cat.getJtxt_id().getText(),v_cat.getJtxt_nombre().getText(),v_cat.getJtxt_descripcion().getText()); aviso("se ha guardado exitosamente"); } v_cat.cancenlar(); } void registrar() { if(v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_cat.insertar(v_cat.getJtxt_id().getText(),v_cat.getJtxt_nombre().getText(),v_cat.getJtxt_descripcion().getText()); aviso("se ha registrado exitosamente"); } v_cat.cancenlar(); } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_cat, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_cat, mensaje); return i; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import modelos.modelo_listado_productos; import modelos.modelo_ordenes; import vistas.vista_listado_productos; public class controlador_listado_productos implements ActionListener{ vista_listado_productos v_l_p;; modelos.modelo_ordenes m_ord = new modelo_ordenes(); ArrayList<modelo_listado_productos> listado_producto = new ArrayList<modelo_listado_productos>(); public controlador_listado_productos (vista_listado_productos v_l_p) { this.v_l_p = v_l_p; } public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("consultar")) { consultar(); } } void consultar() { v_l_p.getModelo_tabla().setRowCount(0); listado_producto=m_ord.listado(); Vector<String> a; for (int i = 0; i < listado_producto.size(); i++) { a = new Vector<String>(); a.add(listado_producto.get(i).getNombre_producto()); a.add(String.valueOf(listado_producto.get(i).getCantidad_producto())); a.add(String.valueOf(listado_producto.get(i).getPrecio_orden())); v_l_p.getModelo_tabla().addRow(a); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; import modelos.modelo_ingredientes; import modelos.modelo_ordenes; import modelos.modelo_productos; import vistas.vista_ordenes; public class controlador_ordenes implements ActionListener { vista_ordenes v_ord ; modelo_ordenes m_ord = new modelo_ordenes(); modelo_productos m_pro = new modelo_productos(); modelo_productos m_pro_guardar = new modelo_productos(); modelo_ingredientes m_ing_guardar = new modelo_ingredientes(); ArrayList<modelo_productos> lista_productos = new ArrayList<modelo_productos>(); ArrayList<modelo_ingredientes> lista_ingredientes_guardar = new ArrayList<modelo_ingredientes>(); ArrayList<modelo_productos> lista_productos_guardar= new ArrayList<modelo_productos>(); public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("mas")) mas(); else if (comando.equals("menos")) menos(); else if (comando.equals("registrar")) registrar(); } public controlador_ordenes(vista_ordenes v_ord) { this.v_ord = v_ord; } void mas() { Vector<String> fila = new Vector<String>(); int posi_producto = v_ord.getCmb_producto().getSelectedIndex(); m_pro_guardar.setId(lista_productos.get(posi_producto).getId().toString()); m_pro_guardar.setNombre(lista_productos.get(posi_producto).getNombre().toString()); m_pro_guardar.setPrecio(lista_productos.get(posi_producto).getPrecio()); m_ing_guardar.setStock(Float.parseFloat(v_ord.getJtxtcantidad().getValue().toString())); fila.add(m_pro_guardar.getNombre()); fila.add(String.valueOf(m_pro_guardar.getPrecio())); fila.add(String.valueOf(v_ord.getJtxtcantidad().getValue())); v_ord.getModelo_tabla().addRow(fila); lista_productos_guardar.add(m_pro_guardar); lista_ingredientes_guardar.add(m_ing_guardar); } void menos() { if(v_ord.getModelo_tabla().getRowCount()>0) { v_ord.getModelo_tabla().removeRow(v_ord.getjTable_ordenes().getSelectedRow()); lista_productos_guardar.remove(v_ord.getjTable_ordenes().getSelectedRow()); lista_ingredientes_guardar.remove(v_ord.getjTable_ordenes().getSelectedRow()); System.out.print(lista_ingredientes_guardar.size()); } } void registrar() { if(hayVacio()) { float total_general=total_general(); v_ord.getJtxt_total().setText(String.valueOf(total_general)); aviso("se ha registrado la orden con exito"); m_ord.registrar(v_ord.getJtxt_nombre().getText().toString(),Float.parseFloat(v_ord.getJtxt_total().getText().toString()),lista_productos_guardar,lista_ingredientes_guardar); v_ord.cancelar(); } else { aviso("faltan campos por llenar"); } } public void cargar_producto() { lista_productos = m_pro.lista(); for (int i = 0; i < lista_productos.size(); i++) { v_ord.getCmb_producto().addItem(lista_productos.get(i).getNombre()); } } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_ord, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_ord, mensaje); return i; } public boolean hayVacio() { if(v_ord.getJtxt_nombre().getText().isEmpty()) return false; else return true; } public float total_general() { float total_general=0; float total_general2=0; for (int i = 0; i < v_ord.getModelo_tabla().getRowCount(); i++) { total_general= Float.parseFloat(v_ord.getjTable_ordenes().getValueAt(i, 2).toString())*Float.parseFloat(v_ord.getjTable_ordenes().getValueAt(i, 1).toString()); total_general2+=total_general; } return total_general2; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MenuPrincipal.java * */ /** Integrantes : * Rosbely Gonzalez * Jaily Leon * Mariant Barroeta * Maria Alejandra Leal * */ package general; import vistas.vista_categorias; import vistas.vista_ingredientes; import vistas.vista_listado_ingredientes; import vistas.vista_listado_productos; import vistas.vista_ordenes; import vistas.vista_producto; public class MenuPrincipal extends javax.swing.JFrame { /** Creates new form MenuPrincipal */ public MenuPrincipal() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { desktopPane = new javax.swing.JDesktopPane(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); boton_ingrediente = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); boton_categoria = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); boton_ordenes = new javax.swing.JMenuItem(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); fileMenu.setText("Ingrediente"); boton_ingrediente.setText("Registrar"); boton_ingrediente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_ingredienteActionPerformed(evt); } }); fileMenu.add(boton_ingrediente); menuBar.add(fileMenu); editMenu.setText("Categoria"); boton_categoria.setText("registrar"); boton_categoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_categoriaActionPerformed(evt); } }); editMenu.add(boton_categoria); menuBar.add(editMenu); helpMenu.setText("Producto"); boton_ordenes.setText("Registrar"); boton_ordenes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_ordenesActionPerformed(evt); } }); helpMenu.add(boton_ordenes); menuBar.add(helpMenu); jMenu1.setText("Ordenes"); jMenuItem1.setText("registrar"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); menuBar.add(jMenu1); jMenu2.setText("listados"); jMenuItem2.setText("Ventas por productos"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu2.add(jMenuItem2); jMenuItem3.setText("cantidad Ingredientes"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); menuBar.add(jMenu2); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 536, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) ); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-562)/2, (screenSize.height-440)/2, 562, 440); }// </editor-fold>//GEN-END:initComponents private void boton_ingredienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_ingredienteActionPerformed // TODO add your handling code here: vista_ingredientes vi = new vista_ingredientes(); vi.show(); }//GEN-LAST:event_boton_ingredienteActionPerformed private void boton_categoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_categoriaActionPerformed // TODO add your handling code here: vista_categorias vc = new vista_categorias(); vc.show(); }//GEN-LAST:event_boton_categoriaActionPerformed private void boton_ordenesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_ordenesActionPerformed // TODO add your handling code here: vista_producto vp = new vista_producto(); vp.show(); }//GEN-LAST:event_boton_ordenesActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: vista_ordenes vo = new vista_ordenes(); vo.show(); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // TODO add your handling code here: vista_listado_productos vlp = new vista_listado_productos(); vlp.show(); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed // TODO add your handling code here: vista_listado_ingredientes vli = new vista_listado_ingredientes(); vli.show(); }//GEN-LAST:event_jMenuItem3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem boton_categoria; private javax.swing.JMenuItem boton_ingrediente; private javax.swing.JMenuItem boton_ordenes; private javax.swing.JDesktopPane desktopPane; private javax.swing.JMenu editMenu; private javax.swing.JMenu fileMenu; private javax.swing.JMenu helpMenu; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package general; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class conectarBD { public ResultSet rs; public Connection con; public Statement stmt; public String driver; public String conneccionString; public String usuario; public String clave; public boolean conectar() { driver = "org.postgresql.Driver"; conneccionString = "jdbc:postgresql://localhost:5432/labUno"; usuario = "postgres"; clave = "123456";// try { Class.forName(driver); return true; } catch (ClassNotFoundException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); return false; } } public void desconectar() { try { con.close(); } catch (SQLException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); } } public boolean accionSql(String sql) { try { con = DriverManager.getConnection(conneccionString, usuario, clave); stmt = (Statement) con.createStatement(); rs = stmt.executeQuery(sql); return true; } catch (SQLException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); return false; } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_ingredientes extends conectarBD{ String id,nombre,descripcion; float stock; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getStock() { return stock; } public void setStock(float stock) { this.stock = stock; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean buscar(String id) { try { conectar();// base de datos String sql = " Select * from t_ingredientes where id_ingrediente = '" + id + "'"; accionSql(sql); while (rs.next()) { if(rs.getString("id_ingrediente").isEmpty()) { return false; } else { id = rs.getString("id_ingrediente"); nombre = rs.getString("nombre_ingrediente"); descripcion = rs.getString("Descripcion_ingrediente"); stock = Float.parseFloat(rs.getString("stock_ingrediente")); desconectar(); return true; } } desconectar(); return false; } catch (SQLException ex) { Logger.getLogger(modelo_ingredientes.class.getName()).log(Level.SEVERE, null, ex); desconectar(); return false; } } public boolean insertar(String id, String Nombre, String Descripcion,String stock) { conectar();// base de datos String sql = " insert into t_ingredientes (id_ingrediente,nombre_ingrediente,descripcion_ingrediente,stock_ingrediente) values ('"+id+"','"+Nombre+"','"+Descripcion+"',"+stock+")"; accionSql(sql); desconectar(); return true; } public boolean modificar(String id, String Nombre, String Descripcion,String stock) { conectar();// base de datos String sql = " update t_ingredientes SET nombre_ingrediente='"+Nombre+"',descripcion_ingrediente='"+Descripcion+"',stock_ingrediente="+stock+" where id_ingrediente='"+id+"'"; accionSql(sql); desconectar(); return true; } public ArrayList<modelo_ingredientes> lista(){ ArrayList<modelo_ingredientes> lista_ingredientes = new ArrayList<modelo_ingredientes>(); String sql="select * from t_ingredientes"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_ingredientes m_ing = new modelo_ingredientes(); m_ing.id = rs.getString("id_ingrediente"); m_ing.nombre = rs.getString("nombre_ingrediente"); System.out.print(nombre); m_ing.stock = rs.getFloat("stock_ingrediente"); m_ing.descripcion = rs.getString("descripcion_ingrediente"); lista_ingredientes.add(m_ing); System.out.print("si entra"); } } catch (SQLException ex) { Logger.getLogger(modelo_ingredientes.class.getName()).log(Level.SEVERE, null, ex); } desconectar(); System.out.print(lista_ingredientes.isEmpty()); return lista_ingredientes; } }
Java