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 |
|---|---|---|---|---|---|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.googleapis.subscriptions.NotificationCallback;
import com.google.api.client.googleapis.subscriptions.SubscribeRequest;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.JsonFactory;
import com.google.common.base.Preconditions;
import java.io.IOException;
/**
* Subscribe JSON request.
*
* @author Yaniv Inbar
* @since 1.14
*/
public class JsonSubscribeRequest extends SubscribeRequest {
/** JSON factory. */
private final JsonFactory jsonFactory;
/**
* @param request HTTP GET request
* @param notificationDeliveryMethod notification delivery method
* @param jsonFactory JSON factory
*/
public JsonSubscribeRequest(
HttpRequest request, String notificationDeliveryMethod, JsonFactory jsonFactory) {
super(request, notificationDeliveryMethod);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
}
@Override
public JsonSubscribeRequest withNotificationCallback(
SubscriptionStore subscriptionStore, NotificationCallback notificationCallback) {
return (JsonSubscribeRequest) super.withNotificationCallback(
subscriptionStore, notificationCallback);
}
@Override
public <N> JsonSubscribeRequest withTypedNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, TypedNotificationCallback<N> typedNotificationCallback) {
return (JsonSubscribeRequest) super.withTypedNotificationCallback(
subscriptionStore, notificationCallbackClass, typedNotificationCallback);
}
@Override
public JsonSubscribeRequest setNotificationDeliveryMethod(String notificationDeliveryMethod) {
return (JsonSubscribeRequest) super.setNotificationDeliveryMethod(notificationDeliveryMethod);
}
@Override
public JsonSubscribeRequest setClientToken(String clientToken) {
return (JsonSubscribeRequest) super.setClientToken(clientToken);
}
@Override
public JsonSubscribeRequest setSubscriptionId(String subscriptionId) {
return (JsonSubscribeRequest) super.setSubscriptionId(subscriptionId);
}
/**
* Sets the subscription store and JSON notification callback associated with this subscription.
*
* @param subscriptionStore subscription store
* @param notificationCallbackClass data class the successful notification will be parsed into or
* {@code Void.class} to ignore the content
* @param jsonNotificationCallback JSON notification callback
*/
public <N> JsonSubscribeRequest withJsonNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, JsonNotificationCallback<N> jsonNotificationCallback) {
return withTypedNotificationCallback(
subscriptionStore, notificationCallbackClass, jsonNotificationCallback);
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Queues the subscribe JSON request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* <p>
* Example usage:
* </p>
*
* <pre>
request.queue(batchRequest, new JsonBatchCallback<Void>() {
public void onSuccess(Void ignored, HttpHeaders responseHeaders) {
log("Success");
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
log(e.getMessage());
}
});
* </pre>
*
*
* @param batchRequest batch request container
* @param callback batch callback
*/
public final void queue(BatchRequest batchRequest, JsonBatchCallback<Void> callback)
throws IOException {
super.queue(batchRequest, GoogleJsonErrorContainer.class, callback);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/json/JsonSubscribeRequest.java | Java | asf20 | 4,752 |
/*
* 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.
*/
/**
* Support for creating subscriptions and receiving notifications for Google APIs.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.subscriptions;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/package-info.java | Java | asf20 | 980 |
/*
* 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;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/EventTypes.java | Java | asf20 | 1,459 |
/*
* 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.common.base.Preconditions;
/**
* Notification sent to this client about a subscribed resource.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/Notification.java | Java | asf20 | 4,367 |
/*
* 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 java.io.IOException;
import java.util.Collection;
/**
* Stores and manages registered subscriptions and their handlers.
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public interface SubscriptionStore {
/**
* Returns all known/registered subscriptions.
*/
Collection<Subscription> listSubscriptions() throws IOException;
/**
* Retrieves a known subscription or {@code null} if not found.
*
* @param subscriptionId ID of the subscription to retrieve
*/
Subscription 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 Subscription} to store/update
*/
void storeSubscription(Subscription subscription) throws IOException;
/**
* Removes a registered subscription from the store.
*
* @param subscription {@link Subscription} to remove or {@code null} to ignore
*/
void removeSubscription(Subscription subscription) throws IOException;
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/SubscriptionStore.java | Java | asf20 | 1,798 |
/*
* 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.ObjectParser;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* 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")
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(
Subscription 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 || Void.class.equals(dataClass)) {
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(Subscription 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/TypedNotificationCallback.java | Java | asf20 | 4,541 |
/*
* 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.HttpHeaders;
/**
* Headers for subscribe request and response.
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class SubscriptionHeaders {
/**
* 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 notifications delivery method in the subscribe request.
*/
public static final String SUBSCRIBE = "X-Goog-Subscribe";
/**
* Name of header for the HTTP Date indicating the time at which the subscription will expire
* returned in the subscribe response or if not returned for an infinite TTL.
*/
public static final String SUBSCRIPTION_EXPIRES = "X-Goog-Subscription-Expires";
/**
* 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";
/**
* Returns the client token (an opaque string) provided by the client in the subscribe request and
* returned in the subscribe response or {@code null} for none.
*/
public static String getClientToken(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(CLIENT_TOKEN);
}
/**
* Sets the client token (an opaque string) provided by the client in the subscribe request and
* returned in the subscribe response or {@code null} for none.
*/
public static void setClientToken(HttpHeaders headers, String clienToken) {
headers.set(CLIENT_TOKEN, clienToken);
}
/**
* Returns the notifications delivery method in the subscribe request or {@code null} for none.
*
* @param headers HTTP headers
*/
public static String getSubscribe(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIBE);
}
/**
* Sets the notifications delivery method in the subscribe request or {@code null} for none.
*/
public static void setSubscribe(HttpHeaders headers, String subscribe) {
headers.set(SUBSCRIBE, subscribe);
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public static String getSubscriptionExpires(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIPTION_EXPIRES);
}
/**
* Sets the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public static void setSubscriptionExpires(HttpHeaders headers, String subscriptionExpires) {
headers.set(SUBSCRIPTION_EXPIRES, subscriptionExpires);
}
/**
* Returns the subscription UUID provided by the client in the subscribe request and returned in
* the subscribe response or {@code null} for none.
*/
public static String getSubscriptionId(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(SUBSCRIPTION_ID);
}
/**
* Sets the subscription UUID provided by the client in the subscribe request and returned in the
* subscribe response or {@code null} for none.
*/
public static void setSubscriptionId(HttpHeaders headers, String subscriptionId) {
headers.set(SUBSCRIPTION_ID, subscriptionId);
}
/**
* Returns the opaque ID for the subscribed resource that is stable across API versions returned
* in the subscribe response or {@code null} for none.
*/
public static String getTopicId(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(TOPIC_ID);
}
/**
* Sets the opaque ID for the subscribed resource that is stable across API versions returned in
* the subscribe response or {@code null} for none.
*/
public static void setTopicId(HttpHeaders headers, String topicId) {
headers.set(TOPIC_ID, topicId);
}
/**
* Returns 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 or {@code null} for none.
*/
public static String getTopicUri(HttpHeaders headers) {
return headers.getFirstHeaderStringValue(TOPIC_URI);
}
/**
* Sets 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 or {@code null} for none.
*/
public static void setTopicUri(HttpHeaders headers, String topicUri) {
headers.set(TOPIC_URI, topicUri);
}
private SubscriptionHeaders() {
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/SubscriptionHeaders.java | Java | asf20 | 5,803 |
/*
* 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.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.IOException;
import java.io.InputStream;
/**
* 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
*/
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.
Subscription 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/UnparsedNotification.java | Java | asf20 | 4,429 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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;
/**
* Headers for notifications.
*
* @author Kyle Marvin (kmarvin)
* @since 1.14
*/
public final class NotificationHeaders {
/** 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/NotificationHeaders.java | Java | asf20 | 1,254 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.googleapis.batch.BatchCallback;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.HttpExecuteInterceptor;
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.HttpResponse;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.UUID;
/**
* Subscribe request.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @author Yaniv Inbar
* @since 1.14
*/
public class SubscribeRequest {
/** HTTP request. */
private final HttpRequest request;
/** Notification callback or {@code null} for none. */
private NotificationCallback notificationCallback;
/** Subscription store or {@code null} for none. */
private SubscriptionStore subscriptionStore;
/** Stored subscription. */
Subscription subscription;
/**
* @param request HTTP GET request
* @param notificationDeliveryMethod notification delivery method
*/
public SubscribeRequest(HttpRequest request, String notificationDeliveryMethod) {
this.request = Preconditions.checkNotNull(request);
Preconditions.checkArgument(HttpMethods.GET.equals(request.getRequestMethod()));
request.setRequestMethod(HttpMethods.POST);
request.setContent(new EmptyContent());
setNotificationDeliveryMethod(notificationDeliveryMethod);
setSubscriptionId(UUID.randomUUID().toString());
}
/**
* Sets the subscription store and notification callback associated with this subscription.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param subscriptionStore subscription store
* @param notificationCallback notification callback
*/
public SubscribeRequest withNotificationCallback(
final SubscriptionStore subscriptionStore, final NotificationCallback notificationCallback) {
Preconditions.checkArgument(this.notificationCallback == null);
this.subscriptionStore = Preconditions.checkNotNull(subscriptionStore);
this.notificationCallback = Preconditions.checkNotNull(notificationCallback);
// execute interceptor
final HttpExecuteInterceptor executeInterceptor = request.getInterceptor();
request.setInterceptor(new HttpExecuteInterceptor() {
public void intercept(HttpRequest request) throws IOException {
if (subscription == null) {
subscription =
new Subscription(notificationCallback, getClientToken(), getSubscriptionId());
subscriptionStore.storeSubscription(subscription);
}
if (executeInterceptor != null) {
executeInterceptor.intercept(request);
}
}
});
// response interceptor
final HttpResponseInterceptor responseInterceptor = request.getResponseInterceptor();
request.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
HttpHeaders headers = response.getHeaders();
Preconditions.checkArgument(
SubscriptionHeaders.getSubscriptionId(headers).equals(getSubscriptionId()));
if (response.isSuccessStatusCode()) {
subscription.processResponse(SubscriptionHeaders.getSubscriptionExpires(headers),
SubscriptionHeaders.getTopicId(headers));
subscriptionStore.storeSubscription(subscription);
} else {
subscriptionStore.removeSubscription(subscription);
}
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response);
}
}
});
return this;
}
/**
* Sets the subscription store and typed notification callback associated with this subscription.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*
* @param subscriptionStore subscription store
* @param notificationCallbackClass data class the successful notification will be parsed into or
* {@code Void.class} to ignore the content
* @param typedNotificationCallback typed notification callback
*/
public <N> SubscribeRequest withTypedNotificationCallback(SubscriptionStore subscriptionStore,
Class<N> notificationCallbackClass, TypedNotificationCallback<N> typedNotificationCallback) {
withNotificationCallback(subscriptionStore, typedNotificationCallback);
typedNotificationCallback.setDataType(notificationCallbackClass);
return this;
}
/** Returns the subscribe HTTP request. */
public final HttpRequest getRequest() {
return request;
}
/** Returns the notifications delivery method. */
public final String getNotificationDeliveryMethod() {
return SubscriptionHeaders.getSubscribe(request.getHeaders());
}
/**
* Sets the notifications delivery method.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public SubscribeRequest setNotificationDeliveryMethod(String notificationDeliveryMethod) {
SubscriptionHeaders.setSubscribe(
request.getHeaders(), Preconditions.checkNotNull(notificationDeliveryMethod));
return this;
}
/** Returns the notification callback or {@code null} for none. */
public final NotificationCallback getNotificationCallback() {
return notificationCallback;
}
/** Returns the subscription store or {@code null} for none. */
public final SubscriptionStore getSubscriptionStore() {
return subscriptionStore;
}
/**
* Returns the client token (an opaque string) provided by the client or {@code null} for none.
*/
public String getClientToken() {
return SubscriptionHeaders.getClientToken(request.getHeaders());
}
/**
* Sets the client token (an opaque string) provided by the client 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 SubscribeRequest setClientToken(String clientToken) {
SubscriptionHeaders.setClientToken(request.getHeaders(), clientToken);
return this;
}
/** Returns the subscription UUID provided by the client. */
public String getSubscriptionId() {
return SubscriptionHeaders.getSubscriptionId(request.getHeaders());
}
/**
* Sets the subscription UUID provided by the client.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public SubscribeRequest setSubscriptionId(String subscriptionId) {
SubscriptionHeaders.setSubscriptionId(
request.getHeaders(), Preconditions.checkNotNull(subscriptionId));
return this;
}
/**
* Executes the subscribe request.
*
* @return subscribe response
*/
public SubscribeResponse execute() throws IOException {
HttpResponse response = request.execute();
return new SubscribeResponse(response, subscription);
}
/**
* Queues the subscribe request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* @param batchRequest batch request container
* @param errorClass data class the unsuccessful response will be parsed into or
* {@code Void.class} to ignore the content
* @param callback batch callback
*/
public final <E> void queue(
BatchRequest batchRequest, Class<E> errorClass, BatchCallback<Void, E> callback)
throws IOException {
batchRequest.queue(request, Void.class, errorClass, callback);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/SubscribeRequest.java | Java | asf20 | 8,666 |
/*
* 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 java.io.IOException;
import java.io.Serializable;
/**
* 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
*/
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(Subscription subscription, UnparsedNotification notification)
throws IOException;
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/NotificationCallback.java | Java | asf20 | 2,110 |
/*
* 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.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.Serializable;
/**
* Client subscription information after the subscription has been created.
*
* <p>
* Should be stored in a {@link SubscriptionStore}. Implementation is thread safe.
* </p>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class Subscription implements Serializable {
private static final long serialVersionUID = 1L;
/** Notification callback called when a notification is received for this subscription. */
private final NotificationCallback notificationCallback;
/**
* Opaque string provided by the client or {@code null} for none.
*/
private final String clientToken;
/**
* HTTP Date indicating the time at which the subscription will expire or {@code null} for an
* infinite TTL.
*/
private String subscriptionExpires;
/** Subscription UUID. */
private final String subscriptionId;
/** Opaque ID for the subscribed resource that is stable across API versions. */
private String topicId;
/**
* Constructor to be called before making the subscribe request.
*
* @param handler notification handler called when a notification is received for this
* subscription
* @param clientToken opaque string provided by the client or {@code null} for none
* @param subscriptionId subscription UUID
*/
public Subscription(NotificationCallback handler, String clientToken, String subscriptionId) {
this.notificationCallback = Preconditions.checkNotNull(handler);
this.clientToken = clientToken;
this.subscriptionId = Preconditions.checkNotNull(subscriptionId);
}
/**
* Process subscribe response.
*
* @param subscriptionExpires HTTP Date indicating the time at which the subscription will expire
* or {@code null} for an infinite TTL
* @param topicId opaque ID for the subscribed resource that is stable across API versions
*/
public Subscription processResponse(String subscriptionExpires, String topicId) {
this.subscriptionExpires = subscriptionExpires;
this.topicId = Preconditions.checkNotNull(topicId);
return this;
}
/**
* Returns the notification callback called when a notification is received for this subscription.
*/
public NotificationCallback getNotificationCallback() {
return notificationCallback;
}
/**
* Returns the Opaque string provided by the client or {@code null} for none.
*/
public String getClientToken() {
return clientToken;
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire or {@code null}
* for an infinite TTL.
*/
public String getSubscriptionExpires() {
return subscriptionExpires;
}
/** Returns the subscription UUID. */
public String getSubscriptionId() {
return subscriptionId;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public String getTopicId() {
return topicId;
}
@Override
public String toString() {
return Objects.toStringHelper(Subscription.class)
.add("notificationCallback", notificationCallback).add("clientToken", clientToken)
.add("subscriptionExpires", subscriptionExpires).add("subscriptionID", subscriptionId)
.add("topicID", topicId).toString();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Subscription)) {
return false;
}
Subscription o = (Subscription) other;
return subscriptionId.equals(o.subscriptionId);
}
@Override
public int hashCode() {
return subscriptionId.hashCode();
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/Subscription.java | Java | asf20 | 4,368 |
/*
* 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.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;
/**
* Utilities for working with the Atom XML of Google Data APIs.
*
* @since 1.0
* @author Yaniv Inbar
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/GoogleAtom.java | Java | asf20 | 9,669 |
/*
* 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.
*/
/**
* 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>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.xml.atom;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/package-info.java | Java | asf20 | 10,135 |
/*
* 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.xml.XmlNamespaceDictionary;
import com.google.api.client.xml.atom.Atom;
import com.google.common.base.Preconditions;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.util.Map;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/AtomPatchRelativeToOriginalContent.java | Java | asf20 | 3,042 |
/*
* 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.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/AtomPatchContent.java | Java | asf20 | 1,964 |
/*
* 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.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;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java | Java | asf20 | 4,511 |
/*
* 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.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.media;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/media/package-info.java | Java | asf20 | 903 |
/*
* 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.GenericUrl;
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.MultipartRelatedContent;
import com.google.common.base.Preconditions;
import com.google.common.io.LimitInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 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>
* 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. If value is set to {@code false}
* then server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
private boolean backOffPolicyEnabled = true;
/**
* 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;
/**
* 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:
*
* <pre>
if (!response.isSuccessStatusCode()) {
throw GoogleJsonResponseException.from(jsonFactory, response);
}
* </pre>
* </p>
*
* <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 MultipartRelatedContent(metadata, mediaContent);
initiationRequestUrl.put("uploadType", "multipart");
} else {
initiationRequestUrl.put("uploadType", "media");
}
HttpRequest request =
requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
request.getHeaders().putAll(initiationHeaders);
request.setThrowExceptionOnExecuteError(false);
request.setEnableGZipContent(!disableGZipContent);
addMethodOverride(request);
// 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 = request.execute();
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);
addMethodOverride(currentRequest); // needed for PUT
setContentAndHeadersOnCurrentRequest(bytesUploaded);
if (backOffPolicyEnabled) {
// Set MediaExponentialBackOffPolicy as the BackOffPolicy of the HTTP Request which will
// callback to this instance if there is a server error.
currentRequest.setBackOffPolicy(new MediaUploadExponentialBackOffPolicy(this));
}
currentRequest.setThrowExceptionOnExecuteError(false);
currentRequest.setRetryOnExecuteIOException(true);
currentRequest.setEnableGZipContent(!disableGZipContent);
response = currentRequest.execute();
boolean returningResponse = false;
try {
if (response.isSuccessStatusCode()) {
bytesUploaded = getMediaContentLength();
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);
addMethodOverride(request);
initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType());
if (getMediaContentLength() >= 0) {
initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength());
}
request.getHeaders().putAll(initiationHeaders);
request.setThrowExceptionOnExecuteError(false);
request.setRetryOnExecuteIOException(true);
request.setEnableGZipContent(!disableGZipContent);
HttpResponse response = request.execute();
boolean notificationCompleted = false;
try {
updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE);
notificationCompleted = true;
} finally {
if (!notificationCompleted) {
response.disconnect();
}
}
return response;
}
/**
* Wraps PUT HTTP requests inside of a POST request and uses {@link MethodOverride#HEADER} header
* to specify the actual HTTP method. This is done in case the HTTP transport does not support
* PUT.
*
* @param request HTTP request
*/
private void addMethodOverride(HttpRequest request) throws IOException {
new MethodOverride().intercept(request);
}
/**
* 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);
// TODO(rmistry): Add tests for LimitInputStream.
InputStream limitInputStream = new LimitInputStream(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;
InputStream limitInputStream = new LimitInputStream(contentInputStream, bytesAllowedToRead);
currentRequestContentBuffer = new byte[blockSize + 1];
if (cachedByte != null) {
currentRequestContentBuffer[0] = cachedByte;
}
actualBytesRead = limitInputStream.read(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);
currentRequest.getHeaders().setContentRange("bytes " + bytesWritten + "-" +
(bytesWritten + actualBlockSize - 1) + "/" + mediaContentLengthStr);
}
/**
* The call back method that will be invoked by
* {@link MediaUploadExponentialBackOffPolicy#getNextBackOffMillis} if it encounters a server
* error. This method should only be used as a call back method after {@link #upload} is invoked.
*
* <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 used by the BackOffPolicy to contain the correct range header and media content chunk.
* </p>
*/
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 POST request on the upload URI.
HttpRequest request = requestFactory.buildPutRequest(currentRequest.getUrl(), null);
addMethodOverride(request); // needed for PUT
request.getHeaders().setContentRange("bytes */" + (
getMediaContentLength() >= 0 ? getMediaContentLength() : "*"));
request.setContent(new EmptyContent());
request.setThrowExceptionOnExecuteError(false);
request.setRetryOnExecuteIOException(true);
HttpResponse response = request.execute();
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;
}
/**
* Sets whether the back off policy is enabled or disabled. If value is set to {@code false} then
* server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public MediaHttpUploader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) {
this.backOffPolicyEnabled = backOffPolicyEnabled;
return this;
}
/**
* Returns whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the upload process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public boolean isBackOffPolicyEnabled() {
return backOffPolicyEnabled;
}
/**
* Sets 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 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>
*
* <p>
* Upgrade warning: Prior to version 1.13.0-beta {@link #setChunkSize} accepted any chunk size
* above {@link #MINIMUM_CHUNK_SIZE}, it now accepts only multiples 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>
*
* @since 1.13
*/
public MediaHttpUploader setDisableGZipContent(boolean disableGZipContent) {
this.disableGZipContent = disableGZipContent;
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.
*
* <p>
* Upgrade warning: in prior version 1.12 the initiation headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*/
public MediaHttpUploader setInitiationHeaders(HttpHeaders initiationHeaders) {
this.initiationHeaders = initiationHeaders;
return this;
}
/**
* Returns the HTTP headers used for the initiation request.
*
* <p>
* Upgrade warning: in prior version 1.12 the initiation headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpUploader.java | Java | asf20 | 31,213 |
/*
* 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-qwqwdfwedwdwq | 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 java.io.IOException;
/**
* 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)
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaUploadExponentialBackOffPolicy.java | Java | asf20 | 1,958 |
/*
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloaderProgressListener.java | Java | asf20 | 2,018 |
/*
* 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.AbstractInputStreamContent;
import com.google.api.client.http.ExponentialBackOffPolicy;
import com.google.api.client.http.GenericUrl;
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.common.base.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>
*
* @since 1.9
*
* @author rmistry@google.com (Ravi Mistry)
*/
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. If value is set to {@code false}
* then server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
private boolean backOffPolicyEnabled = true;
/**
* 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 The 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);
HttpRequest request = requestFactory.buildGetRequest(requestUrl);
if (requestHeaders != null) {
request.getHeaders().putAll(requestHeaders);
}
if (bytesDownloaded != 0) {
StringBuilder rangeHeader = new StringBuilder();
rangeHeader.append("bytes=").append(bytesDownloaded).append("-");
if (lastBytePos != -1) {
rangeHeader.append(lastBytePos);
}
request.getHeaders().setRange(rangeHeader.toString());
}
HttpResponse response = request.execute();
try {
// All required bytes have been downloaded from the server.
mediaContentLength = response.getHeaders().getContentLength();
bytesDownloaded = mediaContentLength;
updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE);
AbstractInputStreamContent.copy(response.getContent(), outputStream);
} finally {
response.disconnect();
}
return;
}
// Download the media content in chunks.
while (true) {
HttpRequest request = requestFactory.buildGetRequest(requestUrl);
if (requestHeaders != null) {
request.getHeaders().putAll(requestHeaders);
}
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);
}
request.getHeaders().setRange(
"bytes=" + bytesDownloaded + "-" + currentRequestLastBytePos);
if (backOffPolicyEnabled) {
// Set ExponentialBackOffPolicy as the BackOffPolicy of the HTTP Request which will
// retry the same request again if there is a server error.
request.setBackOffPolicy(new ExponentialBackOffPolicy());
}
HttpResponse response = request.execute();
AbstractInputStreamContent.copy(response.getContent(), 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);
}
}
/**
* 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;
}
/**
* Sets whether the back off policy is enabled or disabled. If value is set to {@code false} then
* server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
public MediaHttpDownloader setBackOffPolicyEnabled(boolean backOffPolicyEnabled) {
this.backOffPolicyEnabled = backOffPolicyEnabled;
return this;
}
/**
* Returns whether the back off policy is enabled or disabled. If value is set to {@code false}
* then server errors are not handled and the download process will fail if a server error is
* encountered. Defaults to {@code true}.
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/media/MediaHttpDownloader.java | Java | asf20 | 15,761 |
/*
* 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.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.JsonToken;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashSet;
/**
* Parses JSON-C response content into an data class of key/value pairs, assuming the data is
* wrapped in a {@code "data"} envelope.
*
* <p>
* Warning: this should only be used by some older Google APIs that wrapped the response in a
* {@code "data"} envelope. All newer Google APIs don't use this envelope, and for those APIs
* {@link JsonObjectParser} should be used instead.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
* <code>
static void setParser(HttpRequest request) {
request.setParser(new JsonCParser(new JacksonFactory()));
}
* </code>
* </pre>
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <p>
* Upgrade warning: this class now extends {@link JsonObjectParser}, whereas in prior version 1.11
* it extended {@link com.google.api.client.http.json.JsonHttpParser}.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
@SuppressWarnings("javadoc")
public final class JsonCParser extends JsonObjectParser {
private final JsonFactory jsonFactory;
/**
* Returns the JSON factory used for parsing.
*
* @since 1.10
*/
public final JsonFactory getFactory() {
return jsonFactory;
}
/**
* @param jsonFactory non-null JSON factory used for parsing
* @since 1.5
*/
public JsonCParser(JsonFactory jsonFactory) {
super(jsonFactory);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
}
/**
* Initializes a JSON parser to use for parsing by skipping over the {@code "data"} or
* {@code "error"} envelope.
*
* <p>
* The parser will be closed if any throwable is thrown. The current token will be the value of
* the {@code "data"} or {@code "error} key.
* </p>
*
* @param parser the parser which should be initialized for normal parsing
* @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected
* {@code "data"} or {@code "error"} key is not found
* @return the parser which was passed as a parameter
* @since 1.10
*/
public static JsonParser initializeParser(JsonParser parser) throws IOException {
// parse
boolean failed = true;
try {
String match = parser.skipToKey(new HashSet<String>(Arrays.asList("data", "error")));
if (match == null || parser.getCurrentToken() == JsonToken.END_OBJECT) {
throw new IllegalArgumentException("data key not found");
}
failed = false;
} finally {
if (failed) {
parser.close();
}
}
return parser;
}
@Override
public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException {
return initializeParser(jsonFactory.createJsonParser(in, charset)).parse(dataType, true, null);
}
@Override
public Object parseAndClose(Reader reader, Type dataType) throws IOException {
return initializeParser(jsonFactory.createJsonParser(reader)).parse(dataType, true, null);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/JsonCParser.java | Java | asf20 | 4,024 |
/*
* 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>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.json;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/package-info.java | Java | asf20 | 6,159 |
/*
* 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.HttpMediaType;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonGenerator;
import java.io.IOException;
import java.io.OutputStream;
/**
* Serializes JSON-C content based on the data key/value mapping object for an item, wrapped in a
* {@code "data"} envelope.
*
* <p>
* Warning: this should only be used by some older Google APIs that wrapped the response in a
* {@code "data"} envelope. All newer Google APIs don't use this envelope, and for those APIs
* {@link JsonHttpContent} should be used instead.
* </p>
*
* <p>
* Sample usage:
* </p>
*
* <pre>
static void setContent(HttpRequest request, Object data) {
JsonCContent content = new JsonCContent(new JacksonFactory(), data);
request.setContent(content);
}
* </pre>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonCContent extends JsonHttpContent {
/**
* @param jsonFactory JSON factory to use
* @param data JSON key name/value data
* @since 1.5
*/
public JsonCContent(JsonFactory jsonFactory, Object data) {
super(jsonFactory, data);
}
@Override
public void writeTo(OutputStream out) throws IOException {
JsonGenerator generator = getJsonFactory().createJsonGenerator(out, getCharset());
generator.writeStartObject();
generator.writeFieldName("data");
generator.serialize(getData());
generator.writeEndObject();
generator.flush();
}
@Override
public JsonCContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/JsonCContent.java | Java | asf20 | 2,343 |
/*
* 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.common.base.Preconditions;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* 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>
*
* <p>
* Warning: this is based on an undocumented experimental Google functionality that may stop working
* or change in behavior at any time. Beware of this risk if running this in production code.
* </p>
*
* @since 1.3
* @author Yaniv Inbar
*/
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 GoogleJsonRpcHttpTransport} Builder.
*
* <p>
* Implementation is not thread safe.
* </p>
*
* @since 1.9
*/
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, CustomizeJsonParser)}.
* </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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonRpcHttpTransport.java | Java | asf20 | 9,863 |
/*
* 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.util.Data;
import com.google.api.client.util.Key;
import java.io.IOException;
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 {
return new JsonCParser(jsonFactory).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;
}
}
/** 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;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonError.java | Java | asf20 | 6,258 |
/*
* 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.StringUtils;
import com.google.common.base.Preconditions;
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 response HTTP response
* @param details Google JSON error details
* @param message message details
*/
private GoogleJsonResponseException(
HttpResponse response, GoogleJsonError details, String message) {
super(response, message);
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) {
// 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, null);
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.common.base.Strings.isNullOrEmpty(detailString)) {
message.append(StringUtils.LINE_SEPARATOR).append(detailString);
}
// result
return new GoogleJsonResponseException(response, details, message.toString());
}
/**
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonResponseException.java | Java | asf20 | 7,101 |
/*
* 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;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/json/GoogleJsonErrorContainer.java | Java | asf20 | 1,203 |
/*
* 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 API's.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/package-info.java | Java | asf20 | 885 |
/*
* 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 java.io.IOException;
/**
* 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/draft-ietf-oauth-v2-23#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
public GoogleRefreshTokenRequest setScopes(String... scopes) {
return (GoogleRefreshTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleRefreshTokenRequest setScopes(Iterable<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);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleRefreshTokenRequest.java | Java | asf20 | 4,735 |
/*
* 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.common.base.Preconditions;
import java.io.IOException;
/**
* 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
public GoogleAuthorizationCodeTokenRequest setScopes(String... scopes) {
return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeTokenRequest setScopes(Iterable<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);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeTokenRequest.java | Java | asf20 | 6,512 |
/*
* 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.IdTokenResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* Google OAuth 2.0 JSON model for a successful access token response as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-23#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 GoogleIdToken#verify(GoogleIdTokenVerifier)} to verify
* it (or just call {@link #verifyIdToken(GoogleIdTokenVerifier)}).
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleTokenResponse extends IdTokenResponse {
@Override
public GoogleTokenResponse setIdToken(String idToken) {
return (GoogleTokenResponse) super.setIdToken(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);
}
@Override
public GoogleIdToken parseIdToken() throws IOException {
return GoogleIdToken.parse(getFactory(), getIdToken());
}
/**
* Verifies the ID token as specified in {@link GoogleIdTokenVerifier#verify} by passing it
* {@link #parseIdToken}.
*
* @param verifier Google ID token verifier
*/
public boolean verifyIdToken(GoogleIdTokenVerifier verifier)
throws GeneralSecurityException, IOException {
return verifier.verify(parseIdToken());
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleTokenResponse.java | Java | asf20 | 3,021 |
/*
* 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.jsontoken.JsonWebSignature;
import com.google.api.client.auth.jsontoken.JsonWebToken;
import com.google.api.client.auth.jsontoken.RsaSHA256Signer;
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.CredentialStore;
import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.auth.security.PrivateKeys;
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.util.Clock;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.List;
/**
* 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(String...)}. Sample usage:
* </p>
*
* <pre>
public static GoogleCredential createCredentialForServiceAccount(
HttpTransport transport,
JsonFactory jsonFactory,
String serviceAccountId,
Iterable<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,
Iterable<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 CredentialStore} and
* {@link Builder#addRefreshListener(CredentialRefreshListener)}.
* </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;
/**
* Space-separated OAuth scopes to use with the the service account flow or {@code null} if not
* using the service account flow.
*/
private 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() {
super(BearerToken.authorizationHeaderAccessMethod(), null, null,
GoogleOAuthConstants.TOKEN_SERVER_URL, null, null, null);
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport for executing refresh token request or {@code null} if not
* refreshing tokens
* @param jsonFactory JSON factory to use for parsing response for refresh token request or
* {@code null} if not refreshing tokens
* @param tokenServerEncodedUrl encoded token server URL or {@code null} if not refreshing tokens
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param requestInitializer HTTP request initializer for refresh token requests to the token
* server or {@code null} for none.
* @param refreshListeners listeners for refresh token results or {@code null} for none
* @param serviceAccountId service account ID (typically an e-mail address) or {@code null} if not
* using the service account flow
* @param serviceAccountScopes space-separated OAuth scopes to use with the the service account
* flow or {@code null} if not using the service account flow
* @param serviceAccountPrivateKey private key to use with the the service account flow or
* {@code null} if not using the service account flow
* @param serviceAccountUser 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
*/
protected GoogleCredential(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory,
String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication,
HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners,
String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey,
String serviceAccountUser) {
this(method, transport, jsonFactory, tokenServerEncodedUrl, clientAuthentication,
requestInitializer, refreshListeners, serviceAccountId, serviceAccountScopes,
serviceAccountPrivateKey, serviceAccountUser, Clock.SYSTEM);
}
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport for executing refresh token request or {@code null} if not
* refreshing tokens
* @param jsonFactory JSON factory to use for parsing response for refresh token request or
* {@code null} if not refreshing tokens
* @param tokenServerEncodedUrl encoded token server URL or {@code null} if not refreshing tokens
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param requestInitializer HTTP request initializer for refresh token requests to the token
* server or {@code null} for none.
* @param refreshListeners listeners for refresh token results or {@code null} for none
* @param serviceAccountId service account ID (typically an e-mail address) or {@code null} if not
* using the service account flow
* @param serviceAccountScopes space-separated OAuth scopes to use with the the service account
* flow or {@code null} if not using the service account flow
* @param serviceAccountPrivateKey private key to use with the the service account flow or
* {@code null} if not using the service account flow
* @param serviceAccountUser 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
* @param clock The clock to use for expiration check
* @since 1.9
*/
protected GoogleCredential(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory,
String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication,
HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners,
String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey,
String serviceAccountUser, Clock clock) {
super(method, transport, jsonFactory, tokenServerEncodedUrl, clientAuthentication,
requestInitializer, refreshListeners, clock);
if (serviceAccountPrivateKey == null) {
Preconditions.checkArgument(
serviceAccountId == null && serviceAccountScopes == null && serviceAccountUser == null);
} else {
this.serviceAccountId = Preconditions.checkNotNull(serviceAccountId);
this.serviceAccountScopes = Preconditions.checkNotNull(serviceAccountScopes);
this.serviceAccountPrivateKey = serviceAccountPrivateKey;
this.serviceAccountUser = 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
protected TokenResponse executeRefreshToken() throws IOException {
if (serviceAccountPrivateKey == null) {
return super.executeRefreshToken();
}
// service accounts
JsonWebSignature.Header header = new JsonWebSignature.Header();
header.setAlgorithm("RS256");
header.setType("JWT");
JsonWebToken.Payload payload = new JsonWebToken.Payload(getClock());
long currentTime = getClock().currentTimeMillis();
payload.setIssuer(serviceAccountId).setAudience(getTokenServerEncodedUrl())
.setIssuedAtTimeSeconds(currentTime / 1000)
.setExpirationTimeSeconds(currentTime / 1000 + 3600).setPrincipal(serviceAccountUser);
payload.put("scope", serviceAccountScopes);
try {
String assertion =
RsaSHA256Signer.sign(serviceAccountPrivateKey, getJsonFactory(), header, payload);
TokenRequest request = new TokenRequest(
getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()),
"assertion");
request.put("assertion_type", "http://oauth.net/grant_type/jwt/1.0/bearer");
request.put("assertion", assertion);
return request.execute();
} catch (GeneralSecurityException exception) {
IOException e = new IOException();
e.initCause(exception);
throw e;
}
}
/**
* Returns the service account ID (typically an e-mail address) or {@code null} if not using the
* service account flow.
*/
public final String getServiceAccountId() {
return serviceAccountId;
}
/**
* Returns the space-separated OAuth scopes to use with the the service account flow or
* {@code null} if not using the service account flow.
*/
public final String getServiceAccountScopes() {
return serviceAccountScopes;
}
/**
* Returns the private key to use with the the service account flow or {@code null} if not using
* the service account flow.
*/
public final PrivateKey getServiceAccountPrivateKey() {
return serviceAccountPrivateKey;
}
/**
* 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.
*/
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. */
private String serviceAccountId;
/**
* Space-separated OAuth scopes to use with the the service account flow or {@code null} for
* none.
*/
private String serviceAccountScopes;
/** Private key to use with the the service account flow or {@code null} for none. */
private PrivateKey serviceAccountPrivateKey;
/**
* Email address of the user the application is trying to impersonate in the service account
* flow or {@code null} for none.
*/
private String serviceAccountUser;
public Builder() {
super(BearerToken.authorizationHeaderAccessMethod());
setTokenServerEncodedUrl(GoogleOAuthConstants.TOKEN_SERVER_URL);
}
@Override
public GoogleCredential build() {
return new GoogleCredential(getMethod(), getTransport(), getJsonFactory(),
getTokenServerUrl() == null ? null : getTokenServerUrl().build(),
getClientAuthentication(), getRequestInitializer(), getRefreshListeners(),
serviceAccountId, serviceAccountScopes, serviceAccountPrivateKey, serviceAccountUser,
getClock());
}
@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;
}
/** Returns the service account ID (typically an e-mail address) or {@code null} for none. */
public final String getServiceAccountId() {
return serviceAccountId;
}
/**
* 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>
*/
public Builder setServiceAccountId(String serviceAccountId) {
this.serviceAccountId = serviceAccountId;
return this;
}
/**
* Returns the space-separated OAuth scopes to use with the the service account flow or
* {@code null} for none.
*/
public final String getServiceAccountScopes() {
return serviceAccountScopes;
}
/**
* 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)
*/
public Builder setServiceAccountScopes(String... serviceAccountScopes) {
return setServiceAccountScopes(
serviceAccountScopes == null ? null : Arrays.asList(serviceAccountScopes));
}
/**
* 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)
*/
public Builder setServiceAccountScopes(Iterable<String> serviceAccountScopes) {
this.serviceAccountScopes =
serviceAccountScopes == null ? null : Joiner.on(' ').join(serviceAccountScopes);
return this;
}
/**
* Returns the private key to use with the the service account flow or {@code null} for none.
*/
public final PrivateKey getServiceAccountPrivateKey() {
return serviceAccountPrivateKey;
}
/**
* 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>
*/
public Builder setServiceAccountPrivateKey(PrivateKey serviceAccountPrivateKey) {
this.serviceAccountPrivateKey = serviceAccountPrivateKey;
return this;
}
/**
* 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)
*/
public Builder setServiceAccountPrivateKeyFromP12File(File p12File)
throws GeneralSecurityException, IOException {
serviceAccountPrivateKey =
PrivateKeys.loadFromP12File(p12File, "notasecret", "privatekey", "notasecret");
return this;
}
/**
* 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
*/
public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile)
throws GeneralSecurityException, IOException {
serviceAccountPrivateKey =
PrivateKeys.loadFromPkcs8PemFile(pemFile);
return this;
}
/**
* Returns the email address of the user the application is trying to impersonate in the service
* account flow or {@code null} for none.
*/
public final String getServiceAccountUser() {
return serviceAccountUser;
}
/**
* 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>
*/
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(List<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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.java | Java | asf20 | 24,734 |
/*
* 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;
/**
* 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";
/**
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleOAuthConstants.java | Java | asf20 | 1,425 |
/*
* 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>
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library.</b>
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.auth.oauth2;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/package-info.java | Java | asf20 | 3,248 |
/*
* 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.CredentialStore;
import com.google.api.client.auth.oauth2.TokenRequest;
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.Clock;
import com.google.common.base.Preconditions;
import java.util.Collections;
/**
* 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>
*
* @since 1.7
* @author Yaniv Inbar
*/
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;
/**
* @param method method of presenting the access token to the resource server (for example
* {@link BearerToken#authorizationHeaderAccessMethod})
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param tokenServerUrl token server URL
* @param clientAuthentication client authentication or {@code null} for none (see
* {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})
* @param clientId client identifier
* @param authorizationServerEncodedUrl authorization server encoded URL
* @param credentialStore credential persistence store or {@code null} for none
* @param requestInitializer HTTP request initializer or {@code null} for none
* @param scopes space-separated list of scopes or {@code null} for none
* @param accessType access type ({@code "online"} to request online access or {@code "offline"}
* to request offline access) or {@code null} for the default behavior
* @param approvalPrompt 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
*/
protected GoogleAuthorizationCodeFlow(AccessMethod method,
HttpTransport transport,
JsonFactory jsonFactory,
GenericUrl tokenServerUrl,
HttpExecuteInterceptor clientAuthentication,
String clientId,
String authorizationServerEncodedUrl,
CredentialStore credentialStore,
HttpRequestInitializer requestInitializer,
String scopes,
String accessType,
String approvalPrompt) {
super(method,
transport,
jsonFactory,
tokenServerUrl,
clientAuthentication,
clientId,
authorizationServerEncodedUrl,
credentialStore,
requestInitializer,
scopes);
this.accessType = accessType;
this.approvalPrompt = 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(),
"",
Collections.singleton(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.
*/
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.
*/
private String accessType;
/**
* @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)
*/
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 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)
*/
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));
}
@Override
public GoogleAuthorizationCodeFlow build() {
return new GoogleAuthorizationCodeFlow(getMethod(),
getTransport(),
getJsonFactory(),
getTokenServerUrl(),
getClientAuthentication(),
getClientId(),
getAuthorizationServerEncodedUrl(),
getCredentialStore(),
getRequestInitializer(),
getScopes(),
accessType,
approvalPrompt);
}
@Override
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(Iterable<String> scopes) {
return (Builder) super.setScopes(scopes);
}
@Override
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);
}
/**
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeFlow.java | Java | asf20 | 13,787 |
/*
* 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.jsontoken.JsonWebSignature;
import com.google.api.client.auth.jsontoken.JsonWebToken;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* Google ID tokens.
*
* <p>
* Google ID tokens contain useful information such as the {@link Payload#getUserId() obfuscated
* Google user ID}. Google ID tokens are signed and the signature must be verified using
* {@link #verify(GoogleIdTokenVerifier)}, which also checks that your application's client ID is
* the intended audience.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class GoogleIdToken extends JsonWebSignature {
/**
* 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();
}
/** Google ID token payload. */
public static class Payload extends JsonWebToken.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;
/**
* Constructs a new Payload using default settings.
*/
public Payload() {
this(Clock.SYSTEM);
}
/**
* Constructs a new Payload and uses the specified {@link Clock}.
* @param clock Clock to use for expiration checks.
* @since 1.9
*/
public Payload(Clock clock) {
super(clock);
}
/** 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;
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleIdToken.java | Java | asf20 | 6,680 |
/*
* 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.Key;
import com.google.common.base.Preconditions;
/**
* 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="http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html">Using OAuth
* 2.0 for Client-side Applications (Experimental)</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;
/**
* @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)})
*/
public GoogleBrowserClientRequestUrl(
String clientId, String redirectUri, Iterable<String> scopes) {
super(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId);
setRedirectUri(redirectUri);
setScopes(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(Iterable)})
*/
public GoogleBrowserClientRequestUrl(
GoogleClientSecrets clientSecrets, String redirectUri, Iterable<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(String... responseTypes) {
return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
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(String... scopes) {
Preconditions.checkArgument(scopes.length != 0);
return (GoogleBrowserClientRequestUrl) super.setScopes(scopes);
}
@Override
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);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleBrowserClientRequestUrl.java | Java | asf20 | 5,575 |
/*
* 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.Key;
import com.google.common.base.Preconditions;
/**
* 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="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for Web
* Server Applications (Experimental)</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;
/**
* @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)})
*/
public GoogleAuthorizationCodeRequestUrl(
String clientId, String redirectUri, Iterable<String> scopes) {
this(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId, redirectUri, 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(Iterable)})
*
* @since 1.12
*/
public GoogleAuthorizationCodeRequestUrl(String authorizationServerEncodedUrl,
String clientId, String redirectUri, Iterable<String> scopes) {
super(authorizationServerEncodedUrl, clientId);
setRedirectUri(redirectUri);
setScopes(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(Iterable)})
*/
public GoogleAuthorizationCodeRequestUrl(
GoogleClientSecrets clientSecrets, String redirectUri, Iterable<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
public GoogleAuthorizationCodeRequestUrl setResponseTypes(String... responseTypes) {
return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setResponseTypes(Iterable<String> responseTypes) {
return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setRedirectUri(String redirectUri) {
Preconditions.checkNotNull(redirectUri);
return (GoogleAuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri);
}
@Override
public GoogleAuthorizationCodeRequestUrl setScopes(String... scopes) {
Preconditions.checkArgument(scopes.length != 0);
return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes);
}
@Override
public GoogleAuthorizationCodeRequestUrl setScopes(Iterable<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);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeRequestUrl.java | Java | asf20 | 7,558 |
/*
* 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.jsontoken.JsonWebSignature;
import com.google.api.client.http.GenericUrl;
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.Clock;
import com.google.api.client.util.StringUtils;
import com.google.common.base.Preconditions;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Thread-safe Google ID token verifier.
*
* <p>
* The public keys are loaded Google's public certificate endpoint at
* {@code "https://www.googleapis.com/oauth2/v1/certs"}. The public keys are cached in this instance
* of {@link GoogleIdTokenVerifier}. Therefore, for maximum efficiency, applications should use a
* single globally-shared instance of the {@link GoogleIdTokenVerifier}. Use
* {@link #verify(GoogleIdToken)} or {@link GoogleIdToken#verify(GoogleIdTokenVerifier)} to verify a
* Google ID token.
* </p>
*
* <p>
* Samples usage:
* </p>
*
* <pre>
public static GoogleIdTokenVerifier verifier;
public static void initVerifier(
HttpTransport transport, JsonFactory jsonFactory, String clientId) {
verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setClientId(clientId)
.build();
}
public static boolean verifyToken(GoogleIdToken idToken)
throws GeneralSecurityException, IOException {
return verifier.verify(idToken);
}
* </pre>
* @since 1.7
*/
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*");
/** 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;
/** Set of Client IDs. */
private Set<String> clientIds;
/** 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;
/**
* 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(null, transport, jsonFactory);
}
/**
* Construct the {@link GoogleIdTokenVerifier}.
*
* @param clientIds set of client IDs or {@code null} for none
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @since 1.9
*/
protected GoogleIdTokenVerifier(
Set<String> clientIds, HttpTransport transport, JsonFactory jsonFactory) {
this(clientIds, transport, jsonFactory, Clock.SYSTEM);
}
/**
* Construct the {@link GoogleIdTokenVerifier}.
*
* @param clientIds set of client IDs or {@code null} for none
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param clock Clock for expiration checks
* @since 1.9
*/
protected GoogleIdTokenVerifier(
Set<String> clientIds, HttpTransport transport, JsonFactory jsonFactory, Clock clock) {
this.clientIds =
clientIds == null ? Collections.<String>emptySet() : Collections.unmodifiableSet(clientIds);
this.transport = Preconditions.checkNotNull(transport);
this.jsonFactory = Preconditions.checkNotNull(jsonFactory);
this.clock = Preconditions.checkNotNull(clock);
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/**
* Returns the set of client IDs.
*
* @since 1.9
*/
public final Set<String> getClientIds() {
return clientIds;
}
/** 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 {@link #verify(GoogleIdToken, String)} with the
* {@link #getClientIds()}.
*
* @param idToken Google ID token
* @return {@code true} if verified successfully or {@code false} if failed
*/
public boolean verify(GoogleIdToken idToken) throws GeneralSecurityException, IOException {
return verify(clientIds, idToken);
}
/**
* Returns a Google ID token if the given ID token string is valid using
* {@link #verify(GoogleIdToken, String)} with the {@link #getClientIds()}.
*
* @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;
}
/**
* Verifies that the given ID token is valid, using the given client ID.
*
* 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>
* <li>The audience and issuee match the client ID (skipped if {@code clientId} is {@code null}.
* </li>
* <li>
* </ul>
*
* @param idToken Google ID token
* @param clientId client ID or {@code null} to skip checking it
* @return {@code true} if verified successfully or {@code false} if failed
* @since 1.8
*/
public boolean verify(GoogleIdToken idToken, String clientId)
throws GeneralSecurityException, IOException {
return verify(
clientId == null ? Collections.<String>emptySet() : Collections.singleton(clientId),
idToken);
}
/**
* Verifies that the given ID token is valid, using the given set of client IDs.
*
* 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>
* <li>The audience and issuee match one of the client IDs (skipped if {@code clientIds} is
* {@code null}.</li>
* <li>
* </ul>
*
* @param idToken Google ID token
* @param clientIds set of client IDs
* @return {@code true} if verified successfully or {@code false} if failed
* @since 1.9
*/
public boolean verify(Set<String> clientIds, GoogleIdToken idToken)
throws GeneralSecurityException, IOException {
// check the payload
GoogleIdToken.Payload payload = idToken.getPayload();
if (!payload.isValidTime(300) || !"accounts.google.com".equals(payload.getIssuer())
|| !clientIds.isEmpty() && (!clientIds.contains(payload.getAudience())
|| !clientIds.contains(payload.getIssuee()))) {
return false;
}
// check the signature
JsonWebSignature.Header header = idToken.getHeader();
String algorithm = header.getAlgorithm();
if (algorithm.equals("RS256")) {
lock.lock();
try {
// load public keys; expire 5 minutes (300 seconds) before actual expiration time
if (publicKeys == null || clock.currentTimeMillis() + 300000 > expirationTimeMilliseconds) {
loadPublicCerts();
}
Signature signer = Signature.getInstance("SHA256withRSA");
for (PublicKey publicKey : publicKeys) {
signer.initVerify(publicKey);
signer.update(idToken.getSignedContentBytes());
if (signer.verify(idToken.getSignatureBytes())) {
return true;
}
}
} finally {
lock.unlock();
}
}
return false;
}
/**
* Downloads the public keys from the public certificates endpoint at
* {@code "https://www.googleapis.com/oauth2/v1/certs"}.
*
* <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 = CertificateFactory.getInstance("X509");
HttpResponse certsResponse = transport.createRequestFactory()
.buildGetRequest(new GenericUrl("https://www.googleapis.com/oauth2/v1/certs")).execute();
// parse Cache-Control max-age parameter
for (String arg : certsResponse.getHeaders().getCacheControl().split(",")) {
Matcher m = MAX_AGE_PATTERN.matcher(arg);
if (m.matches()) {
expirationTimeMilliseconds = clock.currentTimeMillis() + Long.valueOf(m.group(1)) * 1000;
break;
}
}
// 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();
}
}
/**
* Builder for {@link GoogleIdTokenVerifier}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
*/
public static class Builder {
/** HTTP transport. */
private final HttpTransport transport;
/** JSON factory. */
private final JsonFactory jsonFactory;
/** Set of Client IDs. */
private Set<String> clientIds = new HashSet<String>();
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport
* @param jsonFactory JSON factory
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory) {
this.transport = transport;
this.jsonFactory = jsonFactory;
}
/** Builds a new instance of {@link GoogleIdTokenVerifier}. */
public GoogleIdTokenVerifier build() {
return new GoogleIdTokenVerifier(clientIds, transport, jsonFactory);
}
/** Returns the HTTP transport. */
public final HttpTransport getTransport() {
return transport;
}
/** Returns the JSON factory. */
public final JsonFactory getJsonFactory() {
return jsonFactory;
}
/** Returns the set of client IDs. */
public final Set<String> getClientIds() {
return clientIds;
}
/**
* Sets a list of client IDs.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientIds(Iterable<String> clientIds) {
this.clientIds.clear();
for (String clientId : clientIds) {
this.clientIds.add(clientId);
}
return this;
}
/**
* Sets a list of client IDs.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setClientIds(String... clientIds) {
this.clientIds.clear();
Collections.addAll(this.clientIds, clientIds);
return this;
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleIdTokenVerifier.java | Java | asf20 | 13,878 |
/*
* 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.Key;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
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;
}
}
/** Loads the {@code client_secrets.json} file from the given input stream. */
public static GoogleClientSecrets load(JsonFactory jsonFactory, InputStream inputStream)
throws IOException {
// TODO(mlinder): Change this method to take a charset
return jsonFactory.fromInputStream(inputStream, GoogleClientSecrets.class);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/GoogleClientSecrets.java | Java | asf20 | 4,583 |
/*
* 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.Key;
import com.google.api.client.util.StringUtils;
import java.io.IOException;
/**
* 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
*/
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);
}
// 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 (!com.google.common.base.Strings.isNullOrEmpty(detailString)) {
message.append(StringUtils.LINE_SEPARATOR).append(detailString);
}
throw new ClientLoginResponseException(response, details, message.toString());
}
/**
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/ClientLogin.java | Java | asf20 | 6,370 |
/*
* 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.HttpResponse;
import com.google.api.client.http.HttpResponseException;
/**
* 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
*/
public class ClientLoginResponseException extends HttpResponseException {
private static final long serialVersionUID = 4974317674023010928L;
/** Error details or {@code null} for none. */
private final transient ErrorInfo details;
/**
* @param response HTTP response
* @param details error details or {@code null} for none
* @param message message details
*/
ClientLoginResponseException(HttpResponse response, ErrorInfo details, String message) {
super(response, message);
this.details = details;
}
/** Return the error details or {@code null} for none. */
public final ErrorInfo getDetails() {
return details;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/ClientLoginResponseException.java | Java | asf20 | 1,763 |
/*
* 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 legacy ClientLogin authentication method as described in <a
* href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html">ClientLogin for
* Installed Applications</a>.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.auth.clientlogin;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/package-info.java | Java | asf20 | 1,082 |
/*
* 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.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;
/**
* HTTP parser for Google response to an Authorization request.
*
* @since 1.10
* @author Yaniv Inbar
*/
@SuppressWarnings("deprecation")
final class AuthKeyValueParser implements com.google.api.client.http.HttpParser, 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/auth/clientlogin/AuthKeyValueParser.java | Java | asf20 | 5,286 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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;
/**
* Utility class for the Google API Client Library.
*
* @since 1.12
* @author rmistry@google.com (Ravi Mistry)
*/
public class GoogleUtils {
/** Current version of the Google API Client Library for Java. */
public static final String VERSION = "1.14.0-beta-SNAPSHOT";
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java | Java | asf20 | 880 |
/*
* 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.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.common.base.Preconditions;
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>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
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<?, ?>>();
/** 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;
}
/**
* 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);
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;
batchRequest.setContent(new MultipartMixedContent(requestInfos, "__END_OF_PART__"));
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) {
sleep(backOffTime);
}
}
} else {
break;
}
retriesRemaining--;
} while (retryAllowed);
requestInfos.clear();
}
/**
* An exception safe sleep where if the sleeping is interrupted the exception is ignored.
*
* @param millis to sleep
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// Ignore.
}
}
/**
* 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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchRequest.java | Java | asf20 | 9,267 |
/*
* 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.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.batch.json;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/json/package-info.java | Java | asf20 | 910 |
/*
* 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.
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/json/JsonBatchCallback.java | Java | asf20 | 2,325 |
/*
* 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.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.9
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.batch;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/package-info.java | Java | asf20 | 900 |
/*
* 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.ObjectParser;
import com.google.api.client.util.StringUtils;
import com.google.common.base.Preconditions;
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)
*/
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();
Preconditions.checkState(statusLine != null);
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);
}
}
}
@SuppressWarnings("deprecation")
private <A, T, E> A getParsedDataClass(
Class<A> dataClass, HttpResponse response, RequestInfo<T, E> requestInfo, String contentType)
throws IOException {
// TODO(mlinder): Remove the HttpResponse reference and directly parse the InputStream
com.google.api.client.http.HttpParser oldParser = requestInfo.request.getParser(contentType);
ObjectParser parser = requestInfo.request.getParser();
A parsed = null;
if (dataClass != Void.class) {
parsed = parser != null ? parser.parseAndClose(
response.getContent(), response.getContentCharset(), dataClass) : oldParser.parse(
response, dataClass);
}
return parsed;
}
/** Create a fake HTTP response object populated with the partContent and the statusCode. */
@Deprecated
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();
}
}
@Deprecated
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 buildDeleteRequest(String url) {
return null;
}
@Override
protected LowLevelHttpRequest buildGetRequest(String url) {
return null;
}
@Override
protected LowLevelHttpRequest buildPostRequest(String url) {
return new FakeLowLevelHttpRequest(partContent, statusCode, headerNames, headerValues);
}
@Override
protected LowLevelHttpRequest buildPutRequest(String url) {
return null;
}
}
@Deprecated
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 void setContent(HttpContent content) {
}
@Override
public LowLevelHttpResponse execute() {
FakeLowLevelHttpResponse response = new FakeLowLevelHttpResponse(new ByteArrayInputStream(
StringUtils.getBytesUtf8(partContent)), statusCode, headerNames, headerValues);
return response;
}
}
@Deprecated
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchUnparsedResponse.java | Java | asf20 | 12,631 |
/*
* 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.AbstractHttpContent;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequest;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
/**
* Serializes MIME Multipart/Mixed content as specified by <a
* href="http://tools.ietf.org/html/rfc2046">RFC 2046: Multipurpose Internet Mail Extensions</a>.
*
* <p>
* Takes in a list of {@link HttpRequest} and serializes their headers and content separating each
* request with a boundary. The "Content-ID" header of each request is incremented in order.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.9
* @author rmistry@google.com (Ravi Mistry)
*/
class MultipartMixedContent extends AbstractHttpContent {
private static final String CR_LF = "\r\n";
private static final String TWO_DASHES = "--";
/** List of request infos. */
private List<BatchRequest.RequestInfo<?, ?>> requestInfos;
/**
* Construct an instance of {@link MultipartMixedContent}.
*
* @param requestInfos List of request infos
* @param boundary Boundary string to use for separating each HTTP request
*/
MultipartMixedContent(List<BatchRequest.RequestInfo<?, ?>> requestInfos, String boundary) {
super(new HttpMediaType("multipart/mixed").setParameter(
"boundary", Preconditions.checkNotNull(boundary)));
Preconditions.checkNotNull(requestInfos);
Preconditions.checkArgument(!requestInfos.isEmpty());
this.requestInfos = Collections.unmodifiableList(requestInfos);
}
private String getBoundary() {
return getMediaType().getParameter("boundary");
}
public void writeTo(OutputStream out) throws IOException {
int contentId = 1;
Writer writer = new OutputStreamWriter(out);
String boundary = getBoundary();
for (BatchRequest.RequestInfo<?, ?> requestInfo : requestInfos) {
HttpRequest request = requestInfo.request;
// Write batch separator.
writer.write(TWO_DASHES);
writer.write(boundary);
writer.write(CR_LF);
// Write multipart headers.
writer.write("Content-Type: application/http");
writer.write(CR_LF);
writer.write("Content-Transfer-Encoding: binary");
writer.write(CR_LF);
writer.write("Content-ID: ");
writer.write(String.valueOf(contentId++));
writer.write(CR_LF);
writer.write(CR_LF);
// Write the batch method and path.
writer.write(request.getRequestMethod());
writer.write(" ");
writer.write(request.getUrl().build());
writer.write(CR_LF);
// Write the batch headers.
HttpHeaders.serializeHeadersForMultipartRequests(request.getHeaders(), null, null, writer);
// Write the data to the body.
HttpContent data = request.getContent();
if (data != null) {
String type = data.getType();
if (type != null) {
writeHeader(writer, "Content-Type", type);
}
long length = data.getLength();
if (length != -1) {
writeHeader(writer, "Content-Length", length);
}
writer.write(CR_LF);
writer.flush();
data.writeTo(out);
}
writer.write(CR_LF);
}
// Write the end of the batch separator.
writer.write(TWO_DASHES);
writer.write(boundary);
writer.write(TWO_DASHES);
writer.write(CR_LF);
writer.flush();
}
/** Writes a header to the Writer. */
private void writeHeader(Writer writer, String name, Object value) throws IOException {
writer.write(name);
writer.write(": ");
writer.write(value.toString());
writer.write(CR_LF);
}
@Override
public MultipartMixedContent setMediaType(HttpMediaType mediaType) {
super.setMediaType(mediaType);
return this;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/MultipartMixedContent.java | Java | asf20 | 4,666 |
/*
* 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.
*
* <p>
* Upgrade warning: this method now throws an {@link IOException}. In prior version 1.11 it did
* not throw an exception.
* </p>
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @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.
*
* <p>
* Upgrade warning: in prior version 1.12 the response headers were of type
* {@code GoogleHeaders}, but as of version 1.13 that type is deprecated, so we now use type
* {@link HttpHeaders}.
* </p>
*
* @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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/batch/BatchCallback.java | Java | asf20 | 2,614 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.ObjectParser;
/**
* Thread-safe mock Google client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public class MockGoogleClient extends AbstractGoogleClient {
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser
*/
public MockGoogleClient(HttpTransport transport, HttpRequestInitializer httpRequestInitializer,
String rootUrl, String servicePath, ObjectParser objectParser) {
super(transport, httpRequestInitializer, rootUrl, servicePath, objectParser);
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser or {@code null} for none
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
public MockGoogleClient(HttpTransport transport, HttpRequestInitializer httpRequestInitializer,
String rootUrl, String servicePath, ObjectParser objectParser,
GoogleClientRequestInitializer googleClientRequestInitializer, String applicationName,
boolean suppressPatternChecks) {
super(transport, httpRequestInitializer, rootUrl, servicePath, objectParser,
googleClientRequestInitializer, applicationName, suppressPatternChecks);
}
/**
* Builder for {@link MockGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
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 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(getTransport(), getHttpRequestInitializer(), getRootUrl(),
getServicePath(), getObjectParser(), getGoogleClientRequestInitializer(),
getApplicationName(), getSuppressPatternChecks());
}
@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);
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/MockGoogleClient.java | Java | asf20 | 4,703 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Test utilities for the {@code com.google.api.client.googleapis.json} package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.testing.services.json;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/package-info.java | Java | asf20 | 935 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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;
/**
* Thread-safe mock Google JSON request.
*
* @param <T> type of the response
* @since 1.12
* @author Yaniv Inbar
*/
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-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/MockGoogleJsonClientRequest.java | Java | asf20 | 2,327 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.json.JsonObjectParser;
/**
* Thread-safe mock Google JSON client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public class MockGoogleJsonClient extends AbstractGoogleJsonClient {
/**
* @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) {
super(transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer, legacyDataWrapper);
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param jsonObjectParser JSON object parser
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
public MockGoogleJsonClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
JsonObjectParser jsonObjectParser,
GoogleClientRequestInitializer googleClientRequestInitializer, String applicationName,
boolean suppressPatternChecks) {
super(transport, httpRequestInitializer, rootUrl, servicePath, jsonObjectParser,
googleClientRequestInitializer, applicationName, suppressPatternChecks);
}
/**
* Builder for {@link MockGoogleJsonClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
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(getTransport(), getHttpRequestInitializer(), getRootUrl(),
getServicePath(), getObjectParser(), getGoogleClientRequestInitializer(),
getApplicationName(), getSuppressPatternChecks());
}
@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);
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/json/MockGoogleJsonClient.java | Java | asf20 | 5,079 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Test utilities for the {@code com.google.api.client.googleapis} package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.testing.services;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/package-info.java | Java | asf20 | 925 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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;
/**
* Thread-safe mock Google request.
*
* @param <T> type of the response
* @since 1.12
* @author Yaniv Inbar
*/
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);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/services/MockGoogleClientRequest.java | Java | asf20 | 2,205 |
/*
* 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.
*/
/**
* Test utilities for the Subscriptions extension package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.testing.subscriptions;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/subscriptions/package-info.java | Java | asf20 | 964 |
/*
* 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.Subscription;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
/**
* Mock for the {@link NotificationCallback} class.
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("rawtypes")
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(
Subscription subscription, UnparsedNotification notification) {
wasCalled = true;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/testing/subscriptions/MockNotificationCallback.java | Java | asf20 | 1,517 |
/*
* 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;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* Generic Google URL providing for some common query parameters used in Google API's such as the
* {@link #alt} and {@link #fields} parameters.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Use {@link GenericUrl}
*/
@Deprecated
public class GoogleUrl extends GenericUrl {
/** Whether to pretty print the output. */
@Key("prettyPrint")
private Boolean prettyprint;
/** Alternate wire format. */
@Key
private String alt;
/** Partial fields mask. */
@Key
private String fields;
/**
* API key as described in the <a href="https://code.google.com/apis/console-help/">Google APIs
* Console documentation</a>.
*/
@Key
private String key;
/**
* User IP used to enforce per-user limits for server-side applications, as described in the <a
* href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs Console
* documentation</a>.
*/
@Key("userIp")
private String userip;
public GoogleUrl() {
}
/**
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
*/
public GoogleUrl(String encodedUrl) {
super(encodedUrl);
}
@Override
public GoogleUrl clone() {
return (GoogleUrl) super.clone();
}
/**
* Returns whether to pretty print the output.
*
* @since 1.8
*/
public Boolean getPrettyPrint() {
return prettyprint;
}
/**
* Sets whether to pretty print the output.
*
* @since 1.8
*/
public void setPrettyPrint(Boolean prettyPrint) {
this.prettyprint = prettyPrint;
}
/**
* Returns the alternate wire format.
*
* @since 1.8
*/
public final String getAlt() {
return alt;
}
/**
* Sets the alternate wire format.
*
* @since 1.8
*/
public final void setAlt(String alt) {
this.alt = alt;
}
/**
* Returns the partial fields mask.
*
* @since 1.8
*/
public final String getFields() {
return fields;
}
/**
* Sets the partial fields mask.
*
* @since 1.8
*/
public final void setFields(String fields) {
this.fields = fields;
}
/**
* Returns the API key as described in the <a
* href="https://code.google.com/apis/console-help/">Google APIs Console documentation</a>.
*
* @since 1.8
*/
public final String getKey() {
return key;
}
/**
* Sets the API key as described in the <a
* href="https://code.google.com/apis/console-help/">Google APIs Console documentation</a>.
*
* @since 1.8
*/
public final void setKey(String key) {
this.key = key;
}
/**
* Returns the user IP used to enforce per-user limits for server-side applications, as described
* in the <a href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs
* Console documentation</a>.
*
* @since 1.8
*/
public final String getUserIp() {
return userip;
}
/**
* Sets the user IP used to enforce per-user limits for server-side applications, as described in
* the <a href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs Console
* documentation</a>.
*
* @since 1.8
*/
public final void setUserIp(String userip) {
this.userip = userip;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUrl.java | Java | asf20 | 4,036 |
/*
* 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;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.util.Key;
import com.google.api.client.util.escape.PercentEscaper;
/**
* HTTP headers for Google API's.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Use {@link HttpHeaders}
*/
@Deprecated
public class GoogleHeaders extends HttpHeaders {
/** Escaper for the {@link #slug} header. */
public static final PercentEscaper SLUG_ESCAPER =
new PercentEscaper(" !\"#$&'()*+,-./:;<=>?@[\\]^_`{|}~", false);
/** {@code "GData-Version"} header. */
@Key("GData-Version")
private String gdataVersion;
/**
* Escaped {@code "Slug"} header value, which must be escaped using {@link #SLUG_ESCAPER}.
*
* @see #setSlugFromFileName(String)
*/
@Key("Slug")
private String slug;
/** {@code "X-GData-Client"} header. */
@Key("X-GData-Client")
private String gdataClient;
/**
* {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}.
*
* @see #setDeveloperId(String)
*/
@Key("X-GData-Key")
private String gdataKey;
/** {@code "X-HTTP-Method-Override"} header. */
@Key("X-HTTP-Method-Override")
private String methodOverride;
/** {@code "X-Upload-Content-Length"} header. */
@Key("X-Upload-Content-Length")
private Long uploadContentLength;
/** {@code "X-Upload-Content-Type"} header. */
@Key("X-Upload-Content-Type")
private String uploadContentType;
/**
* Creates an empty GoogleHeaders object.
*/
public GoogleHeaders() {
}
/**
* Creates a GoogleHeaders object using the headers present in the specified {@link HttpHeaders}.
*
* @param headers HTTP headers object including set headers
* @since 1.11
*/
public GoogleHeaders(HttpHeaders headers) {
this.fromHttpHeaders(headers);
}
/**
* Sets the {@code "Slug"} header for the given file name, properly escaping the header value. See
* <a href="http://tools.ietf.org/html/rfc5023#section-9.7">The Slug Header</a>.
*/
public void setSlugFromFileName(String fileName) {
slug = SLUG_ESCAPER.escape(fileName);
}
/**
* Sets the {@code "User-Agent"} header of the form
* {@code "[company-id]-[app-name]/[app-version]"}, for example {@code "Google-Sample/1.0"}.
*/
public void setApplicationName(String applicationName) {
setUserAgent(applicationName);
}
/** Sets the {@link #gdataKey} header using the given developer ID. */
public void setDeveloperId(String developerId) {
gdataKey = "key=" + developerId;
}
/**
* Sets the Google Login {@code "Authorization"} header for the given authentication token.
*/
public void setGoogleLogin(String authToken) {
setAuthorization(getGoogleLoginValue(authToken));
}
/**
* Returns the {@code "X-Upload-Content-Length"} header or {@code null} for none.
*
* <p>
* Upgrade warning: this method now returns a {@link Long}. In prior version 1.11 it returned a
* {@code long}.
* </p>
*
* @since 1.7
*/
public final Long getUploadContentLength() {
return uploadContentLength;
}
/**
* Sets the {@code "X-Upload-Content-Length"} header or {@code null} for none.
*
* @since 1.12
*/
public final void setUploadContentLength(Long uploadContentLength) {
this.uploadContentLength = uploadContentLength;
}
/**
* Sets the {@code "X-Upload-Content-Length"} header.
*
* @since 1.7
*/
@Deprecated
public final void setUploadContentLength(long uploadContentLength) {
this.uploadContentLength = uploadContentLength;
}
/**
* Returns the {@code "X-Upload-Content-Type"} header or {@code null} for none.
*
* @since 1.7
*/
public final String getUploadContentType() {
return uploadContentType;
}
/**
* Sets the {@code "X-Upload-Content-Type"} header or {@code null} for none.
*
* @since 1.7
*/
public final void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
/**
* Returns Google Login {@code "Authorization"} header value based on the given authentication
* token.
* @deprecated (scheduled to be removed in 1.14) Use
* {@code ClientLogin.getAuthorizationHeaderValue}
*/
@Deprecated
public static String getGoogleLoginValue(String authToken) {
return "GoogleLogin auth=" + authToken;
}
/**
* Returns the {@code "GData-Version"} header.
*
* @since 1.8
*/
public final String getGDataVersion() {
return gdataVersion;
}
/**
* Sets the {@code "GData-Version"} header.
*
* @since 1.8
*/
public final void setGDataVersion(String gdataVersion) {
this.gdataVersion = gdataVersion;
}
/**
* Returns the escaped {@code "Slug"} header value, which must be escaped using
* {@link #SLUG_ESCAPER}.
*
* @since 1.8
*/
public final String getSlug() {
return slug;
}
/**
* Sets the escaped {@code "Slug"} header value, which must be escaped using
* {@link #SLUG_ESCAPER}.
*
* @since 1.8
*/
public final void setSlug(String slug) {
this.slug = slug;
}
/**
* Returns the {@code "X-GData-Client"} header.
*
* @since 1.8
*/
public final String getGDataClient() {
return gdataClient;
}
/**
* Sets the {@code "X-GData-Client"} header.
*
* @since 1.8
*/
public final void setGDataClient(String gdataClient) {
this.gdataClient = gdataClient;
}
/**
* Returns the {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}
* .
*
* @since 1.8
*/
public final String getGDataKey() {
return gdataKey;
}
/**
* Sets the {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}.
*
* @since 1.8
*/
public final void setGDataKey(String gdataKey) {
this.gdataKey = gdataKey;
}
/**
* Returns the {@code "X-HTTP-Method-Override"} header.
*
* @since 1.8
*/
public final String getMethodOverride() {
return methodOverride;
}
/**
* Sets the {@code "X-HTTP-Method-Override"} header.
*
* @since 1.8
*/
public final void setMethodOverride(String methodOverride) {
this.methodOverride = methodOverride;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/GoogleHeaders.java | Java | asf20 | 6,936 |
<html>
<title>Release Process</title>
<body>
<h2>Release Process</h2>
<h3>First time set up</h3>
<ul>
<li>Make sure you have at least a Committer role</li>
<li>Make sure you have permission to post to the <a
href="http://google-api-java-client.blogspot.com/">Announcement Blog</a>.</li>
<li>Download <a href="http://sourceforge.net/projects/javadiff/">JDiff</a>.</li>
<li>Set up for pushing to the central Maven repository
<ul>
<li>Sign up for a Sonatype JIRA account at <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>. Click
<i>Sign Up</i> in the Login box, fill out the simple form, and click <i>Sign
Up</i>.</li>
<li>Request publishing rights to the maven project:</li>
<ul>
<li>Go to <a href="https://issues.sonatype.org/browse/OSSRH">
https://issues.sonatype.org/browse/OSSRH</a></li>
<li>Click "Create Issue" in the top-right corner.</li>
<li>Fill our the ticket form as follows, or use <a href="https://issues.sonatype.org/browse/OSSRH-4565">this</a> previous issue as a
template:
<ul>
<li><b>Type:</b> New Project</li>
<li><b>Summary:</b> Publish rights for already existing project</li>
<li><b>Description: </b>This project already exists, I just need to have publish rights to deploy a new release. Thank you.</li>
<li><b>Group Id:</b> com.google.api.client</li>
<li><b>Project URL:</b> http://code.google.com/p/google-api-java-client/</li>
<li><b>SCM url:</b> https://google-api-java-client.googlecode.com/hg/</li>
<li><b>Username:</b> <i>YourUsername</i></li>
</ul>
</li>
</ul>
</li>
</ul>
<li>Install a GPG client from <a href="http://www.gnupg.org/">http://www.gnupg.org/</a>,
and then create a GPG key using <a
href="http://www.sonatype.com/people/2010/01/how-to-generate-pgp-signatures-with-maven/">these
instructions</a>, making sure to specify a passphrase to be used every time you
release. Make sure to run the instructions under "Distribute Your Public
Key".</li>
<li>Add these lines to your <code>~/.hgrc</code>: <pre><code>
[ui]
username = Your Name <i><yourname@domain.com></i>
[auth]
google-api-java-client.prefix = https://google-api-java-client.googlecode.com/hg/
google-api-java-client.username = <i>[username from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i>
google-api-java-client.password = <i>[password from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i>
javadoc-google-api-java-client.prefix = https://javadoc.google-api-java-client.googlecode.com/hg/
javadoc-google-api-java-client.username = <i>[username from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i>
javadoc-google-api-java-client.password = <i>[password from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i>
wiki-google-api-java-client.prefix = https://wiki.google-api-java-client.googlecode.com/hg/
wiki-google-api-java-client.username = <i>[username from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i>
wiki-google-api-java-client.password = <i>[password from <a
href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i></code></pre></li>
<li>Add these lines to your <code>~/.m2/settings.xml</code> (create
this file if it does not already exist): <pre><code><settings>
<servers>
<server>
<id>google-snapshots</id>
<username><i>[username for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></username>
<password><i>[password for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></password>
</server>
<server>
<id>google-releases</id>
<username><i>[username for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></username>
<password><i>[password for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></password>
</server>
<server>
<id>sonatype-nexus-snapshots</id>
<username><i>[username for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></username>
<password><i>[password for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></password>
</server>
<server>
<id>sonatype-nexus-staging</id>
<username><i>[username for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></username>
<password><i>[password for <a
href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i></password>
</server>
</servers>
</settings></code></pre></li>
</ul>
</li>
</ul>
<h3>Fork version 1.14.0-beta</h3>
This is done in preparation for release of the 1.14 branch a week before the
official launch. We create a named Mercurial branch for 1.14. Development in the
default Mercurial branch may then progress for the next minor version.
<ul>
<li>Create the Mercurial named branch: <pre>
hg branch 1.14
hg commit -m "create 1.14 branch in preparation for release"
hg push --new-branch
hg update default
</pre></li>
<li>Update existing files by replacing <code>1.14.0-beta</code> with the
next minor version. This can be done by running this set of sed commands:
<pre>
VER_NEXT=1.15; VER_CUR=1.14; VER_PREV=1.13; VER_SUFFIX='\.0-beta'
function esc() { echo $@ | sed "s/\./\\\./g"; }
ESC_VER_NEXT=`esc ${VER_NEXT}`; ESC_VER_CUR=`esc ${VER_CUR}`; ESC_VER_PREV=`esc ${VER_PREV}`
sed -i "s@${ESC_VER_CUR}${VER_SUFFIX}@${ESC_VER_NEXT}${VER_SUFFIX}@g" pom.xml
sed -i "s@${ESC_VER_CUR}${VER_SUFFIX}@${ESC_VER_NEXT}${VER_SUFFIX}@g" */pom.xml
for filename in google-api-client-assembly/android-properties/*.properties; do newname=`echo $filename | sed -e "s@${ESC_VER_CUR}${VER_SUFFIX}@${ESC_VER_NEXT}${VER_SUFFIX}@g"`; hg mv $filename $newname; done
sed -i -e "s@${ESC_VER_CUR}${VER_SUFFIX}@${ESC_VER_NEXT}${VER_SUFFIX}@g" -e "s@${ESC_VER_PREV}${VER_SUFFIX}@${ESC_VER_CUR}${VER_SUFFIX}@g" jdiff.xml
sed -i "s@${ESC_VER_CUR}${VER_SUFFIX}@${ESC_VER_NEXT}${VER_SUFFIX}@g" google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java
sed -i -e "s@${ESC_VER_CUR}@${ESC_VER_NEXT}@g" -e "s@${ESC_VER_PREV}@${ESC_VER_CUR}@g" release.html
echo -n && read -e -p "Version which comes after ${VER_NEXT}: " NV && sed -i -e "s@VER_NEXT=${ESC_VER_NEXT}@VER_NEXT=${NV}@g" release.html
</pre></li>
<li>Commit and push: <pre>
Submit the changes for review as usual, using upload.py
hg commit -m "Start next minor version"
hg push
</pre></li>
</ul>
<h3>Release version 1.14.0-beta</h3>
This process is followed for the official launch. We are releasing the code from
the 1.14 Mercurial branch.
<ul>
<li>Checkout the source, update dependencies.html, update android-properties, and push to central Maven repository (based on
instructions from <a href="https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide">Sonatype OSS Maven Repository Usage Guide</a>):<pre>
cd /tmp
rm -rf google-api-java-client
mkdir google-api-java-client
cd google-api-java-client
hg clone -b 1.14 https://google-api-java-client.googlecode.com/hg/ 1.14
cd 1.14
Consider changing value of $project.http.version and $project.oauth.version variables in pom.xml
mvn project-info-reports:dependencies
cp google-api-client/target/site/dependencies.html google-api-client-assembly/dependencies/dependencies.html
cp google-api-client-android/target/site/dependencies.html google-api-client-assembly/dependencies/android-dependencies.html
cp google-api-client-appengine/target/site/dependencies.html google-api-client-assembly/dependencies/appengine-dependencies.html
cp google-api-client-java6/target/site/dependencies.html google-api-client-assembly/dependencies/java6-dependencies.html
cp google-api-client-servlet/target/site/dependencies.html google-api-client-assembly/dependencies/servlet-dependencies.html
sed s/-SNAPSHOT//g <google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java >/tmp/GoogleUtils.java
cp /tmp/GoogleUtils.java google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java
for filename in google-api-client-assembly/android-properties/*.properties; do newname=`echo $filename | sed -e 's/-SNAPSHOT//g'`; mv $filename $newname; done
Submit the changes for review as usual, using upload.py
hg commit -m "prepare 1.14.0-beta for release"
hg push
mvn clean deploy
mvn release:clean
mvn release:prepare -DautoVersionSubmodules=true -Dtag=1.14.0-beta --batch-mode
mvn release:perform -Darguments=-Dgpg.passphrase=<i>[YOUR GPG PASSPHRASE]</i>
</pre></li>
<li>Release on oss.sonatype.org
<ul>
<li>Log in to <a href="https://oss.sonatype.org">https://oss.sonatype.org</a></li>
<li>Click on "Staging Repositories" and look for the "com.google"
Repository with your username</li>
<li>check box next to uploaded release; click Close; click Close</li>
<li>check box next to uploaded release; click Release; click Release</li>
</ul>
Central Maven repository is synced hourly. Once uploaded onto
repo2.maven.org, it will be found at: <a
href="http://repo2.maven.org/maven2/com/google/api-client/google-api-client/1.14.0-beta/">repo2.maven.org</a>
</li>
<li>Start development of next bug fix version, by replacing <code>1.14.0-beta</code> with the next bug fix version:<pre>
NEXT_VERSION=<i>(next bug fix version 1.14.X-beta)</i>
for filename in google-api-client-assembly/android-properties/*.properties; do newname=`echo $filename | sed -e "s/1.14.0-beta/$NEXT_VERSION/g"`; mv $filename $newname; done
sed s/1.14.0-beta/$NEXT_VERSION/g <jdiff.xml >/tmp/jdiff.xml
sed s/1.14.0-beta/$NEXT_VERSION/g <release.html >/tmp/release.html
sed s/1.14.0-beta/$NEXT_VERSION-SNAPSHOT/g <google-api-client/src/main/java/com/google/api/client/googleapis/GoogleUtils.java >/tmp/GoogleUtils.java
mv /tmp/jdiff.xml /tmp/release.html .
mv /tmp/GoogleUtils.java google-api-client/src/main/java/com/google/api/client/googleapis/
Consider changing value of $project.http.version and $project.oauth.version variables in pom.xml
hg commit -m "start $NEXT_VERSION"
hg push
</pre></li>
<li>Prepare the released library zip file and javadoc
<ul>
<li>Overview: JDiff is a tool for showing the difference between the
JavaDoc of one version of the library vs. the JavaDoc of an old version of
the library. Hence, we will check out the last minor version of the library
into a temporary directory and compare against the JavaDoc of the just
released version of the library, and then hg commit that diff into the
javadoc Hg repository.</li>
</ul><pre>
cd /tmp/google-api-java-client
hg clone https://code.google.com/p/google-api-java-client.javadoc/ javadoc
hg clone https://code.google.com/p/google-api-java-client.wiki/ wiki
hg clone -r 1.13.0-beta https://google-api-java-client.googlecode.com/hg/ 1.13.0-beta
hg clone -r 1.14.0-beta https://google-api-java-client.googlecode.com/hg/ 1.14.0-beta
cd 1.14.0-beta
mvn javadoc:jar install site
cp -R target/site/apidocs ../javadoc/1.14.0-beta
<i>change these constants from jdiff.xml for your environment: JDIFF_HOME,
MAVEN_REPOSITORY_HOME</i>
ant -f jdiff.xml
cd ../javadoc
hg add
PREV_VERSION=<i>(previous bug fix version 1.13.X-beta)</i>
sed s/$PREV_VERSION/1.14.0-beta/g <index.html >/tmp/index.html && mv /tmp/index.html index.html
hg commit -m "1.14.0-beta"
hg push
cd ../wiki
for s in *; do sed s/$PREV_VERSION/1.14.0-beta/g <$s >/tmp/$s && mv /tmp/$s .; done
hg revert --no-backup ReleaseNotes.wiki
<i>edit ReleaseNotes.wiki to add release notes for 1.14.0-beta</i>
hg commit -m "1.14.0-beta"
hg push
</pre></li>
<li><b>WAIT!</b> Don't do the following instructions until after the
library has been uploaded to repo2.maven.org at: <a
href="http://repo2.maven.org/maven2/com/google/api-client/google-api-client/1.14.0-beta/">repo2.maven.org</a></li>
<li>Update to new version on <a
href="http://code.google.com/p/google-api-java-client">http://code.google.com/p/google-api-java-client</a>
<ul>
<li>Upload to <a
href="http://code.google.com/p/google-api-java-client/downloads/entry">http://code.google.com/p/google-api-java-client/downloads/entry</a>
<ul>
<li>Summary: Google API Client Library for Java, version 1.14.0-beta</li>
<li>File:
<code>/tmp/google-api-java-client/1.14.0-beta/google-api-client-assembly/target/google-api-client-1.14.0-beta-java.zip</code></li>
<li>Labels: <code>Type-Archive</code>, <code>OpSys-All</code>, and <code>Featured</code></li>
<li>click Submit file</li>
</ul>
</li>
<li>If it is a bug fix release, deprecate the library from any previous
versions by removing any <code>Featured</code> label and adding the <code>Deprecated</code>
label.</li>
<li>Update the following pages changing any reference from the previous
version to the new version <code>1.14.0-beta</code>:
<ul>
<li><a href="http://code.google.com/p/google-api-java-client/admin">admin</a></li>
<li><a
href="http://code.google.com/p/google-api-java-client/w/edit/Setup">wiki/Setup</a></li>
<li><a
href="http://code.google.com/p/google-api-java-client/w/edit/SampleProgram">wiki/SampleProgram</a></li>
</ul>
</li>
</ul>
</li>
<li><a
href="http://www.blogger.com/post-create.g?blogID=4531100327392916335">New
Post</a> on the <a href="http://google-api-java-client.blogspot.com/">announcement
blog</a> about the new version, including links to <a
href="http://code.google.com/p/google-api-java-client/issues/list?can=1&q=milestone=Version1.14.0%20status=Fixed&colspec=ID%20Type%20Priority%20Summary">new
features and bugs fixed</a>.</li>
</ul>
</body>
</html>
| 0912116-qwqwdfwedwdwq | release.html | HTML | asf20 | 14,417 |
/* You can override this file with your own styles */ | 0912116-qwqwdfwedwdwq | 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-qwqwdfwedwdwq | 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-qwqwdfwedwdwq | 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-qwqwdfwedwdwq | 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/dependencies.html'>dependencies.html</a></li>
<li>google-api-client-android: <a
href='dependencies/android-dependencies.html'>android-dependencies.html</a></li>
<li>google-api-client-appengine: <a
href='dependencies/appengine-dependencies.html'>appengine-dependencies.html</a></li>
<li>google-api-client-servlet: <a
href='dependencies/servlet-dependencies.html'>servlet-dependencies.html</a></li>
<li>google-api-client-java6: <a
href='dependencies/java6-dependencies.html'>java6-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>guava-jdk5-${project.guava.version}.jar</li>
<li>jsr305-${project.jsr305.version}.jar</li>
<li>google-http-client-protobuf-${project.http.version}.jar (when using
protobuf-java)
<ul>
<li>protobuf-java-${project.protobuf-java.version}.jar</li>
</ul>
</li>
<li>google-http-client-gson-${project.http.version}.jar (when using
GSON)
<ul>
<li>gson-${project.gson.version}.jar</li>
</ul>
</li>
<li>google-http-client-jackson-${project.http.version}.jar (when using
Jackson)
<ul>
<li>jackson-core-asl-${project.jackson-core-asl.version}.jar</li>
</ul>
</li>
<li>google-http-client-jackson2-${project.http.version}.jar (when using
Jackson 2)
<ul>
<li>jackson-core-${project.jackson-core2.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 (for SDK >=
1.6)</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-qwqwdfwedwdwq | google-api-client-assembly/readme.html | HTML | 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.extensions.android.accounts;
import com.google.common.base.Preconditions;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
/**
* Account manager wrapper for Google accounts.
*
* @since 1.11
* @author Yaniv Inbar
*/
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-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/accounts/GoogleAccountManager.java | Java | asf20 | 2,648 |
/*
* 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.
*/
/**
* Utilities for Account Manager for Google accounts on Android Eclair (SDK 2.1) and later.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.android.accounts;
| 0912116-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/accounts/package-info.java | Java | asf20 | 989 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.common.base.Preconditions;
import java.io.IOException;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAuthIOException.java | Java | asf20 | 1,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.
*/
/**
* Utilities based on <a href="https://developers.google.com/android/google-play-services/">Google
* Play services</a>.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.android.gms.auth;
| 0912116-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/package-info.java | Java | asf20 | 981 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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 android.app.Activity;
import java.io.IOException;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GooglePlayServicesAvailabilityIOException.java | Java | asf20 | 2,291 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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 android.app.Activity;
import android.content.Intent;
import java.io.IOException;
/**
* 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
*/
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-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/UserRecoverableAuthIOException.java | Java | asf20 | 1,946 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT 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.BackOffPolicy;
import com.google.api.client.http.ExponentialBackOffPolicy;
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.common.base.Preconditions;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import java.io.IOException;
/**
* 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>
*
* @since 1.12
* @author Yaniv Inbar
*/
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;
/**
* @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;
}
/**
* Constructor 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
*/
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());
}
/**
* 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 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 final String getToken() throws IOException, GoogleAuthException {
BackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
while (true) {
try {
return GoogleAuthUtil.getToken(context, accountName, scope);
} catch (IOException e) {
// network or server error, so retry using exponential backoff
long backOffMillis = backOffPolicy.getNextBackOffMillis();
if (backOffMillis == BackOffPolicy.STOP) {
throw e;
}
// sleep
try {
Thread.sleep(backOffMillis);
} catch (InterruptedException e2) {
// ignore
}
}
}
}
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-qwqwdfwedwdwq | google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java | Java | asf20 | 7,804 |
/*
* 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.extensions.servlet.subscriptions.AbstractWebHookServlet;
import com.google.api.client.googleapis.extensions.servlet.subscriptions.WebHookDeliveryMethod;
/**
* Builds delivery method strings for subscribing to notifications via WebHook on AppEngine.
*
* <p>
* Should be used in conjunction with a {@link AbstractWebHookServlet}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
private static final String DELIVERY_METHOD =
new AppEngineWebHookDeliveryMethod("https://example.appspot.com/notifications").build();
...
request.subscribe(DELIVERY_METHOD, ...).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class AppEngineWebHookDeliveryMethod extends WebHookDeliveryMethod {
/**
* Builds delivery method strings for subscribing to notifications via WebHook on AppEngine.
*
* @param callbackUrl The full URL of the registered Notification-Servlet. Should start with
* https://.
*/
public AppEngineWebHookDeliveryMethod(String callbackUrl) {
super(callbackUrl);
getUrl().set("appEngine", "true");
}
@Override
public AppEngineWebHookDeliveryMethod setHost(String host) {
super.setHost(host);
return this;
}
@Override
public AppEngineWebHookDeliveryMethod setPayloadRequested(boolean isPayloadRequested) {
super.setPayloadRequested(isPayloadRequested);
return this;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/AppEngineWebHookDeliveryMethod.java | Java | asf20 | 2,154 |
/*
* 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.
*/
/**
* Support for creating subscriptions and receiving notifications on AppEngine.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.extensions.appengine.subscriptions;
| 0912116-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/package-info.java | Java | asf20 | 998 |
/*
* 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.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
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;
/**
* 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
*/
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(Subscription subscription) throws IOException {
super.removeSubscription(subscription);
memCache.delete(subscription.getSubscriptionId());
}
@Override
public void storeSubscription(Subscription subscription) throws IOException {
super.storeSubscription(subscription);
memCache.put(subscription.getSubscriptionId(), subscription);
}
@Override
public Subscription getSubscription(String subscriptionId) throws IOException {
if (memCache.contains(subscriptionId)) {
return (Subscription) memCache.get(subscriptionId);
}
Subscription subscription = super.getSubscription(subscriptionId);
memCache.put(subscriptionId, subscription, Expiration.byDeltaSeconds(EXPIRATION_TIME));
return subscription;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/CachedAppEngineSubscriptionStore.java | Java | asf20 | 2,704 |
/*
* 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.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
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 com.google.common.collect.Lists;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
/**
* 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
*/
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 Subscription getSubscriptionFromEntity(Entity entity) throws IOException {
Blob serializedSubscription = (Blob) entity.getProperty(FIELD_SUBSCRIPTION);
return deserialize(serializedSubscription, Subscription.class);
}
@Override
public void storeSubscription(Subscription subscription) throws IOException {
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(KIND, subscription.getSubscriptionId());
entity.setProperty(FIELD_SUBSCRIPTION, serialize(subscription));
service.put(entity);
}
@Override
public void removeSubscription(Subscription subscription) throws IOException {
if (subscription == null) {
return;
}
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
service.delete(KeyFactory.createKey(KIND, subscription.getSubscriptionId()));
}
@Override
public List<Subscription> listSubscriptions() throws IOException {
List<Subscription> 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 Subscription 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-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/subscriptions/AppEngineSubscriptionStore.java | Java | asf20 | 5,031 |
/*
* 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.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.appengine.auth.oauth2;
| 0912116-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/auth/oauth2/package-info.java | Java | asf20 | 963 |
/*
* 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.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.appidentity.AppIdentityServiceFailureException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
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>
* 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. */
private final ImmutableList<String> scopes;
/**
* @param scopes OAuth scopes
*/
public AppIdentityCredential(Iterable<String> scopes) {
this(AppIdentityServiceFactory.getAppIdentityService(), ImmutableList.copyOf(scopes));
}
/**
* @param scopes OAuth scopes
*/
public AppIdentityCredential(String... scopes) {
this(AppIdentityServiceFactory.getAppIdentityService(), ImmutableList.copyOf(scopes));
}
/**
* @param appIdentityService App Identity Service that provides the access token
* @param scopes OAuth scopes
*
* @since 1.12
*/
protected AppIdentityCredential(AppIdentityService appIdentityService, List<String> scopes) {
this.appIdentityService = Preconditions.checkNotNull(appIdentityService);
this.scopes = ImmutableList.copyOf(scopes);
}
@Override
public void initialize(HttpRequest request) throws IOException {
request.setInterceptor(this);
}
/**
* Intercept the request by using the access token obtained from the {@link AppIdentityService}.
*
* <p>
* Upgrade warning: in prior version 1.11 {@link AppIdentityServiceFailureException} was wrapped
* with an {@link IOException}, but now it is no longer wrapped because it is a
* {@link RuntimeException}.
* </p>
*/
@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.
*
* @since 1.12
*/
public final List<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. */
private AppIdentityService appIdentityService;
/** OAuth scopes. */
private final ImmutableList<String> scopes;
/**
* Returns an instance of a new builder.
*
* @param scopes OAuth scopes
*/
public Builder(Iterable<String> scopes) {
this.scopes = ImmutableList.copyOf(scopes);
}
/**
* Returns an instance of a new builder.
*
* @param scopes OAuth scopes
*/
public Builder(String... scopes) {
this.scopes = ImmutableList.copyOf(scopes);
}
/**
* Sets the App Identity Service that provides the access token.
* <p>
* If not explicitly set, the {@link AppIdentityServiceFactory#getAppIdentityService()} method
* will be used to provide the App Identity Service.
* </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 setAppIdentityService(AppIdentityService appIdentityService) {
this.appIdentityService = Preconditions.checkNotNull(appIdentityService);
return this;
}
/**
* Returns a new {@link AppIdentityCredential}.
*/
public AppIdentityCredential build() {
AppIdentityService appIdentityService = this.appIdentityService;
if (appIdentityService == null) {
// 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 = AppIdentityServiceFactory.getAppIdentityService();
}
return new AppIdentityCredential(appIdentityService, scopes);
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-appengine/src/main/java/com/google/api/client/googleapis/extensions/appengine/auth/oauth2/AppIdentityCredential.java | Java | asf20 | 6,026 |
<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-qwqwdfwedwdwq | instructions.html | HTML | asf20 | 2,205 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Google OAuth 2.0 utilities that help simplify the authorization flow on Java 6.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
| 0912116-qwqwdfwedwdwq | google-api-client-java6/src/main/java/com/google/api/client/googleapis/extensions/java6/auth/oauth2/package-info.java | Java | asf20 | 980 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import java.io.IOException;
/**
* Google OAuth 2.0 abstract verification code receiver that prompts user to paste the code copied
* from the browser.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
public class GooglePromptReceiver extends AbstractPromptReceiver {
@Override
public String getRedirectUri() throws IOException {
return GoogleOAuthConstants.OOB_REDIRECT_URI;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-java6/src/main/java/com/google/api/client/googleapis/extensions/java6/auth/oauth2/GooglePromptReceiver.java | Java | asf20 | 1,259 |
/*
* 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.
*/
/**
* Support for subscribing to topics and receiving notifications on servlet-based platforms.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.extensions.servlet.subscriptions;
| 0912116-qwqwdfwedwdwq | google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/package-info.java | Java | asf20 | 1,009 |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.googleapis.subscriptions.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
/**
* {@link SubscriptionStore} making use of JDO.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
service.setSubscriptionStore(new JdoSubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class JdoSubscriptionStore implements SubscriptionStore {
/** Persistence manager factory. */
private final PersistenceManagerFactory persistenceManagerFactory;
/**
* @param persistenceManagerFactory persistence manager factory
*/
public JdoSubscriptionStore(PersistenceManagerFactory persistenceManagerFactory) {
this.persistenceManagerFactory = persistenceManagerFactory;
}
/** Container class for storing subscriptions in the JDO DataStore. */
@PersistenceCapable
private static final class StoredSubscription {
@Persistent(serialized = "true")
private Subscription subscription;
@Persistent
@PrimaryKey
private String subscriptionId;
@SuppressWarnings("unused")
StoredSubscription() {
}
/**
* Creates a stored subscription from an existing subscription.
*
* @param s subscription to store
*/
public StoredSubscription(Subscription s) {
setSubscription(s);
}
/**
* Returns the stored subscription.
*/
public Subscription getSubscription() {
return subscription;
}
/**
* Returns the subscription ID.
*/
@SuppressWarnings("unused")
public String getSubscriptionId() {
return subscriptionId;
}
/**
* Changes the subscription stored in this database entry.
*
* @param subscription The new subscription to store
*/
public void setSubscription(Subscription subscription) {
this.subscription = subscription;
this.subscriptionId = subscription.getSubscriptionId();
}
}
public void storeSubscription(Subscription subscription) {
Preconditions.checkNotNull(subscription);
StoredSubscription dbEntry = getStoredSubscription(subscription.getSubscriptionId());
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
// Check if this subscription is being updated or newly created
if (dbEntry != null) {
// Existing entry
dbEntry.setSubscription(subscription);
} else {
// New entry
dbEntry = new StoredSubscription(subscription);
persistenceManager.makePersistent(dbEntry);
}
} finally {
persistenceManager.close();
}
}
public void removeSubscription(Subscription subscription) {
StoredSubscription dbEntry = getStoredSubscription(subscription.getSubscriptionId());
if (dbEntry != null) {
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
persistenceManager.deletePersistent(dbEntry);
} finally {
persistenceManager.close();
}
}
}
@SuppressWarnings("unchecked")
public List<Subscription> listSubscriptions() {
// Copy the results into a db-detached list.
List<Subscription> list = Lists.newArrayList();
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
Query listQuery = persistenceManager.newQuery(StoredSubscription.class);
Iterable<StoredSubscription> resultList = (Iterable<StoredSubscription>) listQuery.execute();
for (StoredSubscription dbEntry : resultList) {
list.add(dbEntry.getSubscription());
}
} finally {
persistenceManager.close();
}
return list;
}
@SuppressWarnings("unchecked")
private StoredSubscription getStoredSubscription(String subscriptionID) {
Iterable<StoredSubscription> results = null;
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
Query getByIDQuery = persistenceManager.newQuery(StoredSubscription.class);
getByIDQuery.setFilter("subscriptionId == idParam");
getByIDQuery.declareParameters("String idParam");
getByIDQuery.setRange(0, 1);
results = (Iterable<StoredSubscription>) getByIDQuery.execute(subscriptionID);
// return the first result
for (StoredSubscription dbEntry : results) {
return dbEntry;
}
return null;
} finally {
persistenceManager.close();
}
}
public Subscription getSubscription(String subscriptionID) {
StoredSubscription dbEntry = getStoredSubscription(subscriptionID);
return dbEntry == null ? null : dbEntry.getSubscription();
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/JdoSubscriptionStore.java | Java | asf20 | 5,756 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.http.GenericUrl;
import com.google.common.base.Preconditions;
/**
* Builds delivery method strings for subscribing to notifications via WebHook.
*
* <p>
* Should be used in conjunction with a {@link AbstractWebHookServlet}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
private static final String DELIVERY_METHOD =
new WebHookDeliveryMethod("https://example.com/notifications").build();
...
request.subscribe(DELIVERY_METHOD, ...).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class WebHookDeliveryMethod {
/** The URL which is being built. */
private GenericUrl url;
/**
* Builds delivery method strings for subscribing to notifications via WebHook.
*
* @param callbackURL The full URL of the registered Notification-Servlet. Should start with
* https://.
*/
public WebHookDeliveryMethod(String callbackURL) {
// Build the Callback URL and verify it.
Preconditions.checkArgument(new GenericUrl(callbackURL).getScheme().equalsIgnoreCase("https"),
"Callback scheme has to be https://");
// Build the Subscription URL. Only the path and query parameters will actually get.
GenericUrl url = new GenericUrl("http://example.com/web_hook");
url.set("url", callbackURL);
this.url = url;
}
/**
* Returns the URL this builder is currently building.
*/
public final GenericUrl getUrl() {
return url;
}
/**
* Builds and returns the resulting delivery method string.
*/
public final String build() {
return url.buildRelativeUrl().substring("/".length());
}
/**
* Gets the host query parameter.
*/
public final String getHost() {
return (String) url.get("host");
}
/**
* Sets the host query parameter.
*
* @param host New value for the host parameter
*/
public WebHookDeliveryMethod setHost(String host) {
url.set("host", host);
return this;
}
/**
* Returns {@code} true if notifications should contain a payload, or {@code false} if only
* invalidations should be received.
*
* <p>
* Default is {@code true}.
* </p>
*/
public final boolean isPayloadRequested() {
return !Boolean.valueOf((String) url.get("invalidate"));
}
/**
* Sets whether notifications should contain a payload, or whether only
* invalidations should be received.
*
* <p>
* Default is {@code true}.
* </p>
*/
public WebHookDeliveryMethod setPayloadRequested(boolean isPayloadRequested) {
url.set("invalidate", String.valueOf(!isPayloadRequested));
return this;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/WebHookDeliveryMethod.java | Java | asf20 | 3,351 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.googleapis.subscriptions.NotificationHeaders;
import com.google.api.client.googleapis.subscriptions.SubscriptionHeaders;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* WebHook-Servlet used in conjunction with the {@link WebHookDeliveryMethod} to receive
* {@link UnparsedNotification}.
*
* <p>
* In order to use this servlet you should create a class inheriting from
* {@link AbstractWebHookServlet} and register the servlet in your web.xml.
* </p>
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
public class NotificationServlet extends AbstractWebHookServlet {
private static final long serialVersionUID = 1L;
{@literal @}Override
protected SubscriptionStore createSubscriptionStore() {
return new CachedAppEngineSubscriptionStore();
}
}
* </pre>
*
* <b>web.xml setup:</b>
*
* <pre>
<servlet>
<servlet-name>NotificationServlet</servlet-name>
<servlet-class>com.mypackage.NotificationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NotificationServlet</servlet-name>
<url-pattern>/notificiations</url-pattern>
</servlet-mapping>
<security-constraint>
<!-- Lift any ACL imposed upon the servlet -->
<web-resource-collection>
<web-resource-name>any</web-resource-name>
<url-pattern>/notifications</url-pattern>
</web-resource-collection>
</security-constraint>
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
public abstract class AbstractWebHookServlet extends HttpServlet {
/**
* Name of header for the ID of the subscription for which you no longer wish to receive
* notifications (used in the response to a WebHook notification).
*/
public static final String UNSUBSCRIBE_HEADER = "X-Goog-Unsubscribe";
/** Subscription store or {@code null} before initialized in {@link #getSubscriptionStore()}. */
private static SubscriptionStore subscriptionStore;
/**
* Used to get access to the subscription store in order to handle incoming notifications.
*/
protected abstract SubscriptionStore createSubscriptionStore();
/** Returns the (cached) subscription store. */
public final SubscriptionStore getSubscriptionStore() {
if (subscriptionStore == null) {
subscriptionStore = createSubscriptionStore();
}
return subscriptionStore;
}
/**
* Responds to a notification with a 200 OK response with the X-Unsubscribe header which causes
* the subscription to be removed.
*/
protected void sendUnsubscribeResponse(
HttpServletResponse resp, UnparsedNotification notification) {
// Subscriptions can be removed by sending an 200 OK with the X-Unsubscribe header.
resp.setStatus(HttpServletResponse.SC_OK);
resp.setHeader(UNSUBSCRIBE_HEADER, notification.getSubscriptionId());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Parse the relevant headers and create an unparsed notification.
String subscriptionId = req.getHeader(SubscriptionHeaders.SUBSCRIPTION_ID);
String topicId = req.getHeader(SubscriptionHeaders.TOPIC_ID);
String topicUri = req.getHeader(SubscriptionHeaders.TOPIC_URI);
String eventType = req.getHeader(NotificationHeaders.EVENT_TYPE_HEADER);
String clientToken = req.getHeader(SubscriptionHeaders.CLIENT_TOKEN);
String messageNumber = req.getHeader(NotificationHeaders.MESSAGE_NUMBER_HEADER);
String changeType = req.getHeader(NotificationHeaders.CHANGED_HEADER);
if (subscriptionId == null || topicId == null || topicUri == null || eventType == null
|| messageNumber == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Notification did not contain all required information.");
return;
}
// Hand over the unparsed notification to the subscription manager.
InputStream contentStream = req.getInputStream();
try {
UnparsedNotification notification = new UnparsedNotification(subscriptionId,
topicId,
topicUri,
clientToken,
Long.valueOf(messageNumber),
eventType,
changeType,
req.getContentType(),
contentStream);
if (!notification.deliverNotification(getSubscriptionStore())) {
sendUnsubscribeResponse(resp, notification);
}
} finally {
contentStream.close();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/AbstractWebHookServlet.java | Java | asf20 | 5,911 |
import time
def yesno(question):
val = raw_input(question + " ")
return val.startswith("y") or val.startswith("Y")
use_pysqlite2 = yesno("Use pysqlite 2.0?")
use_autocommit = yesno("Use autocommit?")
use_executemany= yesno("Use executemany?")
if use_pysqlite2:
from pysqlite2 import dbapi2 as sqlite
else:
import sqlite
def create_db():
con = sqlite.connect(":memory:")
if use_autocommit:
if use_pysqlite2:
con.isolation_level = None
else:
con.autocommit = True
cur = con.cursor()
cur.execute("""
create table test(v text, f float, i integer)
""")
cur.close()
return con
def test():
row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42)
l = []
for i in range(1000):
l.append(row)
con = create_db()
cur = con.cursor()
if sqlite.version_info > (2, 0):
sql = "insert into test(v, f, i) values (?, ?, ?)"
else:
sql = "insert into test(v, f, i) values (%s, %s, %s)"
starttime = time.time()
for i in range(50):
if use_executemany:
cur.executemany(sql, l)
else:
for r in l:
cur.execute(sql, r)
endtime = time.time()
print "elapsed", endtime - starttime
cur.execute("select count(*) from test")
print "rows:", cur.fetchone()[0]
if __name__ == "__main__":
test()
| 0o2batodd-tntlovspenny | benchmarks/insert.py | Python | mit | 1,496 |
import time
def yesno(question):
val = raw_input(question + " ")
return val.startswith("y") or val.startswith("Y")
use_pysqlite2 = yesno("Use pysqlite 2.0?")
if use_pysqlite2:
use_custom_types = yesno("Use custom types?")
use_dictcursor = yesno("Use dict cursor?")
use_rowcursor = yesno("Use row cursor?")
else:
use_tuple = yesno("Use rowclass=tuple?")
if use_pysqlite2:
from pysqlite2 import dbapi2 as sqlite
else:
import sqlite
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
if use_pysqlite2:
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class DictCursor(sqlite.Cursor):
def __init__(self, *args, **kwargs):
sqlite.Cursor.__init__(self, *args, **kwargs)
self.row_factory = dict_factory
class RowCursor(sqlite.Cursor):
def __init__(self, *args, **kwargs):
sqlite.Cursor.__init__(self, *args, **kwargs)
self.row_factory = sqlite.Row
def create_db():
if sqlite.version_info > (2, 0):
if use_custom_types:
con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
sqlite.register_converter("text", lambda x: "<%s>" % x)
else:
con = sqlite.connect(":memory:")
if use_dictcursor:
cur = con.cursor(factory=DictCursor)
elif use_rowcursor:
cur = con.cursor(factory=RowCursor)
else:
cur = con.cursor()
else:
if use_tuple:
con = sqlite.connect(":memory:")
con.rowclass = tuple
cur = con.cursor()
else:
con = sqlite.connect(":memory:")
cur = con.cursor()
cur.execute("""
create table test(v text, f float, i integer)
""")
return (con, cur)
def test():
row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42)
l = []
for i in range(1000):
l.append(row)
con, cur = create_db()
if sqlite.version_info > (2, 0):
sql = "insert into test(v, f, i) values (?, ?, ?)"
else:
sql = "insert into test(v, f, i) values (%s, %s, %s)"
for i in range(50):
cur.executemany(sql, l)
cur.execute("select count(*) as cnt from test")
starttime = time.time()
for i in range(50):
cur.execute("select v, f, i from test")
l = cur.fetchall()
endtime = time.time()
print "elapsed:", endtime - starttime
if __name__ == "__main__":
test()
| 0o2batodd-tntlovspenny | benchmarks/fetch.py | Python | mit | 2,801 |
#!/usr/bin/env python
from pysqlite2.test import test
test()
| 0o2batodd-tntlovspenny | scripts/test-pysqlite | Python | mit | 61 |
from pysqlite2 import dbapi2 as sqlite
import os, threading
def getcon():
#con = sqlite.connect("db", isolation_level=None, timeout=5.0)
con = sqlite.connect(":memory:")
cur = con.cursor()
cur.execute("create table test(i, s)")
for i in range(10):
cur.execute("insert into test(i, s) values (?, 'asfd')", (i,))
con.commit()
cur.close()
return con
def reader(what):
con = getcon()
while 1:
cur = con.cursor()
cur.execute("select i, s from test where i % 1000=?", (what,))
res = cur.fetchall()
cur.close()
con.close()
def appender():
con = getcon()
counter = 0
while 1:
cur = con.cursor()
cur.execute("insert into test(i, s) values (?, ?)", (counter, "foosadfasfasfsfafs"))
#cur.execute("insert into test(foo) values (?)", (counter,))
counter += 1
if counter % 100 == 0:
#print "appender committing", counter
con.commit()
cur.close()
con.close()
def updater():
con = getcon()
counter = 0
while 1:
cur = con.cursor()
counter += 1
if counter % 5 == 0:
cur.execute("update test set s='foo' where i % 50=0")
#print "updater committing", counter
con.commit()
cur.close()
con.close()
def deleter():
con = getcon()
counter = 0
while 1:
cur = con.cursor()
counter += 1
if counter % 5 == 0:
#print "deleter committing", counter
cur.execute("delete from test where i % 20=0")
con.commit()
cur.close()
con.close()
threads = []
for i in range(10):
continue
threads.append(threading.Thread(target=lambda: reader(i)))
for i in range(5):
threads.append(threading.Thread(target=appender))
#threads.append(threading.Thread(target=updater))
#threads.append(threading.Thread(target=deleter))
for t in threads:
t.start()
| 0o2batodd-tntlovspenny | scripts/stress.py | Python | mit | 1,977 |
# Gerhard Haering <gh@gharing.d> is responsible for the hacked version of this
# module.
#
# This is a modified version of the bdist_wininst distutils command to make it
# possible to build installers *with extension modules* on Unix.
"""distutils.command.bdist_wininst
Implements the Distutils 'bdist_wininst' command: create a windows installer
exe-program."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: bdist_wininst.py 59620 2007-12-31 14:47:07Z christian.heimes $"
import sys, os, string
from distutils.core import Command
from distutils.util import get_platform
from distutils.dir_util import create_tree, remove_tree
from distutils.errors import *
from distutils.sysconfig import get_python_version
from distutils import log
class bdist_wininst (Command):
description = "create an executable installer for MS Windows"
user_options = [('bdist-dir=', None,
"temporary directory for creating the distribution"),
('keep-temp', 'k',
"keep the pseudo-installation tree around after " +
"creating the distribution archive"),
('target-version=', None,
"require a specific python version" +
" on the target system"),
('no-target-compile', 'c',
"do not compile .py to .pyc on the target system"),
('no-target-optimize', 'o',
"do not compile .py to .pyo (optimized)"
"on the target system"),
('dist-dir=', 'd',
"directory to put final built distributions in"),
('bitmap=', 'b',
"bitmap to use for the installer instead of python-powered logo"),
('title=', 't',
"title to display on the installer background instead of default"),
('skip-build', None,
"skip rebuilding everything (for testing/debugging)"),
('install-script=', None,
"basename of installation script to be run after"
"installation or before deinstallation"),
('pre-install-script=', None,
"Fully qualified filename of a script to be run before "
"any files are installed. This script need not be in the "
"distribution"),
]
boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
'skip-build']
def initialize_options (self):
self.bdist_dir = None
self.keep_temp = 0
self.no_target_compile = 0
self.no_target_optimize = 0
self.target_version = None
self.dist_dir = None
self.bitmap = None
self.title = None
self.skip_build = 0
self.install_script = None
self.pre_install_script = None
# initialize_options()
def finalize_options (self):
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'wininst')
if not self.target_version:
self.target_version = ""
if not self.skip_build and self.distribution.has_ext_modules():
short_version = get_python_version()
if self.target_version and self.target_version != short_version:
raise DistutilsOptionError, \
"target version can only be %s, or the '--skip_build'" \
" option must be specified" % (short_version,)
self.target_version = short_version
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.install_script:
for script in self.distribution.scripts:
if self.install_script == os.path.basename(script):
break
else:
raise DistutilsOptionError, \
"install_script '%s' not found in scripts" % \
self.install_script
# finalize_options()
def run (self):
# HACK I disabled this check.
if 0 and (sys.platform != "win32" and
(self.distribution.has_ext_modules() or
self.distribution.has_c_libraries())):
raise DistutilsPlatformError \
("distribution contains extensions and/or C libraries; "
"must be compiled on a Windows 32 platform")
if not self.skip_build:
self.run_command('build')
install = self.reinitialize_command('install', reinit_subcommands=1)
install.root = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
install_lib = self.reinitialize_command('install_lib')
# we do not want to include pyc or pyo files
install_lib.compile = 0
install_lib.optimize = 0
if self.distribution.has_ext_modules():
# If we are building an installer for a Python version other
# than the one we are currently running, then we need to ensure
# our build_lib reflects the other Python version rather than ours.
# Note that for target_version!=sys.version, we must have skipped the
# build step, so there is no issue with enforcing the build of this
# version.
target_version = self.target_version
if not target_version:
assert self.skip_build, "Should have already checked this"
target_version = sys.version[0:3]
plat_specifier = ".%s-%s" % (get_platform(), target_version)
build = self.get_finalized_command('build')
build.build_lib = os.path.join(build.build_base,
'lib' + plat_specifier)
# Use a custom scheme for the zip-file, because we have to decide
# at installation time which scheme to use.
for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
value = string.upper(key)
if key == 'headers':
value = value + '/Include/$dist_name'
setattr(install,
'install_' + key,
value)
log.info("installing to %s", self.bdist_dir)
install.ensure_finalized()
# avoid warning of 'install_lib' about installing
# into a directory not in sys.path
sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB'))
install.run()
del sys.path[0]
# And make an archive relative to the root of the
# pseudo-installation tree.
from tempfile import mktemp
archive_basename = mktemp()
fullname = self.distribution.get_fullname()
arcname = self.make_archive(archive_basename, "zip",
root_dir=self.bdist_dir)
# create an exe containing the zip-file
self.create_exe(arcname, fullname, self.bitmap)
if self.distribution.has_ext_modules():
pyversion = get_python_version()
else:
pyversion = 'any'
self.distribution.dist_files.append(('bdist_wininst', pyversion,
self.get_installer_filename(fullname)))
# remove the zip-file again
log.debug("removing temporary file '%s'", arcname)
os.remove(arcname)
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
# run()
def get_inidata (self):
# Return data describing the installation.
lines = []
metadata = self.distribution.metadata
# Write the [metadata] section.
lines.append("[metadata]")
# 'info' will be displayed in the installer's dialog box,
# describing the items to be installed.
info = (metadata.long_description or '') + '\n'
# Escape newline characters
def escape(s):
return string.replace(s, "\n", "\\n")
for name in ["author", "author_email", "description", "maintainer",
"maintainer_email", "name", "url", "version"]:
data = getattr(metadata, name, "")
if data:
info = info + ("\n %s: %s" % \
(string.capitalize(name), escape(data)))
lines.append("%s=%s" % (name, escape(data)))
# The [setup] section contains entries controlling
# the installer runtime.
lines.append("\n[Setup]")
if self.install_script:
lines.append("install_script=%s" % self.install_script)
lines.append("info=%s" % escape(info))
lines.append("target_compile=%d" % (not self.no_target_compile))
lines.append("target_optimize=%d" % (not self.no_target_optimize))
if self.target_version:
lines.append("target_version=%s" % self.target_version)
title = self.title or self.distribution.get_fullname()
lines.append("title=%s" % escape(title))
import time
import distutils
build_info = "Built %s with distutils-%s" % \
(time.ctime(time.time()), distutils.__version__)
lines.append("build_info=%s" % build_info)
return string.join(lines, "\n")
# get_inidata()
def create_exe (self, arcname, fullname, bitmap=None):
import struct
self.mkpath(self.dist_dir)
cfgdata = self.get_inidata()
installer_name = self.get_installer_filename(fullname)
self.announce("creating %s" % installer_name)
if bitmap:
bitmapdata = open(bitmap, "rb").read()
bitmaplen = len(bitmapdata)
else:
bitmaplen = 0
file = open(installer_name, "wb")
file.write(self.get_exe_bytes())
if bitmap:
file.write(bitmapdata)
# Convert cfgdata from unicode to ascii, mbcs encoded
try:
unicode
except NameError:
pass
else:
if isinstance(cfgdata, unicode):
cfgdata = cfgdata.encode("mbcs")
# Append the pre-install script
cfgdata = cfgdata + "\0"
if self.pre_install_script:
script_data = open(self.pre_install_script, "r").read()
cfgdata = cfgdata + script_data + "\n\0"
else:
# empty pre-install script
cfgdata = cfgdata + "\0"
file.write(cfgdata)
# The 'magic number' 0x1234567B is used to make sure that the
# binary layout of 'cfgdata' is what the wininst.exe binary
# expects. If the layout changes, increment that number, make
# the corresponding changes to the wininst.exe sources, and
# recompile them.
header = struct.pack("<iii",
0x1234567B, # tag
len(cfgdata), # length
bitmaplen, # number of bytes in bitmap
)
file.write(header)
file.write(open(arcname, "rb").read())
# create_exe()
def get_installer_filename(self, fullname):
# Factored out to allow overriding in subclasses
if self.target_version:
# if we create an installer for a specific python version,
# it's better to include this in the name
installer_name = os.path.join(self.dist_dir,
"%s.win32-py%s.exe" %
(fullname, self.target_version))
else:
installer_name = os.path.join(self.dist_dir,
"%s.win32.exe" % fullname)
return installer_name
# get_installer_filename()
def get_exe_bytes (self):
from distutils.msvccompiler import get_build_version
# If a target-version other than the current version has been
# specified, then using the MSVC version from *this* build is no good.
# Without actually finding and executing the target version and parsing
# its sys.version, we just hard-code our knowledge of old versions.
# NOTE: Possible alternative is to allow "--target-version" to
# specify a Python executable rather than a simple version string.
# We can then execute this program to obtain any info we need, such
# as the real sys.version string for the build.
cur_version = get_python_version()
if self.target_version and self.target_version != cur_version:
if self.target_version < "2.3":
raise NotImplementedError
elif self.target_version == "2.3":
bv = "6"
elif self.target_version in ("2.4", "2.5"):
bv = "7.1"
elif self.target_version in ("2.6", "2.7"):
bv = "9.0"
else:
raise NotImplementedError
else:
# for current version - use authoritative check.
bv = get_build_version()
# wininst-x.y.exe is in the same directory as this file
directory = os.path.dirname(__file__)
# we must use a wininst-x.y.exe built with the same C compiler
# used for python. XXX What about mingw, borland, and so on?
# The uninstallers need to be available in $PYEXT_CROSS/uninst/*.exe
# Use http://oss.itsystementwicklung.de/hg/pyext_cross_linux_to_win32/
# and copy it alongside your pysqlite checkout.
filename = os.path.join(directory, os.path.join(os.environ["PYEXT_CROSS"], "uninst", "wininst-%s.exe" % bv))
return open(filename, "rb").read()
# class bdist_wininst
| 0o2batodd-tntlovspenny | cross_bdist_wininst.py | Python | mit | 13,886 |
from __future__ import with_statement
from pysqlite2 import dbapi2 as sqlite3
from datetime import datetime, timedelta
import time
def read_modify_write():
# Open connection and create example schema and data.
# In reality, open a database file instead of an in-memory database.
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table test(id integer primary key, data);
insert into test(data) values ('foo');
insert into test(data) values ('bar');
insert into test(data) values ('baz');
""")
# The read part. There are two ways for fetching data using pysqlite.
# 1. "Lazy-reading"
# cur.execute("select ...")
# for row in cur:
# ...
#
# Advantage: Low memory consumption, good for large resultsets, data is
# fetched on demand.
# Disadvantage: Database locked as long as you iterate over cursor.
#
# 2. "Eager reading"
# cur.fetchone() to fetch one row
# cur.fetchall() to fetch all rows
# Advantage: Locks cleared ASAP.
# Disadvantage: fetchall() may build large lists.
cur.execute("select id, data from test where id=?", (2,))
row = cur.fetchone()
# Stupid way to modify the data column.
lst = list(row)
lst[1] = lst[1] + " & more"
# This is the suggested recipe to modify data using pysqlite. We use
# pysqlite's proprietary API to use the connection object as a context
# manager. This is equivalent to the following code:
#
# try:
# cur.execute("...")
# except:
# con.rollback()
# raise
# finally:
# con.commit()
#
# This makes sure locks are cleared - either by commiting or rolling back
# the transaction.
#
# If the rollback happens because of concurrency issues, you just have to
# try again until it succeeds. Much more likely is that the rollback and
# the raised exception happen because of other reasons, though (constraint
# violation, etc.) - don't forget to roll back on errors.
#
# Or use this recipe. It's useful and gets everything done in two lines of
# code.
with con:
cur.execute("update test set data=? where id=?", (lst[1], lst[0]))
def delete_older_than():
# Use detect_types if you want to use date/time types in pysqlite.
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
# With "DEFAULT current_timestamp" we have SQLite fill the timestamp column
# automatically.
cur.executescript("""
create table test(id integer primary key, data, created timestamp default current_timestamp);
""")
with con:
for i in range(3):
cur.execute("insert into test(data) values ('foo')")
time.sleep(1)
# Delete older than certain interval
# SQLite uses UTC time, so we need to create these timestamps in Python, too.
with con:
delete_before = datetime.utcnow() - timedelta(seconds=2)
cur.execute("delete from test where created < ?", (delete_before,))
def modify_insert():
# Use a unique index and the REPLACE command to have the "insert if not
# there, but modify if it is there" pattern. Race conditions are taken care
# of by transactions.
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table test(id integer primary key, name, age);
insert into test(name, age) values ('Adam', 18);
insert into test(name, age) values ('Eve', 21);
create unique index idx_test_data_unique on test(name);
""")
with con:
# Make Adam age 19
cur.execute("replace into test(name, age) values ('Adam', 19)")
# Create new entry
cur.execute("replace into test(name, age) values ('Abel', 3)")
if __name__ == "__main__":
read_modify_write()
delete_older_than()
modify_insert()
| 0o2batodd-tntlovspenny | misc/patterns.py | Python | mit | 3,936 |
#####################################################################
# Makefile originally written by Hans Oesterholt-Dijkema
# Adapted and sanitized by Gerhard Haering for use with the pysqlite
# project.
#
# It works with the free MSVC2003 toolkit as well as with MS Visual
# Studio 2003.
#
# Makefile for SQLITE for use with GNU Make (MinGW/MSYS)
# and the MSVC2003 free toolkit. Expects the MSVC Free SDK
# installed along with the MSVC2003 free toolkit.
#
# Expects $INCLUDE, $LIB, $PATH set right for use with CL.EXE in
# MSYS. NEEDS MSYS for clean: and install:, for making only:
# Works also in the Visual C++ Toolkit 2003 Command Prompt,
# provided %INCLUDE%, %LIB%, %PATH% are set accordingly.
#####################################################################
CL=cl
CLFLAGS=-O2 -Og -G7
LINK=link
PREFIX=$$VCTOOLKITINSTALLDIR
INCINST=$(PREFIX)/include
LIBINST=$(PREFIX)/lib
BININST=$(PREFIX)/bin
SQLITE_OBJ = alter.o analyze.o attach.o auth.o btree.o build.o \
callback.o complete.o date.o \
delete.o expr.o func.o hash.o insert.o \
main.o opcodes.o os.o os_unix.o os_win.o \
pager.o parse.o pragma.o prepare.o printf.o random.o \
select.o table.o tokenize.o trigger.o update.o \
util.o vacuum.o \
vdbe.o vdbeapi.o vdbeaux.o vdbefifo.o vdbemem.o \
where.o utf.o legacy.o loadext.o vtab.o
SQLITE_OBJ = alter.o analyze.o attach.o auth.o btmutex.o btree.o build.o callback.o \
complete.o date.o delete.o expr.o func.o hash.o insert.o journal.o \
legacy.o loadext.o main.o malloc.o mem1.o mem2.o mem3.o mutex.o \
mutex_w32.o opcodes.o os.o os_win.o pager.o parse.o pragma.o prepare.o \
printf.o random.o select.o table.o tokenize.o trigger.o update.o utf.o \
util.o vacuum.o vdbeapi.o vdbeaux.o vdbeblob.o vdbe.o vdbefifo.o vdbemem.o \
vtab.o where.o
SQLITE_PRG_OBJ=shell.o
all: sqlite3.lib
@echo "done"
clean:
rm -f *.dll *.lib *.exp *.exe *.o
sqlite3.exe: sqlite3.dll $(SQLITE_PRG_OBJ)
$(LINK) -OUT:sqlite3.exe $(SQLITE_PRG_OBJ) sqlite3.lib
sqlite3static.lib: $(SQLITE_OBJ)
$(LINK) -LIB -OUT:sqlite3static.lib $(SQLITE_OBJ)
sqlite3.dll: $(SQLITE_OBJ)
$(LINK) -OUT:sqlite3.dll -dll -def:sqlite3.def $(SQLITE_OBJ)
%.o: %.c
$(CL) -c $(CLFLAGS) -Fo$@ $<
| 0o2batodd-tntlovspenny | misc/Makefile | Makefile | mit | 2,369 |
from pysqlite2 import dbapi2 as sqlite3
Cursor = sqlite3.Cursor
class EagerCursor(Cursor):
def __init__(self, con):
Cursor.__init__(self, con)
self.rows = []
self.pos = 0
def execute(self, *args):
sqlite3.Cursor.execute(self, *args)
self.rows = Cursor.fetchall(self)
self.pos = 0
def fetchone(self):
try:
row = self.rows[self.pos]
self.pos += 1
return row
except IndexError:
return None
def fetchmany(self, num=None):
if num is None:
num = self.arraysize
result = self.rows[self.pos:self.pos+num]
self.pos += num
return result
def fetchall(self):
result = self.rows[self.pos:]
self.pos = len(self.rows)
return result
def test():
con = sqlite3.connect(":memory:")
cur = con.cursor(EagerCursor)
cur.execute("create table test(foo)")
cur.executemany("insert into test(foo) values (?)", [(3,), (4,), (5,)])
cur.execute("select * from test")
print cur.fetchone()
print cur.fetchone()
print cur.fetchone()
print cur.fetchone()
print cur.fetchone()
if __name__ == "__main__":
test()
| 0o2batodd-tntlovspenny | misc/eager.py | Python | mit | 1,230 |
/* microprotocols.c - minimalist and non-validating protocols implementation
*
* Copyright (C) 2003-2004 Federico Di Gregorio <fog@debian.org>
*
* This file is part of psycopg and was adapted for pysqlite. Federico Di
* Gregorio gave the permission to use it within pysqlite under the following
* license:
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Python.h>
#include <structmember.h>
#include "cursor.h"
#include "microprotocols.h"
#include "prepare_protocol.h"
/** the adapters registry **/
PyObject *psyco_adapters;
/* pysqlite_microprotocols_init - initialize the adapters dictionary */
int
pysqlite_microprotocols_init(PyObject *dict)
{
/* create adapters dictionary and put it in module namespace */
if ((psyco_adapters = PyDict_New()) == NULL) {
return -1;
}
return PyDict_SetItemString(dict, "adapters", psyco_adapters);
}
/* pysqlite_microprotocols_add - add a reverse type-caster to the dictionary */
int
pysqlite_microprotocols_add(PyTypeObject *type, PyObject *proto, PyObject *cast)
{
PyObject* key;
int rc;
if (proto == NULL) proto = (PyObject*)&pysqlite_PrepareProtocolType;
key = Py_BuildValue("(OO)", (PyObject*)type, proto);
if (!key) {
return -1;
}
rc = PyDict_SetItem(psyco_adapters, key, cast);
Py_DECREF(key);
return rc;
}
/* pysqlite_microprotocols_adapt - adapt an object to the built-in protocol */
PyObject *
pysqlite_microprotocols_adapt(PyObject *obj, PyObject *proto, PyObject *alt)
{
PyObject *adapter, *key;
/* we don't check for exact type conformance as specified in PEP 246
because the pysqlite_PrepareProtocolType type is abstract and there is no
way to get a quotable object to be its instance */
/* look for an adapter in the registry */
key = Py_BuildValue("(OO)", (PyObject*)obj->ob_type, proto);
if (!key) {
return NULL;
}
adapter = PyDict_GetItem(psyco_adapters, key);
Py_DECREF(key);
if (adapter) {
PyObject *adapted = PyObject_CallFunctionObjArgs(adapter, obj, NULL);
return adapted;
}
/* try to have the protocol adapt this object*/
if (PyObject_HasAttrString(proto, "__adapt__")) {
PyObject *adapted = PyObject_CallMethod(proto, "__adapt__", "O", obj);
if (adapted) {
if (adapted != Py_None) {
return adapted;
} else {
Py_DECREF(adapted);
}
}
if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_TypeError))
return NULL;
}
/* and finally try to have the object adapt itself */
if (PyObject_HasAttrString(obj, "__conform__")) {
PyObject *adapted = PyObject_CallMethod(obj, "__conform__","O", proto);
if (adapted) {
if (adapted != Py_None) {
return adapted;
} else {
Py_DECREF(adapted);
}
}
if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_TypeError)) {
return NULL;
}
}
/* else set the right exception and return NULL */
PyErr_SetString(pysqlite_ProgrammingError, "can't adapt");
return NULL;
}
/** module-level functions **/
PyObject *
pysqlite_adapt(pysqlite_Cursor *self, PyObject *args)
{
PyObject *obj, *alt = NULL;
PyObject *proto = (PyObject*)&pysqlite_PrepareProtocolType;
if (!PyArg_ParseTuple(args, "O|OO", &obj, &proto, &alt)) return NULL;
return pysqlite_microprotocols_adapt(obj, proto, alt);
}
| 0o2batodd-tntlovspenny | src/microprotocols.c | C | mit | 4,357 |