code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* 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;
import com.google.api.client.util.Beta;
import java.io.IOException;
import java.io.Serializable;
/**
* {@link Beta} <br/>
* Callback to receive unparsed notifications for watched resource.
*
* <p>
* Must NOT be implemented in form of an anonymous class since this would break serialization.
* </p>
*
* <p>
* Should be thread-safe as several notifications might be processed at the same time.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
static class MyNotificationCallback implements UnparsedNotificationCallback {
private static final long serialVersionUID = 1L;
{@literal @}Override
public void onNotification(StoredChannel storedChannel, UnparsedNotification notification) {
String contentType = notification.getContentType();
InputStream contentStream = notification.getContentStream();
switch (notification.getResourceState()) {
case ResourceStates.SYNC:
break;
case ResourceStates.EXISTS:
break;
case ResourceStates.NOT_EXISTS:
break;
}
}
}
* </pre>
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public interface UnparsedNotificationCallback extends Serializable {
/**
* Handles a received unparsed notification.
*
* @param storedChannel stored notification channel
* @param notification unparsed notification
*/
void onNotification(StoredChannel storedChannel, UnparsedNotification notification)
throws IOException;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/UnparsedNotificationCallback.java | Java | asf20 | 2,155 |
/*
* 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;
import java.util.UUID;
/**
* Utilities for notifications and notification channels.
*
* @author Yaniv Inbar
* @since 1.16
*/
public final class NotificationUtils {
/** Returns a new random UUID string to be used as a notification channel ID. */
public static String randomUuidString() {
return UUID.randomUUID().toString();
}
private NotificationUtils() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/NotificationUtils.java | Java | asf20 | 1,029 |
/*
* 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;
import com.google.api.client.util.Beta;
/**
* {@link Beta} <br/>
* Notification metadata and parsed content sent to this client about a watched resource.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @param <T> Java type of the notification content
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public class TypedNotification<T> extends AbstractNotification {
/** Parsed notification content or {@code null} for none. */
private T content;
/**
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param resourceState {@link ResourceStates resource state}
* @param resourceId opaque ID for the watched resource that is stable across API versions
* @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that
* is sensitive to the API version
* @param channelId notification channel UUID provided by the client in the watch request
*/
public TypedNotification(long messageNumber, String resourceState, String resourceId,
String resourceUri, String channelId) {
super(messageNumber, resourceState, resourceId, resourceUri, channelId);
}
/**
* @param sourceNotification source notification metadata to copy
*/
public TypedNotification(UnparsedNotification sourceNotification) {
super(sourceNotification);
}
/**
* Returns the parsed notification content or {@code null} for none.
*/
public final T getContent() {
return content;
}
/**
* Sets the parsed notification content 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>
*/
public TypedNotification<T> setContent(T content) {
this.content = content;
return this;
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setMessageNumber(long messageNumber) {
return (TypedNotification<T>) super.setMessageNumber(messageNumber);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setResourceState(String resourceState) {
return (TypedNotification<T>) super.setResourceState(resourceState);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setResourceId(String resourceId) {
return (TypedNotification<T>) super.setResourceId(resourceId);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setResourceUri(String resourceUri) {
return (TypedNotification<T>) super.setResourceUri(resourceUri);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setChannelId(String channelId) {
return (TypedNotification<T>) super.setChannelId(channelId);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setChannelExpiration(String channelExpiration) {
return (TypedNotification<T>) super.setChannelExpiration(channelExpiration);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setChannelToken(String channelToken) {
return (TypedNotification<T>) super.setChannelToken(channelToken);
}
@Override
@SuppressWarnings("unchecked")
public TypedNotification<T> setChanged(String changed) {
return (TypedNotification<T>) super.setChanged(changed);
}
@Override
public String toString() {
return super.toStringHelper().add("content", content).toString();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/TypedNotification.java | Java | asf20 | 4,160 |
/*
* 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;
import com.google.api.client.util.Beta;
import com.google.api.client.util.Objects;
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.io.Serializable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* {@link Beta} <br/>
* Notification channel information to be stored in a data store.
*
* <p>
* Implementation is thread safe.
* </p>
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public final class StoredChannel implements Serializable {
/** Default data store ID. */
public static final String DEFAULT_DATA_STORE_ID = StoredChannel.class.getSimpleName();
private static final long serialVersionUID = 1L;
/** Lock on access to the store. */
private final Lock lock = new ReentrantLock();
/** Notification callback called when a notification is received for this subscription. */
private final UnparsedNotificationCallback notificationCallback;
/**
* Arbitrary string provided by the client associated with this subscription that is delivered to
* the target address with each notification or {@code null} for none.
*/
private String clientToken;
/**
* Milliseconds in Unix time at which the subscription will expire or {@code null} for an infinite
* TTL.
*/
private Long expiration;
/** Subscription UUID. */
private final String id;
/**
* Opaque ID for the subscribed resource that is stable across API versions or {@code null} for
* none.
*/
private String topicId;
/**
* Constructor with a random UUID using {@link NotificationUtils#randomUuidString()}.
*
* @param notificationCallback notification handler called when a notification is received for
* this subscription
*/
public StoredChannel(UnparsedNotificationCallback notificationCallback) {
this(notificationCallback, NotificationUtils.randomUuidString());
}
/**
* Constructor with a custom UUID.
*
* @param notificationCallback notification handler called when a notification is received for
* this subscription
* @param id subscription UUID
*/
public StoredChannel(UnparsedNotificationCallback notificationCallback, String id) {
this.notificationCallback = Preconditions.checkNotNull(notificationCallback);
this.id = Preconditions.checkNotNull(id);
}
/**
* Stores this notification channel in the notification channel data store, which is derived from
* {@link #getDefaultDataStore(DataStoreFactory)} on the given data store factory.
*
* <p>
* It is important that this method be called before the watch HTTP request is made in case the
* notification is received before the watch HTTP response is received.
* </p>
*
* @param dataStoreFactory data store factory
*/
public StoredChannel store(DataStoreFactory dataStoreFactory) throws IOException {
return store(getDefaultDataStore(dataStoreFactory));
}
/**
* Stores this notification channel in the given notification channel data store.
*
* <p>
* It is important that this method be called before the watch HTTP request is made in case the
* notification is received before the watch HTTP response is received.
* </p>
*
* @param dataStore notification channel data store
*/
public StoredChannel store(DataStore<StoredChannel> dataStore) throws IOException {
lock.lock();
try {
dataStore.set(getId(), this);
return this;
} finally {
lock.unlock();
}
}
/**
* Returns the notification callback called when a notification is received for this subscription.
*/
public UnparsedNotificationCallback getNotificationCallback() {
lock.lock();
try {
return notificationCallback;
} finally {
lock.unlock();
}
}
/**
* Returns the arbitrary string provided by the client associated with this subscription that is
* delivered to the target address with each notification or {@code null} for none.
*/
public String getClientToken() {
lock.lock();
try {
return clientToken;
} finally {
lock.unlock();
}
}
/**
* Sets the the arbitrary string provided by the client associated with this subscription that is
* delivered to the target address with each notification or {@code null} for none.
*/
public StoredChannel setClientToken(String clientToken) {
lock.lock();
try {
this.clientToken = clientToken;
} finally {
lock.unlock();
}
return this;
}
/**
* Returns the milliseconds in Unix time at which the subscription will expire or {@code null} for
* an infinite TTL.
*/
public Long getExpiration() {
lock.lock();
try {
return expiration;
} finally {
lock.unlock();
}
}
/**
* Sets the milliseconds in Unix time at which the subscription will expire or {@code null} for an
* infinite TTL.
*/
public StoredChannel setExpiration(Long expiration) {
lock.lock();
try {
this.expiration = expiration;
} finally {
lock.unlock();
}
return this;
}
/** Returns the subscription UUID. */
public String getId() {
lock.lock();
try {
return id;
} finally {
lock.unlock();
}
}
/**
* Returns the opaque ID for the subscribed resource that is stable across API versions or
* {@code null} for none.
*/
public String getTopicId() {
lock.lock();
try {
return topicId;
} finally {
lock.unlock();
}
}
/**
* Sets the opaque ID for the subscribed resource that is stable across API versions or
* {@code null} for none.
*/
public StoredChannel setTopicId(String topicId) {
lock.lock();
try {
this.topicId = topicId;
} finally {
lock.unlock();
}
return this;
}
@Override
public String toString() {
return Objects.toStringHelper(StoredChannel.class)
.add("notificationCallback", getNotificationCallback()).add("clientToken", getClientToken())
.add("expiration", getExpiration()).add("id", getId()).add("topicId", getTopicId())
.toString();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof StoredChannel)) {
return false;
}
StoredChannel o = (StoredChannel) other;
return getId().equals(o.getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
/**
* Returns the stored channel data store using the ID {@link #DEFAULT_DATA_STORE_ID}.
*
* @param dataStoreFactory data store factory
* @return stored channel data store
*/
public static DataStore<StoredChannel> getDefaultDataStore(DataStoreFactory dataStoreFactory)
throws IOException {
return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/StoredChannel.java | Java | asf20 | 7,652 |
/*
* 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/>
* JSON-based notification handling for subscriptions.
*
* @author Yaniv Inbar
* @since 1.16
*/
@com.google.api.client.util.Beta
package com.google.api.client.googleapis.notifications.json;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/json/package-info.java | Java | asf20 | 838 |
/*
* 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;
import com.google.api.client.googleapis.notifications.TypedNotificationCallback;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Beta;
import java.io.IOException;
/**
* {@link Beta} <br/>
* A {@link TypedNotificationCallback} which uses an JSON content encoding.
*
* <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 JsonNotificationCallback{@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 JsonFactory getJsonFactory() throws IOException {
return new JacksonFactory();
}
{@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 JsonNotificationCallback<T> extends TypedNotificationCallback<T> {
private static final long serialVersionUID = 1L;
@Override
protected final JsonObjectParser getObjectParser() throws IOException {
return new JsonObjectParser(getJsonFactory());
}
/** Returns the JSON factory to use to parse the notification content. */
protected abstract JsonFactory getJsonFactory() throws IOException;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/json/JsonNotificationCallback.java | Java | asf20 | 2,671 |
/*
* 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 notification channels to listen for changes to watched Google API resources.
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@com.google.api.client.util.Beta
package com.google.api.client.googleapis.notifications;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/package-info.java | Java | asf20 | 907 |
/*
* 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;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.util.Beta;
import com.google.api.client.util.ObjectParser;
import com.google.api.client.util.Preconditions;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* {@link Beta} <br/>
* Callback to receive notifications for watched resource in which the . Callback which is used to
* receive typed {@link AbstractNotification}s after subscribing to a topic.
*
* <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 JsonNotificationCallback{@literal <}ListResponse{@literal >} {
private static final long serialVersionUID = 1L;
{@literal @}Override
protected void onNotification(
StoredChannel subscription, Notification notification, ListResponse content) {
switch (notification.getResourceState()) {
case ResourceStates.SYNC:
break;
case ResourceStates.EXISTS:
break;
case ResourceStates.NOT_EXISTS:
break;
}
}
{@literal @}Override
protected ObjectParser getObjectParser(Notification notification) throws IOException {
return new JsonObjectParser(new JacksonFactory());
}
{@literal @}Override
protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException {
return ListResponse.class;
}
}
* </pre>
*
* @param <T> Java type of the notification content
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public abstract class TypedNotificationCallback<T> implements UnparsedNotificationCallback {
private static final long serialVersionUID = 1L;
/**
* Handles a received typed notification.
*
* @param storedChannel stored notification channel
* @param notification typed notification
*/
protected abstract void onNotification(
StoredChannel storedChannel, TypedNotification<T> notification) throws IOException;
/** Returns an {@link ObjectParser} which can be used to parse this notification. */
protected abstract ObjectParser getObjectParser() throws IOException;
/**
* Returns the data class to parse the notification content into or {@code Void.class} if no
* notification content is expected.
*/
protected abstract Class<T> getDataClass() throws IOException;
public final void onNotification(StoredChannel storedChannel, UnparsedNotification notification)
throws IOException {
TypedNotification<T> typedNotification = new TypedNotification<T>(notification);
// TODO(yanivi): how to properly detect if there is no content?
String contentType = notification.getContentType();
if (contentType != null) {
Charset charset = new HttpMediaType(contentType).getCharsetParameter();
Class<T> dataClass = Preconditions.checkNotNull(getDataClass());
typedNotification.setContent(
getObjectParser().parseAndClose(notification.getContentStream(), charset, dataClass));
}
onNotification(storedChannel, typedNotification);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/TypedNotificationCallback.java | Java | asf20 | 3,862 |
/*
* 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;
import com.google.api.client.util.Beta;
import java.io.InputStream;
/**
* {@link Beta} <br/>
* Notification metadata and unparsed content stream sent to this client about a watched resource.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public class UnparsedNotification extends AbstractNotification {
/** Notification content media type for the content stream or {@code null} for none or unknown. */
private String contentType;
/** Notification content input stream or {@code null} for none. */
private InputStream contentStream;
/**
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param resourceState {@link ResourceStates resource state}
* @param resourceId opaque ID for the watched resource that is stable across API versions
* @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that
* is sensitive to the API version
* @param channelId notification channel UUID provided by the client in the watch request
*/
public UnparsedNotification(long messageNumber, String resourceState, String resourceId,
String resourceUri, String channelId) {
super(messageNumber, resourceState, resourceId, resourceUri, channelId);
}
/**
* Returns the notification content media type for the content stream or {@code null} for none or
* unknown.
*/
public final String getContentType() {
return contentType;
}
/**
* Sets the notification content media type for the content stream or {@code null} for none or
* unknown.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public UnparsedNotification setContentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* Returns the notification content input stream or {@code null} for none.
*/
public final InputStream getContentStream() {
return contentStream;
}
/**
* Sets the notification content content input stream 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>
*/
public UnparsedNotification setContentStream(InputStream contentStream) {
this.contentStream = contentStream;
return this;
}
@Override
public UnparsedNotification setMessageNumber(long messageNumber) {
return (UnparsedNotification) super.setMessageNumber(messageNumber);
}
@Override
public UnparsedNotification setResourceState(String resourceState) {
return (UnparsedNotification) super.setResourceState(resourceState);
}
@Override
public UnparsedNotification setResourceId(String resourceId) {
return (UnparsedNotification) super.setResourceId(resourceId);
}
@Override
public UnparsedNotification setResourceUri(String resourceUri) {
return (UnparsedNotification) super.setResourceUri(resourceUri);
}
@Override
public UnparsedNotification setChannelId(String channelId) {
return (UnparsedNotification) super.setChannelId(channelId);
}
@Override
public UnparsedNotification setChannelExpiration(String channelExpiration) {
return (UnparsedNotification) super.setChannelExpiration(channelExpiration);
}
@Override
public UnparsedNotification setChannelToken(String channelToken) {
return (UnparsedNotification) super.setChannelToken(channelToken);
}
@Override
public UnparsedNotification setChanged(String changed) {
return (UnparsedNotification) super.setChanged(changed);
}
@Override
public String toString() {
return super.toStringHelper().add("contentType", contentType).toString();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/UnparsedNotification.java | Java | asf20 | 4,541 |
/*
* 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;
import com.google.api.client.util.Beta;
import com.google.api.client.util.Objects;
import com.google.api.client.util.Preconditions;
/**
* {@link Beta} <br/>
* Notification metadata sent to this client about a watched resource.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @author Yaniv Inbar
* @author Matthias Linder (mlinder)
* @since 1.16
*/
@Beta
public abstract class AbstractNotification {
/** Message number (a monotonically increasing value starting with 1). */
private long messageNumber;
/** {@link ResourceStates Resource state}. */
private String resourceState;
/** Opaque ID for the watched resource that is stable across API versions. */
private String resourceId;
/**
* Opaque ID (in the form of a canonicalized URI) for the watched resource that is sensitive to
* the API version.
*/
private String resourceUri;
/** Notification channel UUID provided by the client in the watch request. */
private String channelId;
/** Notification channel expiration time or {@code null} for none. */
private String channelExpiration;
/**
* Notification channel token (an opaque string) provided by the client in the watch request or
* {@code null} for none.
*/
private String channelToken;
/** Type of change performed on the resource or {@code null} for none. */
private String changed;
/**
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param resourceState {@link ResourceStates resource state}
* @param resourceId opaque ID for the watched resource that is stable across API versions
* @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that
* is sensitive to the API version
* @param channelId notification channel UUID provided by the client in the watch request
*/
protected AbstractNotification(long messageNumber, String resourceState, String resourceId,
String resourceUri, String channelId) {
setMessageNumber(messageNumber);
setResourceState(resourceState);
setResourceId(resourceId);
setResourceUri(resourceUri);
setChannelId(channelId);
}
/** Copy constructor based on a source notification object. */
protected AbstractNotification(AbstractNotification source) {
this(source.getMessageNumber(), source.getResourceState(), source.getResourceId(), source
.getResourceUri(), source.getChannelId());
setChannelExpiration(source.getChannelExpiration());
setChannelToken(source.getChannelToken());
setChanged(source.getChanged());
}
@Override
public String toString() {
return toStringHelper().toString();
}
/** Returns the helper for {@link #toString()}. */
protected Objects.ToStringHelper toStringHelper() {
return Objects.toStringHelper(this).add("messageNumber", messageNumber)
.add("resourceState", resourceState).add("resourceId", resourceId)
.add("resourceUri", resourceUri).add("channelId", channelId)
.add("channelExpiration", channelExpiration).add("channelToken", channelToken)
.add("changed", changed);
}
/** Returns the message number (a monotonically increasing value starting with 1). */
public final long getMessageNumber() {
return messageNumber;
}
/**
* Sets the message number (a monotonically increasing value starting with 1).
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractNotification setMessageNumber(long messageNumber) {
Preconditions.checkArgument(messageNumber >= 1);
this.messageNumber = messageNumber;
return this;
}
/** Returns the {@link ResourceStates resource state}. */
public final String getResourceState() {
return resourceState;
}
/**
* Sets the {@link ResourceStates resource state}.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractNotification setResourceState(String resourceState) {
this.resourceState = Preconditions.checkNotNull(resourceState);
return this;
}
/** Returns the opaque ID for the watched resource that is stable across API versions. */
public final String getResourceId() {
return resourceId;
}
/**
* Sets the opaque ID for the watched resource that is stable across API versions.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractNotification setResourceId(String resourceId) {
this.resourceId = Preconditions.checkNotNull(resourceId);
return this;
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the watched resource that is
* sensitive to the API version.
*/
public final String getResourceUri() {
return resourceUri;
}
/**
* Sets the opaque ID (in the form of a canonicalized URI) for the watched resource that is
* sensitive to the API version.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractNotification setResourceUri(String resourceUri) {
this.resourceUri = Preconditions.checkNotNull(resourceUri);
return this;
}
/** Returns the notification channel UUID provided by the client in the watch request. */
public final String getChannelId() {
return channelId;
}
/**
* Sets the notification channel UUID provided by the client in the watch request.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractNotification setChannelId(String channelId) {
this.channelId = Preconditions.checkNotNull(channelId);
return this;
}
/** Returns the notification channel expiration time or {@code null} for none. */
public final String getChannelExpiration() {
return channelExpiration;
}
/**
* Sets the notification channel expiration time 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>
*/
public AbstractNotification setChannelExpiration(String channelExpiration) {
this.channelExpiration = channelExpiration;
return this;
}
/**
* Returns the notification channel token (an opaque string) provided by the client in the watch
* request or {@code null} for none.
*/
public final String getChannelToken() {
return channelToken;
}
/**
* Sets the notification channel token (an opaque string) provided by the client in the watch
* request 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>
*/
public AbstractNotification setChannelToken(String channelToken) {
this.channelToken = channelToken;
return this;
}
/**
* Returns the type of change performed on the resource or {@code null} for none.
*/
public final String getChanged() {
return changed;
}
/**
* Sets the type of change performed on the resource 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>
*/
public AbstractNotification setChanged(String changed) {
this.changed = changed;
return this;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/AbstractNotification.java | Java | asf20 | 8,466 |
/*
* 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;
import com.google.api.client.util.Beta;
/**
* {@link Beta} <br/>
* Standard resource states used by notifications.
*
* @author Yaniv Inbar
* @since 1.16
*/
@Beta
public final class ResourceStates {
/** Notification that the subscription is alive (comes with no payload). */
public static final String SYNC = "SYNC";
/** Resource exists, for example on a create or update. */
public static final String EXISTS = "EXISTS";
/** Resource does not exist, for example on a delete. */
public static final String NOT_EXISTS = "NOT_EXISTS";
private ResourceStates() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/notifications/ResourceStates.java | Java | asf20 | 1,237 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
import java.util.Collection;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* {@link Beta} <br/>
* {@link SubscriptionStore} which stores all subscription information in memory.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
* <pre>
service.setSubscriptionStore(new MemorySubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public class MemorySubscriptionStore implements SubscriptionStore {
/** Lock on the token response information. */
private final Lock lock = new ReentrantLock();
/** Map of all stored subscriptions. */
private final SortedMap<String, StoredSubscription> storedSubscriptions =
new TreeMap<String, StoredSubscription>();
public void storeSubscription(StoredSubscription subscription) {
lock.lock();
try {
storedSubscriptions.put(subscription.getId(), subscription);
} finally {
lock.unlock();
}
}
public void removeSubscription(StoredSubscription subscription) {
lock.lock();
try {
storedSubscriptions.remove(subscription.getId());
} finally {
lock.unlock();
}
}
public Collection<StoredSubscription> listSubscriptions() {
lock.lock();
try {
return Collections.unmodifiableCollection(storedSubscriptions.values());
} finally {
lock.unlock();
}
}
public StoredSubscription getSubscription(String subscriptionId) {
lock.lock();
try {
return storedSubscriptions.get(subscriptionId);
} finally {
lock.unlock();
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/MemorySubscriptionStore.java | Java | asf20 | 2,384 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
/**
* {@link Beta} <br/>
* Typed notification sent to this client about a subscribed resource.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item : notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
* </pre>
*
* @param <T> Data content from the underlying response stored within this notification
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public final class TypedNotification<T> extends Notification {
/** Typed content or {@code null} for none. */
private final T content;
/** Returns the typed content or {@code null} for none. */
public final T getContent() {
return content;
}
/**
* @param notification notification whose information is copied
* @param content typed content or {@code null} for none
*/
public TypedNotification(Notification notification, T content) {
super(notification);
this.content = content;
}
/**
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
* @param content typed content or {@code null} for none
*/
public TypedNotification(String subscriptionId, String topicId, String topicURI,
String clientToken, long messageNumber, String eventType, String changeType, T content) {
super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType);
this.content = content;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/TypedNotification.java | Java | asf20 | 2,778 |
/*
* 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/>
* JSON-based notification handling for subscriptions.
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
@com.google.api.client.util.Beta
package com.google.api.client.googleapis.subscriptions.json;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/json/package-info.java | Java | asf20 | 852 |
/*
* 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.subscriptions.json;
import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Beta;
import com.google.api.client.util.ObjectParser;
import java.io.IOException;
/**
* {@link Beta} <br/>
* A {@link TypedNotificationCallback} which uses an JSON content encoding.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
* <pre>
class MyJsonNotificationCallback extends JsonNotificationCallback<ItemList> {
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item in notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
}
JsonFactory createJsonFactory() {
return new JacksonFactory();
}
...
service.items.list("someID").subscribe(new MyJsonNotificationCallback()).execute()
* </pre>
*
* @param <T> Type of the data contained within a notification
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
@Beta
public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> {
/** JSON factory used to deserialize notifications. {@code null} until first used. */
private transient JsonFactory jsonFactory;
/**
* Returns the JSON-factory used by this handler.
*/
public final JsonFactory getJsonFactory() throws IOException {
if (jsonFactory == null) {
jsonFactory = createJsonFactory();
}
return jsonFactory;
}
// TODO(mlinder): Don't have the user supply the JsonFactory, but serialize it instead.
/**
* Creates a new JSON factory which is used to deserialize notifications.
*/
protected abstract JsonFactory createJsonFactory() throws IOException;
@Override
protected final ObjectParser getParser(UnparsedNotification notification) throws IOException {
return new JsonObjectParser(getJsonFactory());
}
@Override
public JsonNotificationCallback<T> setDataType(Class<T> dataClass) {
return (JsonNotificationCallback<T>) super.setDataType(dataClass);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/json/JsonNotificationCallback.java | Java | asf20 | 3,233 |
/*
* 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 for Google APIs.
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
@com.google.api.client.util.Beta
package com.google.api.client.googleapis.subscriptions;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/package-info.java | Java | asf20 | 876 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
/**
* {@link Beta} <br/>
* Standard event-types used by notifications.
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(Subscription subscription, UnparsedNotification notification) {
if (notification.getEventType().equals(EventTypes.UPDATED)) {
// add items in the notification to the local client state ...
}
}
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public final class EventTypes {
/** Notification that the subscription is alive (comes with no payload). */
public static final String SYNC = "sync";
/** Resource was modified. */
public static final String UPDATED = "updated";
/** Resource was deleted. */
public static final String DELETED = "deleted";
/** Private constructor to prevent instantiation. */
private EventTypes() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/EventTypes.java | Java | asf20 | 1,528 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
import com.google.api.client.util.Preconditions;
/**
* {@link Beta} <br/>
* Notification sent to this client about a subscribed resource.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public abstract class Notification {
/** Subscription UUID. */
private final String subscriptionId;
/** Opaque ID for the subscribed resource that is stable across API versions. */
private final String topicId;
/**
* Opaque ID (in the form of a canonicalized URI) for the subscribed resource that is sensitive to
* the API version.
*/
private final String topicURI;
/** Client token (an opaque string) or {@code null} for none. */
private final String clientToken;
/** Message number (a monotonically increasing value starting with 1). */
private final long messageNumber;
/** Event type (see {@link EventTypes}). */
private final String eventType;
/** Type of change performed on the resource or {@code null} for none. */
private final String changeType;
/**
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
*/
protected Notification(String subscriptionId, String topicId, String topicURI, String clientToken,
long messageNumber, String eventType, String changeType) {
this.subscriptionId = Preconditions.checkNotNull(subscriptionId);
this.topicId = Preconditions.checkNotNull(topicId);
this.topicURI = Preconditions.checkNotNull(topicURI);
this.eventType = Preconditions.checkNotNull(eventType);
this.clientToken = clientToken;
Preconditions.checkArgument(messageNumber >= 1);
this.messageNumber = messageNumber;
this.changeType = changeType;
}
/**
* Creates a new notification by copying all information specified in the source notification.
*
* @param source notification whose information is copied
*/
protected Notification(Notification source) {
this(source.getSubscriptionId(), source.getTopicId(), source.getTopicURI(), source
.getClientToken(), source.getMessageNumber(), source.getEventType(), source
.getChangeType());
}
/** Returns the subscription UUID. */
public final String getSubscriptionId() {
return subscriptionId;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public final String getTopicId() {
return topicId;
}
/** Returns the client token (an opaque string) or {@code null} for none. */
public final String getClientToken() {
return clientToken;
}
/** Returns the event type (see {@link EventTypes}). */
public final String getEventType() {
return eventType;
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version.
*/
public final String getTopicURI() {
return topicURI;
}
/** Returns the message number (a monotonically increasing value starting with 1). */
public final long getMessageNumber() {
return messageNumber;
}
/** Returns the type of change performed on the resource or {@code null} for none. */
public final String getChangeType() {
return changeType;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/Notification.java | Java | asf20 | 4,438 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
import java.io.IOException;
import java.util.Collection;
/**
* {@link Beta} <br/>
* Stores and manages registered subscriptions and their handlers.
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public interface SubscriptionStore {
/**
* Returns all known/registered subscriptions.
*/
Collection<StoredSubscription> listSubscriptions() throws IOException;
/**
* Retrieves a known subscription or {@code null} if not found.
*
* @param subscriptionId ID of the subscription to retrieve
*/
StoredSubscription getSubscription(String subscriptionId) throws IOException;
/**
* Stores the subscription in the applications data store, replacing any existing subscription
* with the same id.
*
* @param subscription New or existing {@link StoredSubscription} to store/update
*/
void storeSubscription(StoredSubscription subscription) throws IOException;
/**
* Removes a registered subscription from the store.
*
* @param subscription {@link StoredSubscription} to remove or {@code null} to ignore
*/
void removeSubscription(StoredSubscription subscription) throws IOException;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/SubscriptionStore.java | Java | asf20 | 1,903 |
/*
* 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.subscriptions;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.util.Beta;
import com.google.api.client.util.ObjectParser;
import com.google.api.client.util.Preconditions;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* {@link Beta} <br/>
* Callback which is used to receive typed {@link Notification}s after subscribing to a topic.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
class MyTypedNotificationCallback extends TypedNotificationCallback<ItemList> {
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item in notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
}
ObjectParser getParser(UnparsedNotification notification) {
return new JacksonFactory().createJsonObjectParser();
}
...
service.items.list("someID").subscribe(new MyTypedNotificationCallback()).execute()
* </pre>
*
* @param <T> Type of the data contained within a notification
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
@Beta
public abstract class TypedNotificationCallback<T> implements NotificationCallback {
/**
* Data type which this handler can parse or {@code Void.class} if no data type is expected.
*/
private Class<T> dataClass;
/**
* Returns the data type which this handler can parse or {@code Void.class} if no data type is
* expected.
*/
public final Class<T> getDataClass() {
return dataClass;
}
/**
* Sets the data type which this handler can parse or {@code Void.class} if no data type is
* expected.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public TypedNotificationCallback<T> setDataType(Class<T> dataClass) {
this.dataClass = Preconditions.checkNotNull(dataClass);
return this;
}
/**
* Handles a received push notification.
*
* @param subscription Subscription to which this notification belongs
* @param notification Typed notification which was delivered to this application
*/
protected abstract void handleNotification(
StoredSubscription subscription, TypedNotification<T> notification) throws IOException;
/**
* Returns an {@link ObjectParser} which can be used to parse this notification.
*
* @param notification Notification which should be parsable by the returned parser
*/
protected abstract ObjectParser getParser(UnparsedNotification notification) throws IOException;
/** Parses the specified content and closes the InputStream of the notification. */
private Object parseContent(ObjectParser parser, UnparsedNotification notification)
throws IOException {
// Return null if no content is expected
if (notification.getContentType() == null) {
return null;
}
// Parse the response otherwise
Charset charset = notification.getContentType() == null ? null : new HttpMediaType(
notification.getContentType()).getCharsetParameter();
return parser.parseAndClose(notification.getContent(), charset, dataClass);
}
public void handleNotification(StoredSubscription subscription, UnparsedNotification notification)
throws IOException {
ObjectParser parser = getParser(notification);
@SuppressWarnings("unchecked")
T content = (T) parseContent(parser, notification);
handleNotification(subscription, new TypedNotification<T>(notification, content));
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/TypedNotificationCallback.java | Java | asf20 | 4,593 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.Strings;
import java.io.IOException;
import java.io.InputStream;
/**
* {@link Beta} <br/>
* A notification whose content has not been parsed yet.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(Subscription subscription, UnparsedNotification notification)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(notification.getContent()));
System.out.println(reader.readLine());
reader.close();
}
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public final class UnparsedNotification extends Notification {
/** The input stream containing the content. */
private final InputStream content;
/** The content-type of the stream or {@code null} if not specified. */
private final String contentType;
/**
* Creates a {@link Notification} whose content has not yet been read and parsed.
*
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
* @param unparsedStream Unparsed content in form of a {@link InputStream}. Caller has the
* responsibility of closing the stream.
*/
public UnparsedNotification(String subscriptionId, String topicId, String topicURI,
String clientToken, long messageNumber, String eventType, String changeType,
String contentType, InputStream unparsedStream) {
super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType);
this.contentType = contentType;
this.content = Preconditions.checkNotNull(unparsedStream);
}
/**
* Returns the Content-Type of the Content of this notification.
*/
public final String getContentType() {
return contentType;
}
/**
* Returns the content stream of this notification.
*/
public final InputStream getContent() {
return content;
}
/**
* Handles a newly received notification, and delegates it to the registered handler.
*
* @param subscriptionStore subscription store
* @return {@code true} if the notification was delivered successfully, or {@code false} if this
* notification could not be delivered and the subscription should be cancelled.
* @throws IllegalArgumentException if there is a client-token mismatch
*/
public boolean deliverNotification(SubscriptionStore subscriptionStore) throws IOException {
// Find out the handler to whom this notification should go.
StoredSubscription subscription =
subscriptionStore.getSubscription(Preconditions.checkNotNull(getSubscriptionId()));
if (subscription == null) {
return false;
}
// Validate the notification.
String expectedToken = subscription.getClientToken();
Preconditions.checkArgument(
Strings.isNullOrEmpty(expectedToken) || expectedToken.equals(getClientToken()),
"Token mismatch for subscription with id=%s -- got=%s expected=%s", getSubscriptionId(),
getClientToken(), expectedToken);
// Invoke the handler associated with this subscription.
NotificationCallback h = subscription.getNotificationCallback();
h.handleNotification(subscription, this);
return true;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/UnparsedNotification.java | Java | asf20 | 4,511 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
/**
* {@link Beta} <br/>
* Headers for notifications.
*
* @author Kyle Marvin (kmarvin)
* @since 1.14
*/
@Beta
public final class NotificationHeaders {
/**
* Name of header for the client token (an opaque string) provided by the client in the subscribe
* request and returned in the subscribe response.
*/
public static final String CLIENT_TOKEN = "X-Goog-Client-Token";
/**
* Name of header for the subscription UUID provided by the client in the subscribe request and
* returned in the subscribe response.
*/
public static final String SUBSCRIPTION_ID = "X-Goog-Subscription-ID";
/**
* Name of header for the opaque ID for the subscribed resource that is stable across API versions
* returned in the subscribe response.
*/
public static final String TOPIC_ID = "X-Goog-Topic-ID";
/**
* Name of header for the opaque ID (in the form of a canonicalized URI) for the subscribed
* resource that is sensitive to the API version returned in the subscribe response.
*/
public static final String TOPIC_URI = "X-Goog-Topic-URI";
/** Name of header for the event type (see {@link EventTypes}). */
public static final String EVENT_TYPE_HEADER = "X-Goog-Event-Type";
/**
* Name of header for the type of change performed on the resource.
*/
public static final String CHANGED_HEADER = "X-Goog-Changed";
/**
* Name of header for the message number (a monotonically increasing value starting with 1).
*/
public static final String MESSAGE_NUMBER_HEADER = "X-Goog-Message-Number";
private NotificationHeaders() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/NotificationHeaders.java | Java | asf20 | 2,250 |
/*
* 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.subscriptions;
import com.google.api.client.util.Beta;
import java.io.IOException;
import java.io.Serializable;
/**
* {@link Beta} <br/>
* Callback which is used to receive {@link UnparsedNotification}s after subscribing to a topic.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Should be thread-safe as several notifications might be processed at the same time.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
class MyNotificationCallback extends NotificationCallback {
void handleNotification(
Subscription subscription, UnparsedNotification notification) {
if (notification.getEventType().equals(EventTypes.UPDATED)) {
// add items in the notification to the local client state ...
}
}
}
...
myRequest.subscribe(new MyNotificationCallback()).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public interface NotificationCallback extends Serializable {
/**
* Handles a received push notification.
*
* @param subscription Subscription to which this notification belongs
* @param notification Notification which was delivered to this application
*/
void handleNotification(StoredSubscription subscription, UnparsedNotification notification)
throws IOException;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/NotificationCallback.java | Java | asf20 | 2,185 |
/*
* 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.subscriptions;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Beta;
import com.google.api.client.util.Objects;
import com.google.api.client.util.Preconditions;
import java.io.Serializable;
import java.util.UUID;
/**
* {@link Beta} <br/>
* Client subscription information to be stored in a {@link SubscriptionStore}.
*
* <p>
* Implementation is thread safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@Beta
public final class StoredSubscription implements Serializable {
private static final long serialVersionUID = 1L;
/** Notification callback called when a notification is received for this subscription. */
private final NotificationCallback notificationCallback;
/**
* Arbitrary string provided by the client associated with this subscription that is delivered to
* the target address with each notification or {@code null} for none.
*/
private String clientToken;
/**
* HTTP date indicating the time at which the subscription will expire or {@code null} for an
* infinite TTL.
*/
private String expiration;
/** Subscription UUID. */
private final String id;
/**
* Opaque ID for the subscribed resource that is stable across API versions or {@code null} for
* none.
*/
private String topicId;
/**
* Constructor with a random UUID using {@link #randomId()}.
*
* @param notificationCallback notification handler called when a notification is received for
* this subscription
*/
public StoredSubscription(NotificationCallback notificationCallback) {
this(notificationCallback, randomId());
}
/**
* Constructor with a custom UUID.
*
* @param notificationCallback notification handler called when a notification is received for
* this subscription
* @param id subscription UUID
*/
public StoredSubscription(NotificationCallback notificationCallback, String id) {
this.notificationCallback = Preconditions.checkNotNull(notificationCallback);
this.id = Preconditions.checkNotNull(id);
}
/**
* Constructor based on a JSON-formatted subscription response information.
*
* @param notificationCallback notification handler called when a notification is received for
* this subscription
* @param subscriptionJson JSON-formatted subscription response information, where the:
* <ul>
* <li>{@code "id"} has a JSON string value for the subscription ID</li>
* <li>{@code "clientToken"} has a JSON string value for the client token (see
* {@link #setClientToken(String)})</li>
* <li>{@code "expiration"} has a JSON string value for the client token (see
* {@link #setExpiration(String)})</li>
* <li>{@code "topicId"} has a JSON string value for the client token (see
* {@link #setTopicId(String)})</li>
* </ul>
*/
public StoredSubscription(
NotificationCallback notificationCallback, GenericJson subscriptionJson) {
this(notificationCallback, (String) subscriptionJson.get("id"));
setClientToken((String) subscriptionJson.get("clientToken"));
setExpiration((String) subscriptionJson.get("expiration"));
setTopicId((String) subscriptionJson.get("topicId"));
}
/**
* Returns the notification callback called when a notification is received for this subscription.
*/
public synchronized NotificationCallback getNotificationCallback() {
return notificationCallback;
}
/**
* Returns the arbitrary string provided by the client associated with this subscription that is
* delivered to the target address with each notification or {@code null} for none.
*/
public synchronized String getClientToken() {
return clientToken;
}
/**
* Sets the the arbitrary string provided by the client associated with this subscription that is
* delivered to the target address with each notification or {@code null} for none.
*/
public synchronized StoredSubscription setClientToken(String clientToken) {
this.clientToken = clientToken;
return this;
}
/**
* Returns the HTTP date indicating the time at which the subscription will expire or {@code null}
* for an infinite TTL.
*/
public synchronized String getExpiration() {
return expiration;
}
/**
* Sets the HTTP date indicating the time at which the subscription will expire or {@code null}
* for an infinite TTL.
*/
public synchronized StoredSubscription setExpiration(String expiration) {
this.expiration = expiration;
return this;
}
/** Returns the subscription UUID. */
public synchronized String getId() {
return id;
}
/**
* Returns the opaque ID for the subscribed resource that is stable across API versions or
* {@code null} for none.
*/
public synchronized String getTopicId() {
return topicId;
}
/**
* Sets the opaque ID for the subscribed resource that is stable across API versions or
* {@code null} for none.
*/
public synchronized StoredSubscription setTopicId(String topicId) {
this.topicId = topicId;
return this;
}
@Override
public String toString() {
return Objects.toStringHelper(StoredSubscription.class)
.add("notificationCallback", getNotificationCallback()).add("clientToken", getClientToken())
.add("expiration", getExpiration()).add("id", getId()).add("topicId", getTopicId())
.toString();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof StoredSubscription)) {
return false;
}
StoredSubscription o = (StoredSubscription) other;
return getId().equals(o.getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
/** Returns a new random UUID to be used as a subscription ID. */
public static String randomId() {
return UUID.randomUUID().toString();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/StoredSubscription.java | Java | asf20 | 6,599 |
/*
* 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.util.ArrayMap;
import com.google.api.client.util.Beta;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.Data;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Types;
import java.util.Collection;
import java.util.Map;
import java.util.TreeSet;
/**
* {@link Beta} <br/>
* Utilities for working with the Atom XML of Google Data APIs.
*
* @since 1.0
* @author Yaniv Inbar
*/
@Beta
public class GoogleAtom {
/**
* GData namespace.
*
* @since 1.0
*/
public static final String GD_NAMESPACE = "http://schemas.google.com/g/2005";
/**
* Content type used on an error formatted in XML.
*
* @since 1.5
*/
public static final String ERROR_CONTENT_TYPE = "application/vnd.google.gdata.error+xml";
// TODO(yanivi): require XmlNamespaceDictory and include xmlns declarations since there is no
// guarantee that there is a match between Google's mapping and the one used by client
/**
* Returns the fields mask to use for the given data class of key/value pairs. It cannot be a
* {@link Map}, {@link GenericData} or a {@link Collection}.
*
* @param dataClass data class of key/value pairs
*/
public static String getFieldsFor(Class<?> dataClass) {
StringBuilder fieldsBuf = new StringBuilder();
appendFieldsFor(fieldsBuf, dataClass, new int[1]);
return fieldsBuf.toString();
}
/**
* Returns the fields mask to use for the given data class of key/value pairs for the feed class
* and for the entry class. This should only be used if the feed class does not contain the entry
* class as a field. The data classes cannot be a {@link Map}, {@link GenericData} or a
* {@link Collection}.
*
* @param feedClass feed data class
* @param entryClass entry data class
*/
public static String getFeedFields(Class<?> feedClass, Class<?> entryClass) {
StringBuilder fieldsBuf = new StringBuilder();
appendFeedFields(fieldsBuf, feedClass, entryClass);
return fieldsBuf.toString();
}
private static void appendFieldsFor(
StringBuilder fieldsBuf, Class<?> dataClass, int[] numFields) {
if (Map.class.isAssignableFrom(dataClass) || Collection.class.isAssignableFrom(dataClass)) {
throw new IllegalArgumentException(
"cannot specify field mask for a Map or Collection class: " + dataClass);
}
ClassInfo classInfo = ClassInfo.of(dataClass);
for (String name : new TreeSet<String>(classInfo.getNames())) {
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo.isFinal()) {
continue;
}
if (++numFields[0] != 1) {
fieldsBuf.append(',');
}
fieldsBuf.append(name);
// TODO(yanivi): handle Java arrays?
Class<?> fieldClass = fieldInfo.getType();
if (Collection.class.isAssignableFrom(fieldClass)) {
// TODO(yanivi): handle Java collection of Java collection or Java map?
fieldClass = (Class<?>) Types.getIterableParameter(fieldInfo.getField().getGenericType());
}
// TODO(yanivi): implement support for map when server implements support for *:*
if (fieldClass != null) {
if (fieldInfo.isPrimitive()) {
if (name.charAt(0) != '@' && !name.equals("text()")) {
// TODO(yanivi): wait for bug fix from server to support text() -- already fixed???
// buf.append("/text()");
}
} else if (!Collection.class.isAssignableFrom(fieldClass)
&& !Map.class.isAssignableFrom(fieldClass)) {
int[] subNumFields = new int[1];
int openParenIndex = fieldsBuf.length();
fieldsBuf.append('(');
// TODO(yanivi): abort if found cycle to avoid infinite loop
appendFieldsFor(fieldsBuf, fieldClass, subNumFields);
updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, subNumFields[0]);
}
}
}
}
private static void appendFeedFields(
StringBuilder fieldsBuf, Class<?> feedClass, Class<?> entryClass) {
int[] numFields = new int[1];
appendFieldsFor(fieldsBuf, feedClass, numFields);
if (numFields[0] != 0) {
fieldsBuf.append(",");
}
fieldsBuf.append("entry(");
int openParenIndex = fieldsBuf.length() - 1;
numFields[0] = 0;
appendFieldsFor(fieldsBuf, entryClass, numFields);
updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, numFields[0]);
}
private static void updateFieldsBasedOnNumFields(
StringBuilder fieldsBuf, int openParenIndex, int numFields) {
switch (numFields) {
case 0:
fieldsBuf.deleteCharAt(openParenIndex);
break;
case 1:
fieldsBuf.setCharAt(openParenIndex, '/');
break;
default:
fieldsBuf.append(')');
}
}
/**
* Compute the patch object of key/value pairs from the given original and patched objects, adding
* a {@code @gd:fields} key for the fields mask.
*
* @param patched patched object
* @param original original object
* @return patch object of key/value pairs
*/
public static Map<String, Object> computePatch(Object patched, Object original) {
FieldsMask fieldsMask = new FieldsMask();
ArrayMap<String, Object> result = computePatchInternal(fieldsMask, patched, original);
if (fieldsMask.numDifferences != 0) {
result.put("@gd:fields", fieldsMask.buf.toString());
}
return result;
}
private static ArrayMap<String, Object> computePatchInternal(
FieldsMask fieldsMask, Object patchedObject, Object originalObject) {
ArrayMap<String, Object> result = ArrayMap.create();
Map<String, Object> patchedMap = Data.mapOf(patchedObject);
Map<String, Object> originalMap = Data.mapOf(originalObject);
TreeSet<String> fieldNames = new TreeSet<String>();
fieldNames.addAll(patchedMap.keySet());
fieldNames.addAll(originalMap.keySet());
for (String name : fieldNames) {
Object originalValue = originalMap.get(name);
Object patchedValue = patchedMap.get(name);
if (originalValue == patchedValue) {
continue;
}
Class<?> type = originalValue == null ? patchedValue.getClass() : originalValue.getClass();
if (Data.isPrimitive(type)) {
if (originalValue != null && originalValue.equals(patchedValue)) {
continue;
}
fieldsMask.append(name);
// TODO(yanivi): wait for bug fix from server
// if (!name.equals("text()") && name.charAt(0) != '@') {
// fieldsMask.buf.append("/text()");
// }
if (patchedValue != null) {
result.add(name, patchedValue);
}
} else if (Collection.class.isAssignableFrom(type)) {
if (originalValue != null && patchedValue != null) {
@SuppressWarnings("unchecked")
Collection<Object> originalCollection = (Collection<Object>) originalValue;
@SuppressWarnings("unchecked")
Collection<Object> patchedCollection = (Collection<Object>) patchedValue;
int size = originalCollection.size();
if (size == patchedCollection.size()) {
int i;
for (i = 0; i < size; i++) {
FieldsMask subFieldsMask = new FieldsMask();
computePatchInternal(subFieldsMask, patchedValue, originalValue);
if (subFieldsMask.numDifferences != 0) {
break;
}
}
if (i == size) {
continue;
}
}
}
// TODO(yanivi): implement
throw new UnsupportedOperationException(
"not yet implemented: support for patching collections");
} else {
if (originalValue == null) { // TODO(yanivi): test
fieldsMask.append(name);
result.add(name, Data.mapOf(patchedValue));
} else if (patchedValue == null) { // TODO(yanivi): test
fieldsMask.append(name);
} else {
FieldsMask subFieldsMask = new FieldsMask();
ArrayMap<String, Object> patch =
computePatchInternal(subFieldsMask, patchedValue, originalValue);
int numDifferences = subFieldsMask.numDifferences;
if (numDifferences != 0) {
fieldsMask.append(name, subFieldsMask);
result.add(name, patch);
}
}
}
}
return result;
}
static class FieldsMask {
int numDifferences;
StringBuilder buf = new StringBuilder();
void append(String name) {
StringBuilder buf = this.buf;
if (++numDifferences != 1) {
buf.append(',');
}
buf.append(name);
}
void append(String name, FieldsMask subFields) {
append(name);
StringBuilder buf = this.buf;
boolean isSingle = subFields.numDifferences == 1;
if (isSingle) {
buf.append('/');
} else {
buf.append('(');
}
buf.append(subFields.buf);
if (!isSingle) {
buf.append(')');
}
}
}
private GoogleAtom() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/GoogleAtom.java | Java | asf20 | 9,737 |
/*
* 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><a></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>
<?xml version='1.0' encoding='utf-8'?>
<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'>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://picasaweb.google.com/data/feed/api/user/liz' />
<author>
<name>Liz</name>
</author>
<openSearch:totalResults>1</openSearch:totalResults>
<entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/photos/2007#album' />
<title>lolcats</title>
<summary>Hilarious Felines</summary>
<gphoto:access>public</gphoto:access>
</entry>
</feed>
</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 {
@Key("@href")
public String href;
@Key("@rel")
public String rel;
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
public class Category {
@Key("@scheme")
public String scheme;
@Key("@term")
public String term;
public static Category newKind(String kind) {
Category category = new Category();
category.scheme = "http://schemas.google.com/g/2005#kind";
category.term = "http://schemas.google.com/photos/2007#" + kind;
return category;
}
}
public class AlbumEntry {
@Key
public String summary;
@Key
public String title;
@Key("gphoto:access")
public String access;
public Category category = newKind("album");
private String getEditLink() {
return Link.find(links, "edit");
}
}
public class Author {
@Key
public String name;
}
public class AlbumFeed {
@Key
public Author author;
@Key("openSearch:totalResults")
public int totalResults;
@Key("entry")
public List<AlbumEntry> photos;
@Key("link")
public List<Link> 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 {
@Key("max-results")
public Integer maxResults;
@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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/package-info.java | Java | asf20 | 10,033 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/AtomPatchRelativeToOriginalContent.java | Java | asf20 | 3,114 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/AtomPatchContent.java | Java | asf20 | 2,032 |
/*
* 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();
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java | Java | asf20 | 4,579 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaUploadErrorHandler.java | Java | asf20 | 3,652 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/package-info.java | Java | asf20 | 715 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java | Java | asf20 | 34,079 |
/*
* 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;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploaderProgressListener.java | Java | asf20 | 2,419 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaUploadExponentialBackOffPolicy.java | Java | asf20 | 2,071 |
/*
* 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;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloaderProgressListener.java | Java | asf20 | 2,017 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java | Java | asf20 | 17,309 |
/*
* 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 {
@Key public int itemsPerPage;
@Key public int startIndex;
@Key public int totalItems;
@Key public DateTime updated;
@Key public List<Video> items;
}
public class Video {
@Key public String id;
@Key public String title;
@Key public DateTime updated;
@Key public String description;
@Key public List<String> tags;
@Key public Player player;
}
public class Player {
// "default" is a Java keyword, so need to specify the JSON key manually
@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 {
@Key
public String author;
@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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/json/package-info.java | Java | asf20 | 5,973 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonRpcHttpTransport.java | Java | asf20 | 10,035 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonError.java | Java | asf20 | 6,935 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonResponseException.java | Java | asf20 | 7,242 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonErrorContainer.java | Java | asf20 | 1,473 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/package-info.java | Java | asf20 | 698 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleRefreshTokenRequest.java | Java | asf20 | 5,143 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeTokenRequest.java | Java | asf20 | 6,982 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleTokenResponse.java | Java | asf20 | 3,561 |
/*
* 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<String> 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<String> 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);
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.java | Java | asf20 | 23,022 |
/*
* 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() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleOAuthConstants.java | Java | asf20 | 1,699 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/package-info.java | Java | asf20 | 3,061 |
/*
* 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;
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeFlow.java | Java | asf20 | 16,630 |
/*
* 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();
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleIdToken.java | Java | asf20 | 6,540 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleBrowserClientRequestUrl.java | Java | asf20 | 8,221 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeRequestUrl.java | Java | asf20 | 11,167 |
/*
* 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;
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleIdTokenVerifier.java | Java | asf20 | 12,171 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleClientSecrets.java | Java | asf20 | 5,505 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/ClientLogin.java | Java | asf20 | 6,687 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/ClientLoginResponseException.java | Java | asf20 | 1,708 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/package-info.java | Java | asf20 | 977 |
/*
* 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");
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/AuthKeyValueParser.java | Java | asf20 | 5,282 |
/*
* 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() {
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java | Java | asf20 | 2,459 |
/*
* 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);
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/HttpRequestContent.java | Java | asf20 | 2,436 |
/*
* 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<Volumes, GoogleJsonErrorContainer>() {
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<Volumes, GoogleJsonErrorContainer>() {
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);
}
}
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchRequest.java | Java | asf20 | 10,601 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/json/package-info.java | Java | asf20 | 725 |
/*
* 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<Volumes>() {
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;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/json/JsonBatchCallback.java | Java | asf20 | 2,102 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/package-info.java | Java | asf20 | 715 |
/*
* 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);
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchUnparsedResponse.java | Java | asf20 | 11,828 |
/*
* 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<Volumes, GoogleJsonErrorContainer>() {
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;
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchCallback.java | Java | asf20 | 2,017 |
/*
* 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);
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/MockGoogleClient.java | Java | asf20 | 4,165 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/package-info.java | Java | asf20 | 830 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/MockGoogleJsonClientRequest.java | Java | asf20 | 2,395 |
/*
* 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);
}
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/MockGoogleJsonClient.java | Java | asf20 | 4,367 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/package-info.java | Java | asf20 | 820 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/MockGoogleClientRequest.java | Java | asf20 | 2,433 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/notifications/MockUnparsedNotificationCallback.java | Java | asf20 | 1,708 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/notifications/package-info.java | Java | asf20 | 882 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/subscriptions/package-info.java | Java | asf20 | 859 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client/src/main/java/com/google/api/client/googleapis/testing/subscriptions/MockNotificationCallback.java | Java | asf20 | 1,597 |
/* You can override this file with your own styles */ | 0912116-hsncloudnotes | google-api-client-assembly/dependencies/css/site.css | CSS | asf20 | 53 |
#banner, #footer, #leftcol, #breadcrumbs, .docs #toc, .docs .courtesylinks, #leftColumn, #navColumn {
display: none !important;
}
#bodyColumn, body.docs div.docs {
margin: 0 !important;
border: none !important
}
| 0912116-hsncloudnotes | google-api-client-assembly/dependencies/css/print.css | CSS | asf20 | 222 |
body {
padding: 0px 0px 10px 0px;
}
body, td, select, input, li{
font-family: Verdana, Helvetica, Arial, sans-serif;
font-size: 13px;
}
code{
font-family: Courier, monospace;
font-size: 13px;
}
a {
text-decoration: none;
}
a:link {
color:#36a;
}
a:visited {
color:#47a;
}
a:active, a:hover {
color:#69c;
}
#legend li.externalLink {
background: url(../images/external.png) left top no-repeat;
padding-left: 18px;
}
a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover {
background: url(../images/external.png) right center no-repeat;
padding-right: 18px;
}
#legend li.newWindow {
background: url(../images/newwindow.png) left top no-repeat;
padding-left: 18px;
}
a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover {
background: url(../images/newwindow.png) right center no-repeat;
padding-right: 18px;
}
h2 {
padding: 4px 4px 4px 6px;
border: 1px solid #999;
color: #900;
background-color: #ddd;
font-weight:900;
font-size: x-large;
}
h3 {
padding: 4px 4px 4px 6px;
border: 1px solid #aaa;
color: #900;
background-color: #eee;
font-weight: normal;
font-size: large;
}
h4 {
padding: 4px 4px 4px 6px;
border: 1px solid #bbb;
color: #900;
background-color: #fff;
font-weight: normal;
font-size: large;
}
h5 {
padding: 4px 4px 4px 6px;
color: #900;
font-size: normal;
}
p {
line-height: 1.3em;
font-size: small;
}
#breadcrumbs {
border-top: 1px solid #aaa;
border-bottom: 1px solid #aaa;
background-color: #ccc;
}
#leftColumn {
margin: 10px 0 0 5px;
border: 1px solid #999;
background-color: #eee;
}
#navcolumn h5 {
font-size: smaller;
border-bottom: 1px solid #aaaaaa;
padding-top: 2px;
color: #000;
}
table.bodyTable th {
color: white;
background-color: #bbb;
text-align: left;
font-weight: bold;
}
table.bodyTable th, table.bodyTable td {
font-size: 1em;
}
table.bodyTable tr.a {
background-color: #ddd;
}
table.bodyTable tr.b {
background-color: #eee;
}
.source {
border: 1px solid #999;
}
dl {
padding: 4px 4px 4px 6px;
border: 1px solid #aaa;
background-color: #ffc;
}
dt {
color: #900;
}
#organizationLogo img, #projectLogo img, #projectLogo span{
margin: 8px;
}
#banner {
border-bottom: 1px solid #fff;
}
.errormark, .warningmark, .donemark, .infomark {
background: url(../images/icon_error_sml.gif) no-repeat;
}
.warningmark {
background-image: url(../images/icon_warning_sml.gif);
}
.donemark {
background-image: url(../images/icon_success_sml.gif);
}
.infomark {
background-image: url(../images/icon_info_sml.gif);
}
| 0912116-hsncloudnotes | google-api-client-assembly/dependencies/css/maven-theme.css | CSS | asf20 | 2,801 |
body {
margin: 0px;
padding: 0px;
}
img {
border:none;
}
table {
padding:0px;
width: 100%;
margin-left: -2px;
margin-right: -2px;
}
acronym {
cursor: help;
border-bottom: 1px dotted #feb;
}
table.bodyTable th, table.bodyTable td {
padding: 2px 4px 2px 4px;
vertical-align: top;
}
div.clear{
clear:both;
visibility: hidden;
}
div.clear hr{
display: none;
}
#bannerLeft, #bannerRight {
font-size: xx-large;
font-weight: bold;
}
#bannerLeft img, #bannerRight img {
margin: 0px;
}
.xleft, #bannerLeft img {
float:left;
}
.xright, #bannerRight {
float:right;
}
#banner {
padding: 0px;
}
#banner img {
border: none;
}
#breadcrumbs {
padding: 3px 10px 3px 10px;
}
#leftColumn {
width: 170px;
float:left;
overflow: auto;
}
#bodyColumn {
margin-right: 1.5em;
margin-left: 197px;
}
#legend {
padding: 8px 0 8px 0;
}
#navcolumn {
padding: 8px 4px 0 8px;
}
#navcolumn h5 {
margin: 0;
padding: 0;
font-size: small;
}
#navcolumn ul {
margin: 0;
padding: 0;
font-size: small;
}
#navcolumn li {
list-style-type: none;
background-image: none;
background-repeat: no-repeat;
background-position: 0 0.4em;
padding-left: 16px;
list-style-position: outside;
line-height: 1.2em;
font-size: smaller;
}
#navcolumn li.expanded {
background-image: url(../images/expanded.gif);
}
#navcolumn li.collapsed {
background-image: url(../images/collapsed.gif);
}
#poweredBy {
text-align: center;
}
#navcolumn img {
margin-top: 10px;
margin-bottom: 3px;
}
#poweredBy img {
display:block;
margin: 20px 0 20px 17px;
}
#search img {
margin: 0px;
display: block;
}
#search #q, #search #btnG {
border: 1px solid #999;
margin-bottom:10px;
}
#search form {
margin: 0px;
}
#lastPublished {
font-size: x-small;
}
.navSection {
margin-bottom: 2px;
padding: 8px;
}
.navSectionHead {
font-weight: bold;
font-size: x-small;
}
.section {
padding: 4px;
}
#footer {
padding: 3px 10px 3px 10px;
font-size: x-small;
}
#breadcrumbs {
font-size: x-small;
margin: 0pt;
}
.source {
padding: 12px;
margin: 1em 7px 1em 7px;
}
.source pre {
margin: 0px;
padding: 0px;
}
#navcolumn img.imageLink, .imageLink {
padding-left: 0px;
padding-bottom: 0px;
padding-top: 0px;
padding-right: 2px;
border: 0px;
margin: 0px;
}
| 0912116-hsncloudnotes | google-api-client-assembly/dependencies/css/maven-base.css | CSS | asf20 | 2,462 |
<html>
<title>${project.name} ${project.version}</title>
<body>
<h2>${project.name} ${project.version}</h2>
<h3>Overview</h3>
<p>
High-level details about this library can be found at <a
href="http://code.google.com/p/google-api-java-client">http://code.google.com/p/google-api-java-client</a>
</p>
<ul>
<li><a
href='http://code.google.com/p/google-api-java-client/wiki/ReleaseNotes#Version_${project.version}'>Release
Notes</a></li>
<li><a
href='http://javadoc.google-api-java-client.googlecode.com/hg/${project.version}/index.html'>JavaDoc</a></li>
<li><a
href='http://code.google.com/p/google-api-java-client/wiki/DeveloperGuide'>Developer's
Guide</a></li>
<li><a href='http://groups.google.com/group/google-api-java-client'>Support</a></li>
</ul>
<h3>Dependencies and Licenses</h3>
The license can be found
<a href='LICENSE.txt'>here</a>.
<br /> Dependent jars can be found in the
<a href='libs'>libs</a> folder and the corresponding source jars can be found
in the
<a href='libs-sources'>libs-sources</a> folder.
<br />
<br /> The dependency structure and licenses for the different libraries can
be found here:
<ul>
<li>google-api-client: <a href='dependencies/google-api-client-dependencies.html'>google-api-client-dependencies.html</a></li>
<li>google-api-client-android: <a
href='dependencies/google-api-client-android-dependencies.html'>google-api-client-android-dependencies.html</a></li>
<li>google-api-client-appengine: <a
href='dependencies/google-api-client-appengine-dependencies.html'>google-api-client-appengine-dependencies.html</a></li>
<li>google-api-client-servlet: <a
href='dependencies/google-api-client-servlet-dependencies.html'>google-api-client-servlet-dependencies.html</a></li>
<li>google-api-client-java6: <a
href='dependencies/google-api-client-java6-dependencies.html'>google-api-client-java6-dependencies.html</a></li>
<li>google-oauth-client: <a href='dependencies/google-oauth-client-dependencies.html'>google-oauth-client-dependencies.html</a></li>
<li>google-oauth-client-appengine: <a
href='dependencies/google-oauth-client-appengine-dependencies.html'>google-oauth-client-appengine-dependencies.html</a></li>
<li>google-oauth-client-servlet: <a
href='dependencies/google-oauth-client-servlet-dependencies.html'>google-oauth-client-servlet-dependencies.html</a></li>
<li>google-oauth-client-java6: <a
href='dependencies/google-oauth-client-java6-dependencies.html'>google-oauth-client-java6-dependencies.html</a></li>
<li>google-oauth-client-java7: <a
href='dependencies/google-oauth-client-java7-dependencies.html'>google-oauth-client-java7-dependencies.html</a></li>
<li>google-oauth-client-jetty: <a
href='dependencies/google-oauth-client-jetty-dependencies.html'>google-oauth-client-jetty-dependencies.html</a></li>
<li>google-http-client: <a href='dependencies/google-http-client-dependencies.html'>google-http-client-dependencies.html</a></li>
<li>google-http-client-android: <a
href='dependencies/google-http-client-android-dependencies.html'>google-http-client-android-dependencies.html</a></li>
<li>google-http-client-appengine: <a
href='dependencies/google-http-client-appengine-dependencies.html'>google-http-client-appengine-dependencies.html</a></li>
<li>google-http-client-protobuf: <a
href='dependencies/google-http-client-protobuf-dependencies.html'>google-http-client-protobuf-dependencies.html</a></li>
<li>google-http-client-gson: <a
href='dependencies/google-http-client-gson-dependencies.html'>google-http-client-gson-dependencies.html</a></li>
<li>google-http-client-jackson: <a
href='dependencies/google-http-client-jackson-dependencies.html'>google-http-client-jackson-dependencies.html</a></li>
<li>google-http-client-jackson2: <a
href='dependencies/google-http-client-jackson2-dependencies.html'>google-http-client-jackson2-dependencies.html</a></li>
</ul>
<h3>Maven Usage</h3>
For information on how to add these libraries to your Maven project please see
<a href='http://code.google.com/p/google-api-java-client/wiki/Setup#Maven'>http://code.google.com/p/google-api-java-client/wiki/Setup#Maven</a>.
<h3>Eclipse</h3>
A .classpath file snippet that can be included in your project's .classpath
has been provided
<a href='.classpath'>here</a>. Please only use the classpathentry's you
actually need (see below for details).
<h3>ProGuard</h3>
<p>
A ProGuard configuration file <a href="proguard-google-api-client.txt">proguard-google-api-client.txt</a>
is included for common settings for using the library. On Android projects,
you may want to add a reference to
<code>proguard-google-api-client.txt</code>
in the
<code>project.properties</code>
file under the
<code>proguard.config</code>
property.
</p>
<p>
Please read <a
href="http://code.google.com/p/google-http-java-client/wiki/Setup#ProGuard">Setup
ProGuard</a> for more details.
</p>
<h3>Dependencies for all Platforms</h3>
The following are the jars from the
<a href='libs'>libs</a> folder needed for applications on all platform:
<ul>
<li>google-api-client-${project.version}.jar</li>
<li>google-oauth-client-${project.oauth.version}.jar</li>
<li>google-http-client-${project.http.version}.jar</li>
<li>jsr305-${project.jsr305.version}.jar</li>
<li>google-api-client-protobuf-${project.api.version}.jar (when using
protobuf-java)
<ul>
<li>google-http-client-protobuf-${project.http.version}.jar</li>
<li>protobuf-java-${project.protobuf-java.version}.jar</li>
</ul>
</li>
<li>google-api-client-gson-${project.api.version}.jar (when using
GSON)
<ul>
<li>google-http-client-gson-${project.http.version}.jar</li>
<li>gson-${project.gson.version}.jar</li>
</ul>
</li>
<li>google-api-client-jackson2-${project.api.version}.jar (when using
Jackson 2)
<ul>
<li>google-http-client-jackson2-${project.http.version}.jar</li>
<li>jackson-core-${project.jackson-core2.version}.jar</li>
</ul>
</li>
<li>google-http-client-jackson-${project.http.version}.jar (when using
Jackson 1)
<ul>
<li>jackson-core-asl-${project.jackson-core-asl.version}.jar</li>
</ul>
</li>
</ul>
<h3>Android Dependencies</h3>
The following are the jars from the
<a href='libs'>libs</a> folder required for Android applications:
<ul>
<li>google-api-client-android-${project.version}.jar (for SDK >= 2.1)</li>
<li>google-http-client-android-${project.http.version}.jar</li>
</ul>
The
<a href='libs'>libs</a> folder also contains properties files that specify the
location of source jars for Android projects in Eclipse.
<br /> Please see the
<a href='http://code.google.com/p/google-api-java-client/wiki/Android'>Android
wiki</a> for the Android Developer's Guide.
<h3>Google App Engine Dependencies</h3>
The following are the jars from the
<a href='libs'>libs</a> folder required for Google App Engine applications or
a newer compatible version:
<ul>
<li>google-api-client-appengine-${project.version}.jar</li>
<li>google-api-client-servlet-${project.version}.jar</li>
<li>google-oauth-client-appengine-${project.oauth.version}.jar</li>
<li>google-oauth-client-servlet-${project.oauth.version}.jar</li>
<li>google-http-client-appengine-${project.http.version}.jar</li>
<li>jdo2-api-${project.jdo2-api.version}.jar</li>
<li>transaction-api-${project.transaction-api.version}.jar</li>
<li>xpp3-${project.xpp3.version}.jar</li>
</ul>
Please see the
<a href='http://code.google.com/p/google-api-java-client/wiki/GoogleAppEngine'>GoogleAppEngine
wiki</a> for the Google App Engine Developer's Guide.
<h3>Servlet Dependencies</h3>
The following are the jars from the
<a href='libs'>libs</a> folder required for Servlet applications or a newer
compatible version:
<ul>
<li>google-api-client-servlet-${project.version}.jar</li>
<li>google-oauth-client-servlet-${project.oauth.version}.jar</li>
<li>commons-logging-${project.commons-logging.version}.jar</li>
<li>httpclient-${project.httpclient.version}.jar</li>
<li>httpcore-${project.httpcore.version}.jar</li>
<li>jdo2-api-${project.jdo2-api.version}.jar</li>
<li>transaction-api-${project.transaction-api.version}.jar</li>
<li>xpp3-${project.xpp3.version}.jar</li>
</ul>
<h3>General Purpose Java 5 Environment Dependencies</h3>
The following are the jars from the
<a href='libs'>libs</a> folder required for general purpose Java 5
applications or a newer compatible version:
<ul>
<li>google-api-client-java6-${project.version}.jar</li>
<li>google-oauth-client-java6-${project.oauth.version}.jar (for JDK >=
6)
<ul>
<li>google-oauth-client-jetty-${project.oauth.version}.jar (for
Jetty 6)
<ul>
<li>jetty-${project.jetty.version}.jar</li>
<li>jetty-util-${project.jetty.version}.jar</li>
</ul>
</li>
</ul>
</li>
<li>google-oauth-client-java7-${project.version}.jar (for JDK >= 7)</li>
<li>commons-logging-${project.commons-logging.version}.jar</li>
<li>httpclient-${project.httpclient.version}.jar</li>
<li>httpcore-${project.httpcore.version}.jar</li>
<li>xpp3-${project.xpp3.version}.jar</li>
</ul>
</body>
</html>
| 0912116-hsncloudnotes | google-api-client-assembly/readme.html | HTML | asf20 | 9,638 |
/*
* 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);
}
}
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/accounts/GoogleAccountManager.java | Java | asf20 | 2,720 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/accounts/package-info.java | Java | asf20 | 884 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAuthIOException.java | Java | asf20 | 1,467 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/package-info.java | Java | asf20 | 876 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GooglePlayServicesAvailabilityIOException.java | Java | asf20 | 2,359 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/UserRecoverableAuthIOException.java | Java | asf20 | 2,014 |
/*
* 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;
}
}
}
| 0912116-hsncloudnotes | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java | Java | asf20 | 9,978 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/notifications/package-info.java | Java | asf20 | 892 |
/*
* 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());
}
}
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/notifications/AppEngineNotificationServlet.java | Java | asf20 | 2,890 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/package-info.java | Java | asf20 | 893 |
/*
* 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;
}
}
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/CachedAppEngineSubscriptionStore.java | Java | asf20 | 2,784 |
/*
* 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;
}
}
}
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/AppEngineSubscriptionStore.java | Java | asf20 | 5,129 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/auth/oauth2/package-info.java | Java | asf20 | 777 |
/*
* 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;
}
}
}
| 0912116-hsncloudnotes | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/auth/oauth2/AppIdentityCredential.java | Java | asf20 | 7,467 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-gson/src/main/java/com/google/api/client/googleapis/notifications/json/gson/package-info.java | Java | asf20 | 908 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client-gson/src/main/java/com/google/api/client/googleapis/notifications/json/gson/GsonNotificationCallback.java | Java | asf20 | 2,465 |
/*
* 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;
| 0912116-hsncloudnotes | google-api-client-jackson2/src/main/java/com/google/api/client/googleapis/notifications/json/jackson2/package-info.java | Java | asf20 | 922 |
/*
* 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();
}
}
| 0912116-hsncloudnotes | google-api-client-jackson2/src/main/java/com/google/api/client/googleapis/notifications/json/jackson2/JacksonNotificationCallback.java | Java | asf20 | 2,485 |
<html>
<title>Setup Instructions for the Google API Client Library for Java</title>
<body>
<h2>Setup Instructions for the Google API Client Library for Java</h2>
<h3>Browse Online</h3>
<ul>
<li><a
href="http://code.google.com/p/google-api-java-client/source/browse/">Browse
Source</a></li>
</ul>
<h3>Checkout Instructions</h3>
<p><b>Prerequisites:</b> install <a href="http://java.com">Java 6</a>, <a
href="http://mercurial.selenic.com/">Mercurial</a> and <a
href="http://maven.apache.org/download.html">Maven</a>. You may need to set
your <code>JAVA_HOME</code>.</p>
<pre><code>hg clone https://google-api-java-client.googlecode.com/hg/ google-api-java-client
cd google-api-java-client
mvn install</code></pre>
There are two named branches:
<ul>
<li>The "default" branch has the stable 1.4 library. This is the default
branch that is checked out with the instructions above.</li>
<li>The "dev" branch has the development 1.5 library. To switch to this
branch, run: <pre><code>hg update dev
mvn clean install</code></pre></li>
</ul>
<h3>Setup Project in Eclipse 3.5</h3>
<p><b>Prerequisites:</b> install <a href="http://www.eclipse.org/downloads/">Eclipse</a>,
the <a href="http://javaforge.com/project/HGE">Mercurial plugin</a>, the <a
href="http://m2eclipse.sonatype.org/installing-m2eclipse.html">Maven
plugin</a>, and the <a
href="http://developer.android.com/sdk/eclipse-adt.html#installing">Android
plugin</a>.</p>
<ul>
<li>Setup Eclipse Preferences
<ul>
<li>Window > Preferences... (or on Mac, Eclipse > Preferences...)</li>
<li>Select Maven
<ul>
<li>check on "Download Artifact Sources"</li>
<li>check on "Download Artifact JavaDoc"</li>
</ul>
</li>
<li>Select Android
<ul>
<li>setup SDK location</li>
</ul>
</li>
</ul>
</li>
<li>Import projects
<ul>
<li>File > Import...</li>
<li>Select "General > Existing Project into Workspace" and click
"Next"</li>
<li>Click "Browse" next to "Select root directory", find <code><i>[someDirectory]</i>/google-api-java-client</code>
and click OK</li>
<li>Click "Next" and "Finish"</li>
</ul>
</li>
</ul>
</body>
</html>
| 0912116-hsncloudnotes | instructions.html | HTML | asf20 | 2,205 |