code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.generator;
import com.google.api.client.generator.model.PackageModel;
import java.io.PrintWriter;
import java.util.SortedSet;
/**
* @author Yaniv Inbar
*/
final class PomFileGenerator extends AbstractFileGenerator {
private final SortedSet<PackageModel> pkgs;
PomFileGenerator(SortedSet<PackageModel> pkgs) {
this.pkgs = pkgs;
}
@Override
public void generate(PrintWriter out) {
out.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 "
+ "http://maven.apache.org/maven-v4_0_0.xsd\">");
out.println(" <modelVersion>4.0.0</modelVersion>");
out.println(" <parent>");
out.println(" <groupId>com.google.api.client</groupId>");
out.println(" <artifactId>google-api-client-parent</artifactId>");
out.println(" <version>" + PackageModel.VERSION_SNAPSHOT + "</version>");
out.println(" <relativePath>../../pom.xml</relativePath>");
out.println(" </parent>");
out.println(" <artifactId>google-api-client-modules-parent</artifactId>");
out.println(" <packaging>pom</packaging>");
out.println(" <description>A place to hold common settings for each module.</description>");
out.println(" <modules>");
for (PackageModel pkg : pkgs) {
out.println(" <module>" + pkg.artifactId + "</module>");
}
out.println(" </modules>");
out.println("</project>");
out.close();
}
@Override
public String getOutputFilePath() {
return "modules/pom.xml";
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.generator;
import com.google.api.client.generator.linewrap.LineWrapper;
import java.io.PrintWriter;
/**
* Defines a single file generator, which manages a single generated file.
*
* @author Yaniv Inbar
*/
abstract class AbstractFileGenerator {
/** Whether to generate this file. Default is to return {@code true}. */
boolean isGenerated() {
return true;
}
/** Generates the content of the file into the given print writer. */
abstract void generate(PrintWriter out);
/**
* Returns the output file path relative to the root output directory.
*/
abstract String getOutputFilePath();
/**
* Returns the line wrapper to use or {@code null} for none. Default is to return {@code null}.
*/
LineWrapper getLineWrapper() {
return null;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.generator;
import com.google.api.client.generator.model.PackageModel;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
/**
* @author Yaniv Inbar
*/
public class GeneratePom {
public static void main(String[] args) throws IOException {
File googleApiClientDirectory = Generation.getDirectory(args[0]);
// package names
SortedSet<PackageModel> pkgs = PackageModel.compute(googleApiClientDirectory);
// compute file generators
List<AbstractFileGenerator> fileGenerators = new ArrayList<AbstractFileGenerator>();
fileGenerators.add(new PomFileGenerator(pkgs));
fileGenerators.add(new DistXmlFileGenerator(pkgs));
for (PackageModel pkg : pkgs) {
fileGenerators.add(new ModulePomFileGenerator(pkg));
}
Generation.compute(fileGenerators, googleApiClientDirectory);
}
private GeneratePom() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.appengine;
import com.google.api.client.http.LowLevelHttpTransport;
import com.google.appengine.api.urlfetch.FetchOptions;
import java.io.IOException;
import java.net.HttpURLConnection;
/**
* HTTP low-level transport for Google App Engine based on <a
* href="http://code.google.com/appengine/docs/java/urlfetch/">URL Fetch</a>.
* <p>
* URL Fetch is only available on Google App Engine (not on any other Java environment), and is the
* underlying HTTP transport used for App Engine. Their implementation of {@link HttpURLConnection}
* is simply an abstraction layer on top of URL Fetch. By implementing a transport that directly
* uses URL Fetch, we can optimize the behavior slightly, and can potentially take advantage of
* features in URL Fetch that are not available in {@link HttpURLConnection}. Furthermore, there is
* currently a serious bug in how HTTP headers are processed in the App Engine implementation of
* {@link HttpURLConnection}, which we are able to avoid using this implementation. Therefore, this
* is the recommended transport to use on App Engine.
*
* @since 1.2
* @author Yaniv Inbar
*/
public final class UrlFetchTransport extends LowLevelHttpTransport {
/** Singleton instance of this transport. */
public static final UrlFetchTransport INSTANCE = new UrlFetchTransport();
/**
* Sets the deadline in seconds or {@code null} for no deadline using
* {@link FetchOptions#setDeadline(Double)}. By default it is 20 seconds.
*/
public Double deadline = 20.0;
@Override
public boolean supportsHead() {
return true;
}
@Override
public UrlFetchRequest buildDeleteRequest(String url) throws IOException {
return new UrlFetchRequest(this, "DELETE", url);
}
@Override
public UrlFetchRequest buildGetRequest(String url) throws IOException {
return new UrlFetchRequest(this, "GET", url);
}
@Override
public UrlFetchRequest buildHeadRequest(String url) throws IOException {
return new UrlFetchRequest(this, "HEAD", url);
}
@Override
public UrlFetchRequest buildPostRequest(String url) throws IOException {
return new UrlFetchRequest(this, "POST", url);
}
@Override
public UrlFetchRequest buildPutRequest(String url) throws IOException {
return new UrlFetchRequest(this, "PUT", url);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.appengine;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.ResponseTooLargeException;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
/**
* @author Yaniv Inbar
*/
final class UrlFetchRequest extends LowLevelHttpRequest {
private HttpContent content;
private final UrlFetchTransport transport;
private final HTTPMethod method;
private final HTTPRequest request;
UrlFetchRequest(UrlFetchTransport transport, String requestMethod, String url)
throws IOException {
this.transport = transport;
method = HTTPMethod.valueOf(requestMethod);
FetchOptions options = FetchOptions.Builder.doNotFollowRedirects().disallowTruncate();
request = new HTTPRequest(new URL(url), method, options);
}
@Override
public void addHeader(String name, String value) {
request.addHeader(new HTTPHeader(name, value));
}
@Override
public LowLevelHttpResponse execute() throws IOException {
// write content
if (content != null) {
addHeader("Content-Type", content.getType());
String contentEncoding = content.getEncoding();
if (contentEncoding != null) {
addHeader("Content-Encoding", contentEncoding);
}
long contentLength = content.getLength();
if (contentLength >= 0) {
addHeader("Content-Length", Long.toString(contentLength));
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
content.writeTo(out);
request.setPayload(out.toByteArray());
}
// connect
double deadline = transport.deadline;
if (deadline >= 0) {
request.getFetchOptions().setDeadline(deadline);
}
URLFetchService service = URLFetchServiceFactory.getURLFetchService();
try {
HTTPResponse response = service.fetch(request);
return new UrlFetchResponse(response);
} catch (ResponseTooLargeException e) {
IOException ioException = new IOException();
ioException.initCause(e);
throw ioException;
}
}
@Override
public void setContent(HttpContent content) {
this.content = content;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.appengine;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
final class UrlFetchResponse extends LowLevelHttpResponse {
private final ArrayList<String> headerNames = new ArrayList<String>();
private final ArrayList<String> headerValues = new ArrayList<String>();
private final HTTPResponse fetchResponse;
private String contentEncoding;
private String contentType;
private long contentLength;
UrlFetchResponse(HTTPResponse fetchResponse) {
this.fetchResponse = fetchResponse;
for (HTTPHeader header : fetchResponse.getHeaders()) {
String name = header.getName();
String value = header.getValue();
// Note: URLFetch will merge any duplicate headers with the same key and join their values
// using ", " as separator. However, ", " is also common inside values, such as in Expires or
// Set-Cookie headers.
if (name != null && value != null) {
headerNames.add(name);
headerValues.add(value);
if ("content-type".equalsIgnoreCase(name)) {
contentType = value;
} else if ("content-encoding".equalsIgnoreCase(name)) {
contentEncoding = value;
} else if ("content-length".equalsIgnoreCase(name)) {
try {
contentLength = Long.parseLong(value);
} catch (NumberFormatException e) {
// ignore
}
}
}
}
}
@Override
public int getStatusCode() {
return fetchResponse.getResponseCode();
}
@Override
public InputStream getContent() {
return new ByteArrayInputStream(fetchResponse.getContent());
}
@Override
public String getContentEncoding() {
return contentEncoding;
}
@Override
public long getContentLength() {
return contentLength;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getReasonPhrase() {
// unfortunately not available
return null;
}
@Override
public String getStatusLine() {
// unfortunately not available
return null;
}
@Override
public int getHeaderCount() {
return headerNames.size();
}
@Override
public String getHeaderName(int index) {
return headerNames.get(index);
}
@Override
public String getHeaderValue(int index) {
return headerValues.get(index);
}
}
|
Java
|
/*
* Copyright (c) 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.xml;
import com.google.api.client.util.DataUtil;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.FieldInfo;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* XML namespace dictionary that maps namespace aliases to URI.
* <p>
* Sample usage:
*
* <pre>{@code
static final XmlNamespaceDictionary NAMESPACE_DICTIONARY
= new XmlNamespaceDictionary();
static {
Map<String, String> map = NAMESPACE_DICTIONARY.namespaceAliasToUriMap;
map.put("", "http://www.w3.org/2005/Atom");
map.put("activity", "http://activitystrea.ms/spec/1.0/");
map.put("georss", "http://www.georss.org/georss");
map.put("media", "http://search.yahoo.com/mrss/");
map.put("thr", "http://purl.org/syndication/thread/1.0");
}
*}</pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class XmlNamespaceDictionary {
/**
* Map from XML namespace alias (or {@code ""} for the default namespace) to XML namespace URI.
*/
public final HashMap<String, String> namespaceAliasToUriMap = new HashMap<String, String>();
/**
* Adds a known namespace of the given alias and URI.
*
* @param alias alias
* @param uri namespace URI
*/
public void addNamespace(String alias, String uri) {
if (alias == null || uri == null) {
throw new NullPointerException();
}
HashMap<String, String> namespaceAliasToUriMap = this.namespaceAliasToUriMap;
String knownUri = namespaceAliasToUriMap.get(alias);
if (!uri.equals(knownUri)) {
if (knownUri != null) {
throw new IllegalArgumentException(
"expected namespace alias <" + alias + "> to be <" + knownUri + "> but encountered <"
+ uri + ">");
}
namespaceAliasToUriMap.put(alias, uri);
}
}
/**
* Shows a debug string representation of an element data object of key/value pairs.
*
* @param element element data object ({@link GenericXml}, {@link Map}, or any object with public
* fields)
* @param elementName optional XML element local name prefixed by its namespace alias -- for
* example {@code "atom:entry"} -- or {@code null} to make up something
*/
public String toStringOf(String elementName, Object element) {
try {
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.createSerializer();
serializer.setOutput(writer);
serialize(serializer, elementName, element, false);
return writer.toString();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Shows a debug string representation of an element data object of key/value pairs.
*
* @param element element data object ({@link GenericXml}, {@link Map}, or any object with public
* fields)
* @param elementNamespaceUri XML namespace URI or {@code null} for no namespace
* @param elementLocalName XML local name
* @throws IOException I/O exception
*/
public void serialize(
XmlSerializer serializer, String elementNamespaceUri, String elementLocalName, Object element)
throws IOException {
serialize(serializer, elementNamespaceUri, elementLocalName, element, true);
}
/**
* Shows a debug string representation of an element data object of key/value pairs.
*
* @param element element data object ({@link GenericXml}, {@link Map}, or any object with public
* fields)
* @param elementName XML element local name prefixed by its namespace alias
* @throws IOException I/O exception
*/
public void serialize(XmlSerializer serializer, String elementName, Object element)
throws IOException {
serialize(serializer, elementName, element, true);
}
private void serialize(XmlSerializer serializer, String elementNamespaceUri,
String elementLocalName, Object element, boolean errorOnUnknown) throws IOException {
startDoc(serializer, element, errorOnUnknown, elementNamespaceUri).serialize(
serializer, elementNamespaceUri, elementLocalName);
serializer.endDocument();
}
private void serialize(
XmlSerializer serializer, String elementName, Object element, boolean errorOnUnknown)
throws IOException {
startDoc(serializer, element, errorOnUnknown, null).serialize(serializer, elementName);
serializer.endDocument();
}
private ElementSerializer startDoc(
XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace)
throws IOException {
serializer.startDocument(null, null);
SortedSet<String> aliases = new TreeSet<String>();
computeAliases(element, aliases);
HashMap<String, String> namespaceAliasToUriMap = this.namespaceAliasToUriMap;
boolean foundExtra = extraNamespace == null;
for (String alias : aliases) {
String uri = namespaceAliasToUriMap.get(alias);
serializer.setPrefix(alias, uri);
if (!foundExtra && uri.equals(extraNamespace)) {
foundExtra = true;
}
}
if (!foundExtra) {
for (Map.Entry<String, String> entry : namespaceAliasToUriMap.entrySet()) {
if (extraNamespace.equals(entry.getValue())) {
serializer.setPrefix(entry.getKey(), extraNamespace);
break;
}
}
}
return new ElementSerializer(element, errorOnUnknown);
}
private void computeAliases(Object element, SortedSet<String> aliases) {
for (Map.Entry<String, Object> entry : DataUtil.mapOf(element).entrySet()) {
Object value = entry.getValue();
if (value != null) {
String name = entry.getKey();
if (!"text()".equals(name)) {
int colon = name.indexOf(':');
boolean isAttribute = name.charAt(0) == '@';
if (colon != -1 || !isAttribute) {
String alias = colon == -1 ? "" : name.substring(name.charAt(0) == '@' ? 1 : 0, colon);
aliases.add(alias);
}
if (!isAttribute && !FieldInfo.isPrimitive(value)) {
if (value instanceof Collection<?>) {
for (Object subValue : (Collection<?>) value) {
computeAliases(subValue, aliases);
}
} else {
computeAliases(value, aliases);
}
}
}
}
}
}
class ElementSerializer {
private final boolean errorOnUnknown;
Object textValue = null;
final List<String> attributeNames = new ArrayList<String>();
final List<Object> attributeValues = new ArrayList<Object>();
final List<String> subElementNames = new ArrayList<String>();
final List<Object> subElementValues = new ArrayList<Object>();
ElementSerializer(Object elementValue, boolean errorOnUnknown) {
this.errorOnUnknown = errorOnUnknown;
Class<?> valueClass = elementValue.getClass();
if (FieldInfo.isPrimitive(valueClass)) {
textValue = elementValue;
} else {
for (Map.Entry<String, Object> entry : DataUtil.mapOf(elementValue).entrySet()) {
Object fieldValue = entry.getValue();
if (fieldValue != null) {
String fieldName = entry.getKey();
if ("text()".equals(fieldName)) {
textValue = fieldValue;
} else if (fieldName.charAt(0) == '@') {
attributeNames.add(fieldName.substring(1));
attributeValues.add(fieldValue);
} else {
subElementNames.add(fieldName);
subElementValues.add(fieldValue);
}
}
}
}
}
String getNamespaceUriForAlias(String alias) {
String result = namespaceAliasToUriMap.get(alias);
if (result == null) {
if (errorOnUnknown) {
throw new IllegalArgumentException(
"unrecognized alias: " + (alias.length() == 0 ? "(default)" : alias));
}
return "http://unknown/" + alias;
}
return result;
}
void serialize(XmlSerializer serializer, String elementName) throws IOException {
String elementLocalName = null;
String elementNamespaceUri = null;
if (elementName != null) {
int colon = elementName.indexOf(':');
elementLocalName = elementName.substring(colon + 1);
String alias = colon == -1 ? "" : elementName.substring(0, colon);
elementNamespaceUri = getNamespaceUriForAlias(alias);
if (elementNamespaceUri == null) {
elementNamespaceUri = "http://unknown/" + alias;
}
}
serialize(serializer, elementNamespaceUri, elementLocalName);
}
void serialize(XmlSerializer serializer, String elementNamespaceUri, String elementLocalName)
throws IOException {
boolean errorOnUnknown = this.errorOnUnknown;
if (elementLocalName == null) {
if (errorOnUnknown) {
throw new IllegalArgumentException("XML name not specified");
}
elementLocalName = "unknownName";
}
serializer.startTag(elementNamespaceUri, elementLocalName);
// attributes
List<String> attributeNames = this.attributeNames;
List<Object> attributeValues = this.attributeValues;
int num = attributeNames.size();
for (int i = 0; i < num; i++) {
String attributeName = attributeNames.get(i);
int colon = attributeName.indexOf(':');
String attributeLocalName = attributeName.substring(colon + 1);
String attributeNamespaceUri =
colon == -1 ? null : getNamespaceUriForAlias(attributeName.substring(0, colon));
serializer.attribute(
attributeNamespaceUri, attributeLocalName, toSerializedValue(attributeValues.get(i)));
}
// text
Object textValue = this.textValue;
if (textValue != null) {
serializer.text(toSerializedValue(textValue));
}
// elements
List<String> subElementNames = this.subElementNames;
List<Object> subElementValues = this.subElementValues;
num = subElementNames.size();
for (int i = 0; i < num; i++) {
Object subElementValue = subElementValues.get(i);
String subElementName = subElementNames.get(i);
if (subElementValue instanceof Collection<?>) {
for (Object subElement : (Collection<?>) subElementValue) {
new ElementSerializer(subElement, errorOnUnknown).serialize(serializer, subElementName);
}
} else {
new ElementSerializer(subElementValue, errorOnUnknown).serialize(
serializer, subElementName);
}
}
serializer.endTag(elementNamespaceUri, elementLocalName);
}
}
static String toSerializedValue(Object value) {
if (value instanceof Float) {
Float f = (Float) value;
if (f.floatValue() == Float.POSITIVE_INFINITY) {
return "INF";
}
if (f.floatValue() == Float.NEGATIVE_INFINITY) {
return "-INF";
}
}
if (value instanceof Double) {
Double d = (Double) value;
if (d.doubleValue() == Double.POSITIVE_INFINITY) {
return "INF";
}
if (d.doubleValue() == Double.NEGATIVE_INFINITY) {
return "-INF";
}
}
if (value instanceof String || value instanceof Number || value instanceof Boolean) {
return value.toString();
}
if (value instanceof DateTime) {
return ((DateTime) value).toStringRfc3339();
}
throw new IllegalArgumentException("unrecognized value type: " + value.getClass());
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
/**
* Factory for creating new XML pull parsers and XML serializers.
*
* @since 1.0
* @author Yaniv Inbar
*/
public interface XmlParserFactory {
/**
* Creates a new XML pull parser.
*
* @throws XmlPullParserException if parser could not be created
*/
XmlPullParser createParser() throws XmlPullParserException;
/**
* Creates a new XML serializer.
*
* @throws XmlPullParserException if serializer could not be created
*/
XmlSerializer createSerializer() throws XmlPullParserException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
/**
* Serializes XML HTTP content based on the data key/value mapping object for an item.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request,
* XmlNamespaceDictionary namespaceDictionary, String elementName,
* Object data) {
* XmlHttpContent content = new XmlHttpContent();
* content.namespaceDictionary = namespaceDictionary;
* content.elementName = elementName;
* content.data = data;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class XmlHttpContent extends AbstractXmlHttpContent {
/**
* XML element local name, optionally prefixed by its namespace alias, for example {@code
* "atom:entry"}.
*/
public String elementName;
/** Key/value pair data. */
public Object data;
@Override
public final void writeTo(XmlSerializer serializer) throws IOException {
namespaceDictionary.serialize(serializer, elementName, data);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml;
import com.google.api.client.http.HttpContent;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.io.OutputStream;
/**
* Abstract serializer for XML HTTP content based on the data key/value mapping object for an item.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class AbstractXmlHttpContent implements HttpContent {
/**
* Content type. Default value is {@link XmlHttpParser#CONTENT_TYPE}, though subclasses may define
* a different default value.
*/
public String contentType = XmlHttpParser.CONTENT_TYPE;
/** XML namespace dictionary. */
public XmlNamespaceDictionary namespaceDictionary;
/** Default implementation returns {@code null}, but subclasses may override. */
public String getEncoding() {
return null;
}
/** Default implementation returns {@code -1}, but subclasses may override. */
public long getLength() {
return -1;
}
public final String getType() {
return contentType;
}
public final void writeTo(OutputStream out) throws IOException {
XmlSerializer serializer = Xml.createSerializer();
serializer.setOutput(out, "UTF-8");
writeTo(serializer);
}
protected abstract void writeTo(XmlSerializer serializer) throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml;
import com.google.api.client.http.HttpParser;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.ClassInfo;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
/**
* XML HTTP parser into an data class of key/value pairs.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setParser(HttpTransport transport) {
* XmlHttpParser parser = new XmlHttpParser();
* parser.namespaceDictionary = NAMESPACE_DICTIONARY;
* transport.addParser(parser);
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class XmlHttpParser implements HttpParser {
/** {@code "application/xml"} content type. */
public static final String CONTENT_TYPE = "application/xml";
/** Content type. Default value is {@link #CONTENT_TYPE}. */
public String contentType = CONTENT_TYPE;
/** XML namespace dictionary. */
public XmlNamespaceDictionary namespaceDictionary;
public final String getContentType() {
return contentType;
}
/**
* Default implementation parses the content of the response into the data class of key/value
* pairs, but subclasses may override.
*/
public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException {
InputStream content = response.getContent();
try {
T result = ClassInfo.newInstance(dataClass);
XmlPullParser parser = Xml.createParser();
parser.setInput(content, null);
Xml.parseElement(parser, result, namespaceDictionary, null);
return result;
} catch (XmlPullParserException e) {
IOException exception = new IOException();
exception.initCause(e);
throw exception;
} finally {
content.close();
}
}
}
|
Java
|
package com.google.api.client.xml;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
/**
* XML utilities.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class Xml {
/** XML Parser factory. */
public static XmlParserFactory parserFactory;
/** Returns the parser factory. */
private static XmlParserFactory getParserFactory() throws XmlPullParserException {
XmlParserFactory parserFactory = Xml.parserFactory;
if (parserFactory == null) {
parserFactory = Xml.parserFactory = DefaultXmlParserFactory.getInstance();
}
return parserFactory;
}
/**
* Returns a new XML serializer.
*
* @throws IllegalArgumentException if encountered an {@link XmlPullParserException}
*/
public static XmlSerializer createSerializer() {
try {
return getParserFactory().createSerializer();
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(e);
}
}
/** Returns a new XML pull parser. */
public static XmlPullParser createParser() throws XmlPullParserException {
XmlPullParser result = getParserFactory().createParser();
if (!result.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES)) {
throw new IllegalStateException("XML pull parser must have " + "namespace-aware feature");
}
// TODO: make the XML pull parser secure
return result;
}
/**
* Shows a debug string representation of an element data object of key/value pairs.
* <p>
* It will make up something for the element name and XML namespaces. If those are known, it is
* better to use {@link XmlNamespaceDictionary#toStringOf(String, Object)}.
*
* @param element element data object of key/value pairs ({@link GenericXml}, {@link Map}, or any
* object with public fields)
*/
public static String toStringOf(Object element) {
return new XmlNamespaceDictionary().toStringOf(null, element);
}
private static void parseValue(String stringValue,
Field field,
Object destination,
GenericXml genericXml,
Map<String, Object> destinationMap,
String name) {
if (field == null) {
if (genericXml != null) {
genericXml.set(name, parseValue(stringValue, null));
} else if (destinationMap != null) {
destinationMap.put(name, parseValue(stringValue, null));
}
} else {
Class<?> fieldClass = field.getType();
if (Modifier.isFinal(field.getModifiers()) && !FieldInfo.isPrimitive(fieldClass)) {
throw new IllegalArgumentException("final sub-element fields are not supported");
}
Object fieldValue = parseValue(stringValue, fieldClass);
FieldInfo.setFieldValue(field, destination, fieldValue);
}
}
/**
* Customizes the behavior of XML parsing. Subclasses may override any methods they need to
* customize behavior.
*/
public static class CustomizeParser {
/**
* Returns whether to stop parsing when reaching the start tag of an XML element before it has
* been processed. Only called if the element is actually being processed. By default, returns
* {@code false}, but subclasses may override.
*
* @param namespace XML element's namespace URI
* @param localName XML element's local name
*/
public boolean stopBeforeStartTag(String namespace, String localName) {
return false;
}
/**
* Returns whether to stop parsing when reaching the end tag of an XML element after it has been
* processed. Only called if the element is actually being processed. By default, returns {@code
* false}, but subclasses may override.
*
* @param namespace XML element's namespace URI
* @param localName XML element's local name
*/
public boolean stopAfterEndTag(String namespace, String localName) {
return false;
}
}
/**
* Parses an XML elment using the given XML pull parser into the given destination object.
* <p>
* Requires the the current event be {@link XmlPullParser#START_TAG} (skipping any initial
* {@link XmlPullParser#START_DOCUMENT}) of the element being parsed. At normal parsing
* completion, the current event will either be {@link XmlPullParser#END_TAG} of the element being
* parsed, or the {@link XmlPullParser#START_TAG} of the requested {@code atom:entry}.
*
* @param parser XML pull parser
* @param destination optional destination object to parser into or {@code null} to ignore XML
* content
* @param namespaceDictionary XML namespace dictionary to store unknown namespaces
* @param customizeParser optional parser customizer or {@code null} for none
*/
public static void parseElement(XmlPullParser parser, Object destination,
XmlNamespaceDictionary namespaceDictionary, CustomizeParser customizeParser)
throws IOException, XmlPullParserException {
parseElementInternal(parser, destination, namespaceDictionary, customizeParser);
}
/**
* Returns whether the customize parser has requested to stop or reached end of document.
* Otherwise, identical to
* {@link #parseElement(XmlPullParser, Object, XmlNamespaceDictionary, CustomizeParser)} .
*/
private static boolean parseElementInternal(XmlPullParser parser, Object destination,
XmlNamespaceDictionary namespaceDictionary, CustomizeParser customizeParser)
throws IOException, XmlPullParserException {
Class<?> destinationClass = destination == null ? null : destination.getClass();
GenericXml genericXml = destination instanceof GenericXml ? (GenericXml) destination : null;
boolean isMap = genericXml == null && destination instanceof Map<?, ?>;
@SuppressWarnings("unchecked")
Map<String, Object> destinationMap = isMap ? (Map<String, Object>) destination : null;
ClassInfo classInfo = isMap || destination == null ? null : ClassInfo.of(destinationClass);
int eventType = parser.getEventType();
if (parser.getEventType() == XmlPullParser.START_DOCUMENT) {
eventType = parser.next();
}
if (eventType != XmlPullParser.START_TAG) {
throw new IllegalArgumentException(
"expected start of XML element, but got something else (event type " + eventType + ")");
}
// generic XML
String prefix = parser.getPrefix();
String alias = prefix == null ? "" : prefix;
namespaceDictionary.addNamespace(alias, parser.getNamespace());
// TODO: can instead just look at the xmlns attributes?
if (genericXml != null) {
genericXml.namespaceDictionary = namespaceDictionary;
String name = parser.getName();
genericXml.name = prefix == null ? name : prefix + ":" + name;
}
// attributes
if (destination != null) {
int attributeCount = parser.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
String attributeName = parser.getAttributeName(i);
String attributePrefix = parser.getAttributePrefix(i);
String attributeNamespace = parser.getAttributeNamespace(i);
if (attributePrefix != null) {
namespaceDictionary.addNamespace(attributePrefix, attributeNamespace);
}
String fieldName = getFieldName(true, attributePrefix, attributeNamespace, attributeName);
Field field = isMap ? null : classInfo.getField(fieldName);
parseValue(parser.getAttributeValue(i),
field,
destination,
genericXml,
destinationMap,
fieldName);
}
}
Field field;
while (true) {
int event = parser.next();
switch (event) {
case XmlPullParser.END_DOCUMENT:
return true;
case XmlPullParser.END_TAG:
return customizeParser != null
&& customizeParser.stopAfterEndTag(parser.getNamespace(), parser.getName());
case XmlPullParser.TEXT:
// parse text content
if (destination != null) {
String textFieldName = "text()";
field = isMap ? null : classInfo.getField(textFieldName);
parseValue(parser.getText(),
field,
destination,
genericXml,
destinationMap,
textFieldName);
}
break;
case XmlPullParser.START_TAG:
if (customizeParser != null
&& customizeParser.stopBeforeStartTag(parser.getNamespace(), parser.getName())) {
return true;
}
if (destination == null) {
int level = 1;
while (level != 0) {
switch (parser.next()) {
case XmlPullParser.END_DOCUMENT:
return true;
case XmlPullParser.START_TAG:
level++;
break;
case XmlPullParser.END_TAG:
level--;
break;
}
}
continue;
}
// element
String fieldName =
getFieldName(false, parser.getPrefix(), parser.getNamespace(), parser.getName());
field = isMap ? null : classInfo.getField(fieldName);
Class<?> fieldClass = field == null ? null : field.getType();
boolean isStopped = false;
if (field == null && !isMap && genericXml == null || field != null
&& FieldInfo.isPrimitive(fieldClass)) {
int level = 1;
while (level != 0) {
switch (parser.next()) {
case XmlPullParser.END_DOCUMENT:
return true;
case XmlPullParser.START_TAG:
level++;
break;
case XmlPullParser.END_TAG:
level--;
break;
case XmlPullParser.TEXT:
if (level == 1) {
parseValue(parser.getText(),
field,
destination,
genericXml,
destinationMap,
fieldName);
}
break;
}
}
} else if (field == null || Map.class.isAssignableFrom(fieldClass)) {
// TODO: handle sub-field type
Map<String, Object> mapValue = ClassInfo.newMapInstance(fieldClass);
isStopped =
parseElementInternal(parser, mapValue, namespaceDictionary, customizeParser);
if (isMap) {
@SuppressWarnings("unchecked")
Collection<Object> list = (Collection<Object>) destinationMap.get(fieldName);
if (list == null) {
list = new ArrayList<Object>(1);
destinationMap.put(fieldName, list);
}
list.add(mapValue);
} else if (field != null) {
FieldInfo.setFieldValue(field, destination, mapValue);
} else {
GenericXml atom = (GenericXml) destination;
@SuppressWarnings("unchecked")
Collection<Object> list = (Collection<Object>) atom.get(fieldName);
if (list == null) {
list = new ArrayList<Object>(1);
atom.set(fieldName, list);
}
list.add(mapValue);
}
} else if (Collection.class.isAssignableFrom(fieldClass)) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue =
(Collection<Object>) FieldInfo.getFieldValue(field, destination);
if (collectionValue == null) {
collectionValue = ClassInfo.newCollectionInstance(fieldClass);
FieldInfo.setFieldValue(field, destination, collectionValue);
}
Object elementValue = null;
// TODO: what about Collection<Object> or Collection<?> or
// Collection<? extends X>?
Class<?> subFieldClass = ClassInfo.getCollectionParameter(field);
if (subFieldClass == null || FieldInfo.isPrimitive(subFieldClass)) {
int level = 1;
while (level != 0) {
switch (parser.next()) {
case XmlPullParser.END_DOCUMENT:
return true;
case XmlPullParser.START_TAG:
level++;
break;
case XmlPullParser.END_TAG:
level--;
break;
case XmlPullParser.TEXT:
if (level == 1 && subFieldClass != null) {
elementValue = parseValue(parser.getText(), subFieldClass);
}
break;
}
}
} else {
elementValue = ClassInfo.newInstance(subFieldClass);
isStopped =
parseElementInternal(parser, elementValue, namespaceDictionary, customizeParser);
}
collectionValue.add(elementValue);
} else {
Object value = ClassInfo.newInstance(fieldClass);
isStopped = parseElementInternal(parser, value, namespaceDictionary, customizeParser);
FieldInfo.setFieldValue(field, destination, value);
}
if (isStopped) {
return true;
}
break;
}
}
}
private static String getFieldName(
boolean isAttribute, String alias, String namespace, String name) {
alias = alias == null ? "" : alias;
StringBuilder buf = new StringBuilder(2 + alias.length() + name.length());
if (isAttribute) {
buf.append('@');
}
if (alias != "") {
buf.append(alias).append(':');
}
return buf.append(name).toString();
}
private static Object parseValue(String stringValue, Class<?> fieldClass) {
if (fieldClass == Double.class || fieldClass == double.class) {
if (stringValue.equals("INF")) {
return new Double(Double.POSITIVE_INFINITY);
}
if (stringValue.equals("-INF")) {
return new Double(Double.NEGATIVE_INFINITY);
}
}
if (fieldClass == Float.class || fieldClass == float.class) {
if (stringValue.equals("INF")) {
return Float.POSITIVE_INFINITY;
}
if (stringValue.equals("-INF")) {
return Float.NEGATIVE_INFINITY;
}
}
return FieldInfo.parsePrimitiveValue(fieldClass, stringValue);
}
private Xml() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
/**
* Abstract base class for an Atom feed parser when the feed type is known in advance.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class AbstractAtomFeedParser<T> {
private boolean feedParsed;
public XmlPullParser parser;
public InputStream inputStream;
public Class<T> feedClass;
public XmlNamespaceDictionary namespaceDictionary;
/**
* Parse the feed and return a new parsed instance of the feed type. This method can be skipped if
* all you want are the items.
*
* @throws XmlPullParserException
*/
public T parseFeed() throws IOException, XmlPullParserException {
boolean close = true;
try {
this.feedParsed = true;
T result = ClassInfo.newInstance(this.feedClass);
Xml.parseElement(
this.parser, result, this.namespaceDictionary, Atom.StopAtAtomEntry.INSTANCE);
close = false;
return result;
} finally {
if (close) {
close();
}
}
}
/**
* Parse the next item in the feed and return a new parsed instanceof of the item type. If there
* is no item to parse, it will return {@code null} and automatically close the parser (in which
* case there is no need to call {@link #close()}.
*
* @throws XmlPullParserException
*/
public Object parseNextEntry() throws IOException, XmlPullParserException {
XmlPullParser parser = this.parser;
if (!this.feedParsed) {
this.feedParsed = true;
Xml.parseElement(parser, null, this.namespaceDictionary, Atom.StopAtAtomEntry.INSTANCE);
}
boolean close = true;
try {
if (parser.getEventType() == XmlPullParser.START_TAG) {
Object result = parseEntryInternal();
parser.next();
close = false;
return result;
}
} finally {
if (close) {
close();
}
}
return null;
}
/** Closes the underlying parser. */
public void close() throws IOException {
this.inputStream.close();
}
protected abstract Object parseEntryInternal() throws IOException, XmlPullParserException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.xml.AbstractXmlHttpContent;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
/**
* Serializes Atom XML HTTP content based on the data key/value mapping object for an Atom feed.
* <p>
* Default value for {@link #contentType} is {@link Atom#CONTENT_TYPE}.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request,
* XmlNamespaceDictionary namespaceDictionary, Object feed) {
* AtomFeedContent content = new AtomFeedContent();
* content.namespaceDictionary = namespaceDictionary;
* content.feed = feed;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.1
* @author Yaniv Inbar
*/
public class AtomFeedContent extends AbstractXmlHttpContent {
/** Key/value pair data for the Atom feed. */
public Object feed;
public AtomFeedContent() {
contentType = Atom.CONTENT_TYPE;
}
@Override
public final void writeTo(XmlSerializer serializer) throws IOException {
namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "feed", feed);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
/**
* Atom feed parser when the item class is known in advance.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomFeedParser<T, I> extends AbstractAtomFeedParser<T> {
public Class<I> entryClass;
@SuppressWarnings("unchecked")
@Override
public I parseNextEntry() throws IOException, XmlPullParserException {
return (I) super.parseNextEntry();
}
@Override
protected Object parseEntryInternal() throws IOException, XmlPullParserException {
I result = ClassInfo.newInstance(this.entryClass);
Xml.parseElement(parser, result, namespaceDictionary, null);
return result;
}
public static <T, I> AtomFeedParser<T, I> create(HttpResponse response,
XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<I> entryClass)
throws XmlPullParserException, IOException {
InputStream content = response.getContent();
try {
Atom.checkContentType(response.contentType);
XmlPullParser parser = Xml.createParser();
parser.setInput(content, null);
AtomFeedParser<T, I> result = new AtomFeedParser<T, I>();
result.parser = parser;
result.inputStream = content;
result.feedClass = feedClass;
result.entryClass = entryClass;
result.namespaceDictionary = namespaceDictionary;
content = null;
return result;
} finally {
if (content != null) {
content.close();
}
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.xml.XmlHttpParser;
/**
* Atom XML HTTP parser into an data class of key/value pairs.
* <p>
* It overrides the {@link #contentType} to {@link Atom#CONTENT_TYPE}.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setParser(HttpTransport transport) {
* AtomParser parser = new AtomParser();
* parser.namespaceDictionary = NAMESPACE_DICTIONARY;
* transport.addParser(parser);
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomParser extends XmlHttpParser {
public AtomParser() {
contentType = Atom.CONTENT_TYPE;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.xml.Xml;
/**
* @since 1.0
* @author Yaniv Inbar
*/
public final class Atom {
public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
public static final String CONTENT_TYPE = "application/atom+xml";
static final class StopAtAtomEntry extends Xml.CustomizeParser {
static final StopAtAtomEntry INSTANCE = new StopAtAtomEntry();
@Override
public boolean stopBeforeStartTag(String namespace, String localName) {
return "entry".equals(localName) && ATOM_NAMESPACE.equals(namespace);
}
}
private Atom() {
}
public static void checkContentType(String contentType) {
if (contentType == null || !contentType.startsWith(CONTENT_TYPE)) {
throw new IllegalArgumentException(
"Wrong content type: expected <" + CONTENT_TYPE + "> but got <" + contentType + ">");
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.xml.atom;
import com.google.api.client.xml.AbstractXmlHttpContent;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
/**
* Serializes Atom XML HTTP content based on the data key/value mapping object for an Atom entry.
* <p>
* Default value for {@link #contentType} is {@link Atom#CONTENT_TYPE}.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request,
* XmlNamespaceDictionary namespaceDictionary, Object entry) {
* AtomContent content = new AtomContent();
* content.namespaceDictionary = namespaceDictionary;
* content.entry = entry;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class AtomContent extends AbstractXmlHttpContent {
/** Key/value pair data for the Atom entry. */
public Object entry;
public AtomContent() {
contentType = Atom.CONTENT_TYPE;
}
@Override
public final void writeTo(XmlSerializer serializer) throws IOException {
namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "entry", entry);
}
}
|
Java
|
package com.google.api.client.xml;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
/**
* Generic XML data that stores all unknown key name/value pairs.
* <p>
* Each data key name maps into the name of the XPath expression value for the XML element,
* attribute, or text content (using {@code "text()"}). Subclasses can declare fields for known XML
* content using the {@link Key} annotation. Each field can be of any visibility (private, package
* private, protected, or public) and must not be static. {@code null} unknown data key names are
* not allowed, but {@code null} data values are allowed.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GenericXml extends GenericData implements Cloneable {
/**
* Optional XML element local name prefixed by its namespace alias -- for example {@code
* "atom:entry"} -- or {@code null} if not set.
*/
public String name;
/** Optional namespace dictionary or {@code null} if not set. */
public XmlNamespaceDictionary namespaceDictionary;
@Override
public GenericXml clone() {
return (GenericXml) super.clone();
}
@Override
public String toString() {
XmlNamespaceDictionary namespaceDictionary = this.namespaceDictionary;
if (namespaceDictionary == null) {
namespaceDictionary = new XmlNamespaceDictionary();
}
return namespaceDictionary.toStringOf(name, this);
}
}
|
Java
|
package com.google.api.client.xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
/**
* Default XML parser factory that uses the default specified in {@link XmlPullParserFactory}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class DefaultXmlParserFactory implements XmlParserFactory {
/**
* Only instance or {@code null} if {@link #getInstance()} has not been called.
*/
private static DefaultXmlParserFactory INSTANCE;
/** Returns the only instance of the default XML parser factory. */
public static DefaultXmlParserFactory getInstance() throws XmlPullParserException {
if (INSTANCE == null) {
INSTANCE = new DefaultXmlParserFactory();
}
return INSTANCE;
}
/** XML pull parser factory. */
private final XmlPullParserFactory factory;
private DefaultXmlParserFactory() throws XmlPullParserException {
factory = XmlPullParserFactory.newInstance(
System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
factory.setNamespaceAware(true);
}
public XmlPullParser createParser() throws XmlPullParserException {
return factory.newPullParser();
}
public XmlSerializer createSerializer() throws XmlPullParserException {
return factory.newSerializer();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.escape;
/**
* An object that converts literal text into a format safe for inclusion in a particular context
* (such as an XML document). Typically (but not always), the inverse process of "unescaping" the
* text is performed automatically by the relevant parser.
*
* <p>
* For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
* "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
* resulting XML document is parsed, the parser API will return this text as the original literal
* string {@code "Foo<Bar>"}.
*
* <p>
* An {@code Escaper} instance is required to be stateless, and safe when used concurrently by
* multiple threads.
*
* <p>
* Several popular escapers are defined as constants in the class {@link CharEscapers}.
*
* @since 1.0
*/
public abstract class Escaper {
/**
* Returns the escaped form of a given literal string.
*
* <p>
* Note that this method may treat input characters differently depending on the specific escaper
* implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* correctly, including surrogate character pairs. If the input is badly formed the escaper should
* throw {@link IllegalArgumentException}.
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be
* escaped for any other reason
*/
public abstract String escape(String string);
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.escape;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Utility functions for dealing with {@code CharEscaper}s, and some commonly used {@code
* CharEscaper} instances.
*
* @since 1.0
*/
public final class CharEscapers {
private static final Escaper URI_ESCAPER =
new PercentEscaper(PercentEscaper.SAFECHARS_URLENCODER, true);
private static final Escaper URI_PATH_ESCAPER =
new PercentEscaper(PercentEscaper.SAFEPATHCHARS_URLENCODER, false);
private static final Escaper URI_QUERY_STRING_ESCAPER =
new PercentEscaper(PercentEscaper.SAFEQUERYSTRINGCHARS_URLENCODER, false);
/**
* Escapes the string value so it can be safely included in URIs. For details on escaping URIs,
* see section 2.4 of <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>.
*
* <p>
* When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the
* same.
* <li>The special characters ".", "-", "*", and "_" remain the same.
* <li>The space character " " is converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8 encoding and each
* byte is then represented by the 3-character string "%XY", where "XY" is the two-digit,
* uppercase, hexadecimal representation of the byte value.
* <ul>
*
* <p>
* <b>Note</b>: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt"> RFC 3986</a>:<br> <i>"URI producers and
* normalizers should use uppercase hexadecimal digits for all percent-encodings."</i>
*
* <p>
* This escaper has identical behavior to (but is potentially much faster than):
* <ul>
* <li>{@link java.net.URLEncoder#encode(String, String)} with the encoding name "UTF-8"
* </ul>
*/
public static String escapeUri(String value) {
return URI_ESCAPER.escape(value);
}
/**
* Percent-decodes a US-ASCII string into a Unicode string. UTF-8 encoding is used to determine
* what characters are represented by any consecutive sequences of the form "%<i>XX</i>".
*
* <p>
* This replaces each occurrence of '+' with a space, ' '. So this method should not be used for
* non application/x-www-form-urlencoded strings such as host and path.
*
* @param uri a percent-encoded US-ASCII string
* @return a Unicode string
*/
public static String decodeUri(String uri) {
try {
return URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
// UTF-8 encoding guaranteed to be supported by JVM
throw new RuntimeException(e);
}
}
/**
* Escapes the string value so it can be safely included in URI path segments. For details on
* escaping URIs, see section 2.4 of <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>
* When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the
* same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The subdelimiters "!", "$", "&", "'", "(", ")", "*", ",", ";", and "=" remain the same.
* <li>The space character " " is converted into %20.
* <li>All other characters are converted into one or more bytes using UTF-8 encoding and each
* byte is then represented by the 3-character string "%XY", where "XY" is the two-digit,
* uppercase, hexadecimal representation of the byte value.
* </ul>
*
* <p>
* <b>Note</b>: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt"> RFC 3986</a>:<br> <i>"URI producers and
* normalizers should use uppercase hexadecimal digits for all percent-encodings."</i>
*/
public static String escapeUriPath(String value) {
return URI_PATH_ESCAPER.escape(value);
}
/**
* Escapes the string value so it can be safely included in URI query string segments. When the
* query string consists of a sequence of name=value pairs separated by &, the names and
* values should be individually encoded. If you escape an entire query string in one pass with
* this escaper, then the "=" and "&" characters used as separators will also be escaped.
*
* <p>
* This escaper is also suitable for escaping fragment identifiers.
*
* <p>
* For details on escaping URIs, see section 2.4 of <a
* href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>
* When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the
* same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The path delimiters "/" and "?" remain the same.
* <li>The subdelimiters "!", "$", "'", "(", ")", "*", ",", and ";", remain the same.
* <li>The space character " " is converted into %20.
* <li>The equals sign "=" is converted into %3D.
* <li>The ampersand "&" is converted into %26.
* <li>All other characters are converted into one or more bytes using UTF-8 encoding and each
* byte is then represented by the 3-character string "%XY", where "XY" is the two-digit,
* uppercase, hexadecimal representation of the byte value.
* </ul>
*
* <p>
* <b>Note</b>: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt"> RFC 3986</a>:<br> <i>"URI producers and
* normalizers should use uppercase hexadecimal digits for all percent-encodings."</i>
*/
public static String escapeUriQuery(String value) {
return URI_QUERY_STRING_ESCAPER.escape(value);
}
private CharEscapers() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.escape;
/**
* A {@code UnicodeEscaper} that escapes some set of Java characters using the URI percent encoding
* scheme. The set of safe characters (those which remain unescaped) can be specified on
* construction.
*
* <p>
* For details on escaping URIs for use in web pages, see section 2.4 of <a
* href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>
* When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the
* same.
* <li>Any additionally specified safe characters remain the same.
* <li>If {@code plusForSpace} was specified, the space character " " is converted into a plus sign
* "+".
* <li>All other characters are converted into one or more bytes using UTF-8 encoding and each byte
* is then represented by the 3-character string "%XY", where "XY" is the two-digit, uppercase,
* hexadecimal representation of the byte value.
* </ul>
*
* <p>
* RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!", "~", "*", "'", "(" and
* ")". It goes on to state:
*
* <p>
* <i>Unreserved characters can be escaped without changing the semantics of the URI, but this
* should not be done unless the URI is being used in a context that does not allow the unescaped
* character to appear.</i>
*
* <p>
* For performance reasons the only currently supported character encoding of this class is UTF-8.
*
* <p>
* <b>Note</b>: This escaper produces uppercase hexadecimal sequences. From <a
* href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br> <i>"URI producers and normalizers
* should use uppercase hexadecimal digits for all percent-encodings."</i>
*
* @since 1.0
*/
public class PercentEscaper extends UnicodeEscaper {
/**
* A string of safe characters that mimics the behavior of {@link java.net.URLEncoder}.
*
* TODO: Fix escapers to be compliant with RFC 3986
*/
public static final String SAFECHARS_URLENCODER = "-_.*";
/**
* A string of characters that do not need to be encoded when used in URI path segments, as
* specified in RFC 3986. Note that some of these characters do need to be escaped when used in
* other parts of the URI.
*/
public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;=";
/**
* A string of characters that do not need to be encoded when used in URI query strings, as
* specified in RFC 3986. Note that some of these characters do need to be escaped when used in
* other parts of the URI.
*/
public static final String SAFEQUERYSTRINGCHARS_URLENCODER = "-_.!~*'()@:$,;/?:";
// In some uri escapers spaces are escaped to '+'
private static final char[] URI_ESCAPED_SPACE = {'+'};
private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray();
/**
* If true we should convert space to the {@code +} character.
*/
private final boolean plusForSpace;
/**
* An array of flags where for any {@code char c} if {@code safeOctets[c]} is true then {@code c}
* should remain unmodified in the output. If {@code c > safeOctets.length} then it should be
* escaped.
*/
private final boolean[] safeOctets;
/**
* Constructs a URI escaper with the specified safe characters and optional handling of the space
* character.
*
* @param safeChars a non null string specifying additional safe characters for this escaper (the
* ranges 0..9, a..z and A..Z are always safe and should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +} rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
*/
public PercentEscaper(String safeChars, boolean plusForSpace) {
// Avoid any misunderstandings about the behavior of this escaper
if (safeChars.matches(".*[0-9A-Za-z].*")) {
throw new IllegalArgumentException(
"Alphanumeric characters are always 'safe' and should not be " + "explicitly specified");
}
// Avoid ambiguous parameters. Safe characters are never modified so if
// space is a safe character then setting plusForSpace is meaningless.
if (plusForSpace && safeChars.contains(" ")) {
throw new IllegalArgumentException(
"plusForSpace cannot be specified when space is a 'safe' character");
}
if (safeChars.contains("%")) {
throw new IllegalArgumentException("The '%' character cannot be specified as 'safe'");
}
this.plusForSpace = plusForSpace;
safeOctets = createSafeOctets(safeChars);
}
/**
* Creates a boolean[] with entries corresponding to the character values for 0-9, A-Z, a-z and
* those specified in safeChars set to true. The array is as small as is required to hold the
* given character information.
*/
private static boolean[] createSafeOctets(String safeChars) {
int maxChar = 'z';
char[] safeCharArray = safeChars.toCharArray();
for (char c : safeCharArray) {
maxChar = Math.max(c, maxChar);
}
boolean[] octets = new boolean[maxChar + 1];
for (int c = '0'; c <= '9'; c++) {
octets[c] = true;
}
for (int c = 'A'; c <= 'Z'; c++) {
octets[c] = true;
}
for (int c = 'a'; c <= 'z'; c++) {
octets[c] = true;
}
for (char c : safeCharArray) {
octets[c] = true;
}
return octets;
}
/*
* Overridden for performance. For unescaped strings this improved the performance of the uri
* escaper from ~760ns to ~400ns as measured by {@link CharEscapersBenchmark}.
*/
@Override
protected int nextEscapeIndex(CharSequence csq, int index, int end) {
for (; index < end; index++) {
char c = csq.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
break;
}
}
return index;
}
/*
* Overridden for performance. For unescaped strings this improved the performance of the uri
* escaper from ~400ns to ~170ns as measured by {@link CharEscapersBenchmark}.
*/
@Override
public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
return escapeSlow(s, index);
}
}
return s;
}
/**
* Escapes the given Unicode code point in UTF-8.
*/
@Override
protected char[] escape(int cp) {
// We should never get negative values here but if we do it will throw an
// IndexOutOfBoundsException, so at least it will get spotted.
if (cp < safeOctets.length && safeOctets[cp]) {
return null;
} else if (cp == ' ' && plusForSpace) {
return URI_ESCAPED_SPACE;
} else if (cp <= 0x7F) {
// Single byte UTF-8 characters
// Start with "%--" and fill in the blanks
char[] dest = new char[3];
dest[0] = '%';
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
dest[1] = UPPER_HEX_DIGITS[cp >>> 4];
return dest;
} else if (cp <= 0x7ff) {
// Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff]
// Start with "%--%--" and fill in the blanks
char[] dest = new char[6];
dest[0] = '%';
dest[3] = '%';
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[1] = UPPER_HEX_DIGITS[0xC | cp];
return dest;
} else if (cp <= 0xffff) {
// Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff]
// Start with "%E-%--%--" and fill in the blanks
char[] dest = new char[9];
dest[0] = '%';
dest[1] = 'E';
dest[3] = '%';
dest[6] = '%';
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp];
return dest;
} else if (cp <= 0x10ffff) {
char[] dest = new char[12];
// Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff]
// Start with "%F-%--%--%--" and fill in the blanks
dest[0] = '%';
dest[1] = 'F';
dest[3] = '%';
dest[6] = '%';
dest[9] = '%';
dest[11] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[10] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0x7];
return dest;
} else {
// If this ever happens it is due to bug in UnicodeEscaper, not bad input.
throw new IllegalArgumentException("Invalid unicode character value " + cp);
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.escape;
/**
* Methods factored out so that they can be emulated differently in GWT.
*/
final class Platform {
private Platform() {
}
/** Returns a thread-local 1024-char array. */
// DEST_TL.get() is not null because initialValue() below returns a non-null.
@SuppressWarnings("nullness")
static char[] charBufferFromThreadLocal() {
return DEST_TL.get();
}
/**
* A thread-local destination buffer to keep us from creating new buffers. The starting size is
* 1024 characters. If we grow past this we don't put it back in the threadlocal, we just keep
* going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.escape;
/**
* An {@link Escaper} that converts literal text into a format safe for inclusion in a particular
* context (such as an XML document). Typically (but not always), the inverse process of
* "unescaping" the text is performed automatically by the relevant parser.
*
* <p>
* For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
* "Foo<Bar>"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
* resulting XML document is parsed, the parser API will return this text as the original literal
* string {@code "Foo<Bar>"}.
*
* <p>
* As there are important reasons, including potential security issues, to handle Unicode correctly
* if you are considering implementing a new escaper you should favor using UnicodeEscaper wherever
* possible.
*
* <p>
* A {@code UnicodeEscaper} instance is required to be stateless, and safe when used concurrently by
* multiple threads.
*
* <p>
* Several popular escapers are defined as constants in the class {@link CharEscapers}. To create
* your own escapers extend this class and implement the {@link #escape(int)} method.
*
* @since 1.0
*/
public abstract class UnicodeEscaper extends Escaper {
/** The amount of padding (chars) to use when growing the escape buffer. */
private static final int DEST_PAD = 32;
/**
* Returns the escaped form of the given Unicode code point, or {@code null} if this code point
* does not need to be escaped. When called as part of an escaping operation, the given code point
* is guaranteed to be in the range {@code 0 <= cp <= Character#MAX_CODE_POINT}.
*
* <p>
* If an empty array is returned, this effectively strips the input character from the resulting
* text.
*
* <p>
* If the character does not need to be escaped, this method should return {@code null}, rather
* than an array containing the character representation of the code point. This enables the
* escaping algorithm to perform more efficiently.
*
* <p>
* If the implementation of this method cannot correctly handle a particular code point then it
* should either throw an appropriate runtime exception or return a suitable replacement
* character. It must never silently discard invalid input as this may constitute a security risk.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was needed
*/
protected abstract char[] escape(int cp);
/**
* Scans a sub-sequence of characters from a given {@link CharSequence}, returning the index of
* the next character that requires escaping.
*
* <p>
* <b>Note:</b> When implementing an escaper, it is a good idea to override this method for
* efficiency. The base class implementation determines successive Unicode code points and invokes
* {@link #escape(int)} for each of them. If the semantics of your escaper are such that code
* points in the supplementary range are either all escaped or all unescaped, this method can be
* implemented more efficiently using {@link CharSequence#charAt(int)}.
*
* <p>
* Note however that if your escaper does not escape characters in the supplementary range, you
* should either continue to validate the correctness of any surrogate characters encountered or
* provide a clear warning to users that your escaper does not validate its input.
*
* <p>
* See {@link PercentEscaper} for an example.
*
* @param csq a sequence of characters
* @param start the index of the first character to be scanned
* @param end the index immediately after the last character to be scanned
* @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} contains invalid
* surrogate pairs
*/
protected abstract int nextEscapeIndex(CharSequence csq, int start, int end);
/**
* Returns the escaped form of a given literal string.
*
* <p>
* If you are escaping input in arbitrary successive chunks, then it is not generally safe to use
* this method. If an input string ends with an unmatched high surrogate character, then this
* method will throw {@link IllegalArgumentException}. You should ensure your input is valid <a
* href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this method.
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are encountered
*/
@Override
public abstract String escape(String string);
/**
* Returns the escaped form of a given literal string, starting at the given index. This method is
* called by the {@link #escape(String)} method when it discovers that escaping is required. It is
* protected to allow subclasses to override the fastpath escaping function to inline their
* escaping test.
*
* <p>
* This method is not reentrant and may only be invoked by the top level {@link #escape(String)}
* method.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are encountered
*/
protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = Platform.charBufferFromThreadLocal();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, index, end);
if (cp < 0) {
throw new IllegalArgumentException("Trailing high surrogate at end of input");
}
// It is possible for this to return null because nextEscapeIndex() may
// (for performance reasons) yield some false positives but it must never
// give false negatives.
char[] escaped = escape(cp);
int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
if (escaped != null) {
int charsSkipped = index - unescapedChunkStart;
// This is the size needed to add the replacement, not the full
// size needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + escaped.length;
if (dest.length < sizeNeeded) {
int destLength = sizeNeeded + end - index + DEST_PAD;
dest = growBuffer(dest, destIndex, destLength);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(unescapedChunkStart, index, dest, destIndex);
destIndex += charsSkipped;
}
if (escaped.length > 0) {
System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
destIndex += escaped.length;
}
// If we dealt with an escaped character, reset the unescaped range.
unescapedChunkStart = nextIndex;
}
index = nextEscapeIndex(s, nextIndex, end);
}
// Process trailing unescaped characters - no need to account for escaped
// length or padding the allocation.
int charsSkipped = end - unescapedChunkStart;
if (charsSkipped > 0) {
int endIndex = destIndex + charsSkipped;
if (dest.length < endIndex) {
dest = growBuffer(dest, destIndex, endIndex);
}
s.getChars(unescapedChunkStart, end, dest, destIndex);
destIndex = endIndex;
}
return new String(dest, 0, destIndex);
}
/**
* Returns the Unicode code point of the character at the given index.
*
* <p>
* Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)} this
* method will never fail silently when encountering an invalid surrogate pair.
*
* <p>
* The behaviour of this method is as follows:
* <ol>
* <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
* <li><b>If the character at the specified index is not a surrogate, it is returned.</b>
* <li>If the first character was a high surrogate value, then an attempt is made to read the next
* character.
* <ol>
* <li><b>If the end of the sequence was reached, the negated value of the trailing high surrogate
* is returned.</b>
* <li><b>If the next character was a valid low surrogate, the code point value of the high/low
* surrogate pair is returned.</b>
* <li>If the next character was not a low surrogate value, then {@link IllegalArgumentException}
* is thrown.
* </ol>
* <li>If the first character was a low surrogate value, {@link IllegalArgumentException} is
* thrown.
* </ol>
*
* @param seq the sequence of characters from which to decode the code point
* @param index the index of the first character to decode
* @param end the index beyond the last valid character to decode
* @return the Unicode code point for the given index or the negated value of the trailing high
* surrogate character at the end of the sequence
*/
protected static int codePointAt(CharSequence seq, int index, int end) {
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '" + c2 + "' with value " + (int) c2 + " at index "
+ index);
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c1 + "' with value " + (int) c1 + " at index "
+ (index - 1));
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
}
/**
* Helper method to grow the character buffer as needed, this only happens once in a while so it's
* ok if it's in a method call. If the index passed in is 0 then no copying will be done.
*/
private static char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.javanet;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.LowLevelHttpResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
final class NetHttpResponse extends LowLevelHttpResponse {
private final HttpURLConnection connection;
private final int responseCode;
private final String responseMessage;
private final ArrayList<String> headerNames = new ArrayList<String>();
private final ArrayList<String> headerValues = new ArrayList<String>();
NetHttpResponse(HttpURLConnection connection) throws IOException {
this.connection = connection;
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
List<String> headerNames = this.headerNames;
List<String> headerValues = this.headerValues;
for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
String key = entry.getKey();
if (key != null) {
for (String value : entry.getValue()) {
if (value != null) {
headerNames.add(key);
headerValues.add(value);
}
}
}
}
}
@Override
public int getStatusCode() {
return responseCode;
}
@Override
public InputStream getContent() throws IOException {
HttpURLConnection connection = this.connection;
return HttpResponse.isSuccessStatusCode(responseCode)
? connection.getInputStream() : connection.getErrorStream();
}
@Override
public String getContentEncoding() {
return connection.getContentEncoding();
}
@Override
public long getContentLength() {
String string = connection.getHeaderField("Content-Length");
return string == null ? -1 : Long.parseLong(string);
}
@Override
public String getContentType() {
return connection.getHeaderField("Content-Type");
}
@Override
public String getReasonPhrase() {
return responseMessage;
}
@Override
public String getStatusLine() {
String result = connection.getHeaderField(0);
return result != null && result.startsWith("HTTP/1.") ? result : null;
}
@Override
public int getHeaderCount() {
return headerNames.size();
}
@Override
public String getHeaderName(int index) {
return headerNames.get(index);
}
@Override
public String getHeaderValue(int index) {
return headerValues.get(index);
}
}
|
Java
|
/*
* Copyright (c) 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.javanet;
import com.google.api.client.http.LowLevelHttpTransport;
import java.io.IOException;
import java.net.HttpURLConnection;
/**
* HTTP low-level transport based on the {@code java.net} package.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class NetHttpTransport extends LowLevelHttpTransport {
/** Singleton instance of this transport. */
public static final NetHttpTransport INSTANCE = new NetHttpTransport();
/**
* Sets the connection timeout to a specified timeout in milliseconds by calling
* {@link HttpURLConnection#setConnectTimeout(int)}, or a negative value avoid calling that
* method. By default it is 20 seconds.
*
* @since 1.1
*/
public int connectTimeout = 20 * 1000;
/**
* Sets the read timeout to a specified timeout in milliseconds by calling
* {@link HttpURLConnection#setReadTimeout(int)}, or a negative value avoid calling that method.
* By default it is 20 seconds.
*
* @since 1.1
*/
public int readTimeout = 20 * 1000;
@Override
public boolean supportsHead() {
return true;
}
@Override
public NetHttpRequest buildDeleteRequest(String url) throws IOException {
return new NetHttpRequest(this, "DELETE", url);
}
@Override
public NetHttpRequest buildGetRequest(String url) throws IOException {
return new NetHttpRequest(this, "GET", url);
}
@Override
public NetHttpRequest buildHeadRequest(String url) throws IOException {
return new NetHttpRequest(this, "HEAD", url);
}
@Override
public NetHttpRequest buildPostRequest(String url) throws IOException {
return new NetHttpRequest(this, "POST", url);
}
@Override
public NetHttpRequest buildPutRequest(String url) throws IOException {
return new NetHttpRequest(this, "PUT", url);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.javanet;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author Yaniv Inbar
*/
final class NetHttpRequest extends LowLevelHttpRequest {
private final HttpURLConnection connection;
private HttpContent content;
private final NetHttpTransport transport;
NetHttpRequest(NetHttpTransport transport, String requestMethod, String url) throws IOException {
this.transport = transport;
HttpURLConnection connection =
this.connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(requestMethod);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
}
@Override
public void addHeader(String name, String value) {
connection.addRequestProperty(name, value);
}
@Override
public LowLevelHttpResponse execute() throws IOException {
HttpURLConnection connection = this.connection;
// write content
HttpContent content = this.content;
if (content != null) {
connection.setDoOutput(true);
addHeader("Content-Type", content.getType());
String contentEncoding = content.getEncoding();
if (contentEncoding != null) {
addHeader("Content-Encoding", contentEncoding);
}
long contentLength = content.getLength();
if (contentLength >= 0) {
addHeader("Content-Length", Long.toString(contentLength));
}
content.writeTo(connection.getOutputStream());
}
// connect
NetHttpTransport transport = this.transport;
int readTimeout = transport.readTimeout;
if (readTimeout >= 0) {
connection.setReadTimeout(readTimeout);
}
int connectTimeout = transport.connectTimeout;
if (connectTimeout >= 0) {
connection.setConnectTimeout(connectTimeout);
}
connection.connect();
return new NetHttpResponse(connection);
}
@Override
public void setContent(HttpContent content) {
this.content = content;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.android.xml;
import com.google.api.client.xml.XmlParserFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
/**
* XML parser factory for Android.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AndroidXmlParserFactory implements XmlParserFactory {
public XmlPullParser createParser() {
return Xml.newPullParser();
}
public XmlSerializer createSerializer() {
return Xml.newSerializer();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
import java.net.Proxy;
/**
* Low-level HTTP transport.
* <p>
* This allows providing a different implementation of the HTTP transport that is more compatible
* with the Java environment used.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class LowLevelHttpTransport {
/**
* Returns whether this HTTP transport implementation supports the {@code HEAD} request method.
* <p>
* Default implementation returns {@code false}.
*/
public boolean supportsHead() {
return false;
}
/**
* Returns whether this HTTP transport implementation supports the {@code PATCH} request method.
* <p>
* Default implementation returns {@code false}.
*/
public boolean supportsPatch() {
return false;
}
/**
* Returns whether this HTTP transport implementation supports proxies.
* <p>
* Default implementation returns {@code false}.
*/
public boolean supportsProxy() {
return false;
}
/**
* Builds a {@code DELETE} request.
*
* @param url URL
* @throws IOException I/O exception
*/
public abstract LowLevelHttpRequest buildDeleteRequest(String url) throws IOException;
/**
* Builds a {@code GET} request.
*
* @param url URL
* @throws IOException I/O exception
*/
public abstract LowLevelHttpRequest buildGetRequest(String url) throws IOException;
/**
* Builds a {@code HEAD} request. Won't be called if {@link #supportsHead()} returns {@code false}
* .
* <p>
* Default implementation throws an {@link UnsupportedOperationException}.
*
* @param url URL
* @throws IOException I/O exception
*/
public LowLevelHttpRequest buildHeadRequest(String url) throws IOException {
throw new UnsupportedOperationException();
}
/**
* Builds a {@code PATCH} request. Won't be called if {@link #supportsPatch()} returns
* {@code false}.
* <p>
* Default implementation throws an {@link UnsupportedOperationException}.
*
* @param url URL
* @throws IOException I/O exception
*/
public LowLevelHttpRequest buildPatchRequest(String url) throws IOException {
throw new UnsupportedOperationException();
}
/**
* Builds a {@code POST} request.
*
* @param url URL
* @throws IOException I/O exception
*/
public abstract LowLevelHttpRequest buildPostRequest(String url) throws IOException;
/**
* Builds a {@code PUT} request.
*
* @param url URL
* @throws IOException I/O exception
*/
public abstract LowLevelHttpRequest buildPutRequest(String url) throws IOException;
/**
* Sets a proxy server to use for all the requests.
* <p>
* Default implementation simply ignores the parameters.
*
* @param host Proxy host
* @param port Proxy port
* @param type Proxy type (SOCKS or HTTP)
*/
public void setProxy(String host, int port, Proxy.Type type) {
}
/**
* Removes the proxy server so all the subsequent requests will be made directly again.
* <p>
* Default implementation does nothing.
*/
public void removeProxy() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
/**
* Low-level HTTP request.
* <p>
* This allows providing a different implementation of the HTTP request that is more compatible with
* the Java environment used.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class LowLevelHttpRequest {
/**
* Adds a header to the HTTP request.
* <p>
* Note that multiple headers of the same name need to be supported, in which case
* {@link #addHeader} will be called for each instance of the header.
*
* @param name header name
* @param value header value
*/
public abstract void addHeader(String name, String value);
/**
* Sets the HTTP request content.
*
* @throws IOException
*/
public abstract void setContent(HttpContent content) throws IOException;
/**
* Executes the request and returns a low-level HTTP response object.
*
* @throws IOException
*/
public abstract LowLevelHttpResponse execute() throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Serializes HTTP request content from an input stream into an output stream.
* <p>
* The {@link #type} and {@link #inputStream} fields are required. The input stream is guaranteed to
* be closed at the end of {@link #writeTo(OutputStream)}.
* <p>
* For a file input, use {@link #setFileInput(File)}, and for a byte array or string input use
* {@link #setByteArrayInput(byte[])}.
* <p>
* Sample use with a URL:
*
* <pre>
* <code>
* private static void setRequestJpegContent(HttpRequest request, URL jpegUrl) {
* InputStreamContent content = new InputStreamContent();
* content.inputStream = jpegUrl.openStream();
* content.type = "image/jpeg";
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class InputStreamContent implements HttpContent {
private final static int BUFFER_SIZE = 2048;
/** Required content type. */
public String type;
/** Content length or less than zero if not known. Defaults to {@code -1}. */
public long length = -1;
/** Required input stream to read from. */
public InputStream inputStream;
/**
* Content encoding (for example {@code "gzip"}) or {@code null} for none.
*/
public String encoding;
/**
* Sets the {@link #inputStream} from a file input stream based on the given file, and the
* {@link #length} based on the file's length.
* <p>
* Sample use:
*
* <pre>
* <code>
* private static void setRequestJpegContent(HttpRequest request, File jpegFile) {
* InputStreamContent content = new InputStreamContent();
* content.setFileInput(jpegFile);
* content.type = "image/jpeg";
* request.content = content;
* }
* </code>
* </pre>
*/
public void setFileInput(File file) throws FileNotFoundException {
inputStream = new FileInputStream(file);
length = file.length();
}
/**
* Sets the {@link #inputStream} and {@link #length} from the given byte array.
* <p>
* For string input, call the appropriate {@link String#getBytes} method.
* <p>
* Sample use:
*
* <pre>
* <code>
* private static void setRequestJsonContent(HttpRequest request, String json) {
* InputStreamContent content = new InputStreamContent();
* content.setByteArrayInput(json.getBytes());
* content.type = "application/json";
* request.content = content;
* }
* </code>
* </pre>
*/
public void setByteArrayInput(byte[] content) {
inputStream = new ByteArrayInputStream(content);
length = content.length;
}
public void writeTo(OutputStream out) throws IOException {
InputStream inputStream = this.inputStream;
long contentLength = length;
if (contentLength < 0) {
copy(inputStream, out);
} else {
byte[] buffer = new byte[BUFFER_SIZE];
try {
// consume no more than length
long remaining = contentLength;
while (remaining > 0) {
int read = inputStream.read(buffer, 0, (int) Math.min(BUFFER_SIZE, remaining));
if (read == -1) {
break;
}
out.write(buffer, 0, read);
remaining -= read;
}
} finally {
inputStream.close();
}
}
}
public String getEncoding() {
return encoding;
}
public long getLength() {
return length;
}
public String getType() {
return type;
}
/**
* Writes the content provided by the given source input stream into the given destination output
* stream.
* <p>
* The input stream is guaranteed to be closed at the end of the method.
* </p>
* <p>
* Sample use:
*
* <pre><code>
static void downloadMedia(HttpResponse response, File file)
throws IOException {
FileOutputStream out = new FileOutputStream(file);
try {
InputStreamContent.copy(response.getContent(), out);
} finally {
out.close();
}
}
* </code></pre>
* </p>
*
* @param inputStream source input stream
* @param outputStream destination output stream
* @throws IOException I/O exception
*/
public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
try {
byte[] tmp = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(tmp)) != -1) {
outputStream.write(tmp, 0, bytesRead);
}
} finally {
inputStream.close();
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
/**
* Exception thrown when an error status code is detected in an HTTP response.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class HttpResponseException extends IOException {
static final long serialVersionUID = 1;
/** HTTP response. */
public final HttpResponse response;
/**
* @param response HTTP response
*/
public HttpResponseException(HttpResponse response) {
super(computeMessage(response));
this.response = response;
}
/** Returns an exception message to use for the given HTTP response. */
public static String computeMessage(HttpResponse response) {
String statusMessage = response.statusMessage;
int statusCode = response.statusCode;
if (statusMessage == null) {
return String.valueOf(statusCode);
}
StringBuilder buf = new StringBuilder(4 + statusMessage.length());
return buf.append(statusCode).append(' ').append(statusMessage).toString();
}
}
|
Java
|
package com.google.api.client.http;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
/**
* Serializes MIME Multipart/Related content as specified by <a
* href="http://tools.ietf.org/html/rfc2387">RFC 2387: The MIME Multipart/Related Content-type</a>.
* <p>
* Limitations:
* <ul>
* <li>No support of parameters other than {@code "boundary"}</li>
* <li>No support for specifying headers for each content part</li>
* </ul>
* </p>
* <p>
* Sample usage:
*
* <pre><code>
static void setMediaWithMetadataContent(HttpRequest request,
AtomContent atomContent, InputStreamContent imageContent) {
MultipartRelatedContent content =
MultipartRelatedContent.forRequest(request);
content.parts.add(atomContent);
content.parts.add(imageContent);
}
* </code></pre>
*
* @since 1.1
* @author Yaniv Inbar
*/
public final class MultipartRelatedContent implements HttpContent {
/** Boundary string to use. By default, it is {@code "END_OF_PART"}. */
public String boundary = "END_OF_PART";
/** Collection of HTTP content parts. By default, it is an empty list. */
public Collection<HttpContent> parts = new ArrayList<HttpContent>();
private static final byte[] CR_LF = "\r\n".getBytes();
private static final byte[] CONTENT_TYPE = "Content-Type: ".getBytes();
private static final byte[] CONTENT_TRANSFER_ENCODING =
"Content-Transfer-Encoding: binary".getBytes();
private static final byte[] TWO_DASHES = "--".getBytes();
/**
* Returns a new multi-part content serializer as the content for the given HTTP request.
*
* <p>
* It also sets the {@link HttpHeaders#mimeVersion} of {@link HttpRequest#headers headers} to
* {@code "1.0"}.
* </p>
*
* @param request HTTP request
* @return new multi-part content serializer
*/
public static MultipartRelatedContent forRequest(HttpRequest request) {
MultipartRelatedContent result = new MultipartRelatedContent();
request.headers.mimeVersion = "1.0";
request.content = result;
return result;
}
public void writeTo(OutputStream out) throws IOException {
byte[] END_OF_PART = boundary.getBytes();
out.write(TWO_DASHES);
out.write(END_OF_PART);
for (HttpContent part : parts) {
String contentType = part.getType();
byte[] typeBytes = contentType.getBytes();
out.write(CR_LF);
out.write(CONTENT_TYPE);
out.write(typeBytes);
out.write(CR_LF);
if (!LogContent.isTextBasedContentType(contentType)) {
out.write(CONTENT_TRANSFER_ENCODING);
out.write(CR_LF);
}
out.write(CR_LF);
part.writeTo(out);
out.write(CR_LF);
out.write(TWO_DASHES);
out.write(END_OF_PART);
}
out.write(TWO_DASHES);
out.flush();
}
public String getEncoding() {
return null;
}
public long getLength() {
// TODO: compute this?
return -1;
}
public String getType() {
return "multipart/related; boundary=\"END_OF_PART\"";
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.util.Base64;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
import com.google.api.client.util.Strings;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Stores HTTP headers used in an HTTP request or response, as defined in <a
* href="http://tools.ietf.org/html/rfc2616#section-14">Header Field Definitions</a>.
* <p>
* {@code null} is not allowed as a name or value of a header. Names are case-insensitive.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class HttpHeaders extends GenericData {
/** {@code "Accept"} header. */
@Key("Accept")
public String accept;
/** {@code "Accept-Encoding"} header. By default, this is {@code "gzip"}. */
@Key("Accept-Encoding")
public String acceptEncoding = "gzip";
/** {@code "Authorization"} header. */
@Key("Authorization")
public String authorization;
/** {@code "Cache-Control"} header. */
@Key("Cache-Control")
public String cacheControl;
/** {@code "Content-Encoding"} header. */
@Key("Content-Encoding")
public String contentEncoding;
/** {@code "Content-Length"} header. */
@Key("Content-Length")
public String contentLength;
/** {@code "Content-MD5"} header. */
@Key("Content-MD5")
public String contentMD5;
/** {@code "Content-Range"} header. */
@Key("Content-Range")
public String contentRange;
/** {@code "Content-Type"} header. */
@Key("Content-Type")
public String contentType;
/** {@code "Date"} header. */
@Key("Date")
public String date;
/** {@code "ETag"} header. */
@Key("ETag")
public String etag;
/** {@code "Expires"} header. */
@Key("Expires")
public String expires;
/** {@code "If-Modified-Since"} header. */
@Key("If-Modified-Since")
public String ifModifiedSince;
/** {@code "If-Match"} header. */
@Key("If-Match")
public String ifMatch;
/** {@code "If-None-Match"} header. */
@Key("If-None-Match")
public String ifNoneMatch;
/** {@code "If-Unmodified-Since"} header. */
@Key("If-Unmodified-Since")
public String ifUnmodifiedSince;
/** {@code "Last-Modified"} header. */
@Key("Last-Modified")
public String lastModified;
/** {@code "Location"} header. */
@Key("Location")
public String location;
/** {@code "MIME-Version"} header. */
@Key("MIME-Version")
public String mimeVersion;
/** {@code "Range"} header. */
@Key("Range")
public String range;
/** {@code "Retry-After"} header. */
@Key("Retry-After")
public String retryAfter;
/** {@code "User-Agent"} header. */
@Key("User-Agent")
public String userAgent;
/** {@code "WWW-Authenticate"} header. */
@Key("WWW-Authenticate")
public String authenticate;
@Override
public HttpHeaders clone() {
return (HttpHeaders) super.clone();
}
/**
* Sets the {@link #authorization} header as specified in <a
* href="http://tools.ietf.org/html/rfc2617#section-2">Basic Authentication Scheme</a>.
*
* @since 1.2
*/
public void setBasicAuthentication(String username, String password) {
String encoded =
Strings.fromBytesUtf8(Base64.encode(Strings.toBytesUtf8(username + ":" + password)));
authorization = "Basic " + encoded;
}
/**
* Computes a canonical map from lower-case header name to its values.
*
* @return canonical map from lower-case header name to its values
*/
public Map<String, Collection<Object>> canonicalMap() {
Map<String, Collection<Object>> result = new HashMap<String, Collection<Object>>();
for (Map.Entry<String, Object> entry : entrySet()) {
String canonicalName = entry.getKey().toLowerCase();
if (result.containsKey(canonicalName)) {
throw new IllegalArgumentException(
"multiple headers of the same name (headers are case insensitive): " + canonicalName);
}
Object value = entry.getValue();
if (value != null) {
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
result.put(canonicalName, Collections.unmodifiableCollection(collectionValue));
} else {
result.put(canonicalName, Collections.singleton(value));
}
}
}
return result;
}
/**
* Returns the map from lower-case field name to field name used to allow for case insensitive
* HTTP headers for the given HTTP headers class.
*/
static HashMap<String, String> getFieldNameMap(Class<? extends HttpHeaders> headersClass) {
HashMap<String, String> fieldNameMap = new HashMap<String, String>();
for (String keyName : ClassInfo.of(headersClass).getKeyNames()) {
fieldNameMap.put(keyName.toLowerCase(), keyName);
}
return fieldNameMap;
}
// TODO: override equals and hashCode
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
/**
* Parses HTTP response content into an data class of key/value pairs.
*
* @since 1.0
* @author Yaniv Inbar
*/
public interface HttpParser {
/** Returns the content type. */
String getContentType();
/**
* Parses the given HTTP response into a new instance of the the given data class of key/value
* pairs.
* <p>
* How the parsing is performed is not restricted by this interface, and is instead defined by the
* concrete implementation. Implementations should check {@link HttpResponse#isSuccessStatusCode}
* to know whether they are parsing a success or error response.
*/
<T> T parse(HttpResponse response, Class<T> dataClass) throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.escape.CharEscapers;
import com.google.api.client.util.DataUtil;
import com.google.api.client.util.Strings;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;
/**
* Implements support for HTTP form content encoding serialization of type {@code
* application/x-www-form-urlencoded} as specified in the <a href=
* "http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1">HTML 4.0 Specification</a>.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request, Object item) {
* UrlEncodedContent content = new UrlEncodedContent();
* content.setData(item);
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class UrlEncodedContent implements HttpContent {
/** Content type. Default value is {@link UrlEncodedParser#CONTENT_TYPE}. */
public String contentType = UrlEncodedParser.CONTENT_TYPE;
/** Key/value data or {@code null} for none. */
public Object data;
private byte[] content;
public String getEncoding() {
return null;
}
public long getLength() {
return computeContent().length;
}
public String getType() {
return contentType;
}
public void writeTo(OutputStream out) throws IOException {
out.write(computeContent());
}
private byte[] computeContent() {
if (content == null) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Map.Entry<String, Object> nameValueEntry : DataUtil.mapOf(data).entrySet()) {
Object value = nameValueEntry.getValue();
if (value != null) {
String name = CharEscapers.escapeUri(nameValueEntry.getKey());
if (value instanceof Collection<?>) {
Collection<?> collectionValue = (Collection<?>) value;
for (Object repeatedValue : collectionValue) {
first = appendParam(first, buf, name, repeatedValue);
}
} else {
first = appendParam(first, buf, name, value);
}
}
}
content = Strings.toBytesUtf8(buf.toString());
}
return content;
}
private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value) {
if (first) {
first = false;
} else {
buf.append('&');
}
buf.append(name);
String stringValue = CharEscapers.escapeUri(value.toString());
if (stringValue.length() != 0) {
buf.append('=').append(stringValue);
}
return first;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.escape.CharEscapers;
import com.google.api.client.escape.Escaper;
import com.google.api.client.escape.PercentEscaper;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* URL builder in which the query parameters are specified as generic data key/value pairs, based on
* the specification <a href="http://tools.ietf.org/html/rfc3986">RFC 3986: Uniform Resource
* Identifier (URI)</a>.
* <p>
* The query parameters are specified with the data key name as the parameter name, and the data
* value as the parameter value. Subclasses can declare fields for known query parameters using the
* {@link Key} annotation. {@code null} parameter names are not allowed, but {@code null} query
* values are allowed.
* </p>
* <p>
* Query parameter values are parsed using {@link UrlEncodedParser#parse(String, Object)}.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GenericUrl extends GenericData {
private static final Escaper URI_FRAGMENT_ESCAPER =
new PercentEscaper("=&-_.!~*'()@:$,;/?:", false);
/** Scheme (lowercase), for example {@code "https"}. */
public String scheme;
/** Host, for example {@code "www.google.com"}. */
public String host;
/** Port number or {@code -1} if undefined, for example {@code 443}. */
public int port = -1;
/**
* Decoded path component by parts with each part separated by a {@code '/'} or {@code null} for
* none, for example {@code "/m8/feeds/contacts/default/full"} is represented by {@code "", "m8",
* "feeds", "contacts", "default", "full"}.
* <p>
* Use {@link #appendRawPath(String)} to append to the path, which ensures that no extra slash is
* added.
*/
public List<String> pathParts;
/** Fragment component or {@code null} for none. */
public String fragment;
public GenericUrl() {
}
/**
* Constructs from an encoded URL.
* <p>
* Any known query parameters with pre-defined fields as data keys will be parsed based on their
* data type. Any unrecognized query parameter will always be parsed as a string.
*
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
* @throws IllegalArgumentException if URL has a syntax error
*/
public GenericUrl(String encodedUrl) {
URI uri;
try {
uri = new URI(encodedUrl);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
scheme = uri.getScheme().toLowerCase();
host = uri.getHost();
port = uri.getPort();
pathParts = toPathParts(uri.getRawPath());
fragment = uri.getFragment();
String query = uri.getRawQuery();
if (query != null) {
UrlEncodedParser.parse(query, this);
}
}
@Override
public int hashCode() {
// TODO: optimize?
return build().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj) || !(obj instanceof GenericUrl)) {
return false;
}
GenericUrl other = (GenericUrl) obj;
// TODO: optimize?
return build().equals(other.toString());
}
@Override
public String toString() {
return build();
}
@Override
public GenericUrl clone() {
GenericUrl result = (GenericUrl) super.clone();
result.pathParts = new ArrayList<String>(pathParts);
return result;
}
/**
* Constructs the string representation of the URL, including the path specified by
* {@link #pathParts} and the query parameters specified by this generic URL.
*/
public final String build() {
// scheme, host, port, and path
StringBuilder buf = new StringBuilder();
buf.append(scheme).append("://").append(host);
int port = this.port;
if (port != -1) {
buf.append(':').append(port);
}
List<String> pathParts = this.pathParts;
if (pathParts != null) {
appendRawPathFromParts(buf);
}
// query parameters (similar to UrlEncodedContent)
boolean first = true;
for (Map.Entry<String, Object> nameValueEntry : entrySet()) {
Object value = nameValueEntry.getValue();
if (value != null) {
String name = CharEscapers.escapeUriQuery(nameValueEntry.getKey());
if (value instanceof Collection<?>) {
Collection<?> collectionValue = (Collection<?>) value;
for (Object repeatedValue : collectionValue) {
first = appendParam(first, buf, name, repeatedValue);
}
} else {
first = appendParam(first, buf, name, value);
}
}
}
// URL fragment
String fragment = this.fragment;
if (fragment != null) {
buf.append('#').append(URI_FRAGMENT_ESCAPER.escape(fragment));
}
return buf.toString();
}
/**
* Returns the first query parameter value for the given query parameter name.
*
* @param name query parameter name
* @return first query parameter value
*/
public Object getFirst(String name) {
Object value = get(name);
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
Iterator<Object> iterator = collectionValue.iterator();
return iterator.hasNext() ? iterator.next() : null;
}
return value;
}
/**
* Returns all query parameter values for the given query parameter name.
*
* @param name query parameter name
* @return unmodifiable collection of query parameter values (possibly empty)
*/
public Collection<Object> getAll(String name) {
Object value = get(name);
if (value == null) {
return Collections.emptySet();
}
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
return Collections.unmodifiableCollection(collectionValue);
}
return Collections.singleton(value);
}
/**
* Returns the raw encoded path computed from the {@link #pathParts}.
*
* @return raw encoded path computed from the {@link #pathParts} or {@code null} if
* {@link #pathParts} is {@code null}
*/
public String getRawPath() {
List<String> pathParts = this.pathParts;
if (pathParts == null) {
return null;
}
StringBuilder buf = new StringBuilder();
appendRawPathFromParts(buf);
return buf.toString();
}
/**
* Sets the {@link #pathParts} from the given raw encoded path.
*
* @param encodedPath raw encoded path or {@code null} to set {@link #pathParts} to {@code null}
*/
public void setRawPath(String encodedPath) {
pathParts = toPathParts(encodedPath);
}
/**
* Appends the given raw encoded path to the current {@link #pathParts}, setting field only if it
* is {@code null} or empty.
* <p>
* The last part of the {@link #pathParts} is merged with the first part of the path parts
* computed from the given encoded path. Thus, if the current raw encoded path is {@code "a"}, and
* the given encoded path is {@code "b"}, then the resulting raw encoded path is {@code "ab"}.
*
* @param encodedPath raw encoded path or {@code null} to ignore
*/
public void appendRawPath(String encodedPath) {
if (encodedPath != null && encodedPath.length() != 0) {
List<String> pathParts = this.pathParts;
List<String> appendedPathParts = toPathParts(encodedPath);
if (pathParts == null || pathParts.isEmpty()) {
this.pathParts = appendedPathParts;
} else {
int size = pathParts.size();
pathParts.set(size - 1, pathParts.get(size - 1) + appendedPathParts.get(0));
pathParts.addAll(appendedPathParts.subList(1, appendedPathParts.size()));
}
}
}
/**
* Returns the decoded path parts for the given encoded path.
*
* @param encodedPath slash-prefixed encoded path, for example {@code
* "/m8/feeds/contacts/default/full"}
* @return decoded path parts, with each part assumed to be preceded by a {@code '/'}, for example
* {@code "", "m8", "feeds", "contacts", "default", "full"}, or {@code null} for {@code
* null} or {@code ""} input
*/
public static List<String> toPathParts(String encodedPath) {
if (encodedPath == null || encodedPath.length() == 0) {
return null;
}
List<String> result = new ArrayList<String>();
int cur = 0;
boolean notDone = true;
while (notDone) {
int slash = encodedPath.indexOf('/', cur);
notDone = slash != -1;
String sub;
if (notDone) {
sub = encodedPath.substring(cur, slash);
} else {
sub = encodedPath.substring(cur);
}
result.add(CharEscapers.decodeUri(sub));
cur = slash + 1;
}
return result;
}
private void appendRawPathFromParts(StringBuilder buf) {
List<String> pathParts = this.pathParts;
int size = pathParts.size();
for (int i = 0; i < size; i++) {
String pathPart = pathParts.get(i);
if (i != 0) {
buf.append('/');
}
if (pathPart.length() != 0) {
buf.append(CharEscapers.escapeUriPath(pathPart));
}
}
}
private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value) {
if (first) {
first = false;
buf.append('?');
} else {
buf.append('&');
}
buf.append(name);
String stringValue = CharEscapers.escapeUriQuery(value.toString());
if (stringValue.length() != 0) {
buf.append('=').append(stringValue);
}
return first;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
/**
* Serializes another source of HTTP content using GZip compression.
*
* @author Yaniv Inbar
*/
final class GZipContent implements HttpContent {
private final HttpContent httpContent;
private final String contentType;
/**
* @param httpContent another source of HTTP content
*/
GZipContent(HttpContent httpContent, String contentType) {
this.httpContent = httpContent;
this.contentType = contentType;
}
public void writeTo(OutputStream out) throws IOException {
GZIPOutputStream zipper = new GZIPOutputStream(out);
httpContent.writeTo(zipper);
zipper.finish();
}
public String getEncoding() {
return "gzip";
}
public long getLength() {
return -1;
}
public String getType() {
return contentType;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.escape.CharEscapers;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.GenericData;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
/**
* Implements support for HTTP form content encoding parsing of type {@code
* application/x-www-form-urlencoded} as specified in the <a href=
* "http://www.w3.org/TR/1998/REC-html40-19980424/interact/forms.html#h-17.13.4.1" >HTML 4.0
* Specification</a>.
* <p>
* The data is parsed using {@link #parse(String, Object)}.
* </p>
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setParser(HttpTransport transport) {
* transport.addParser(new UrlEncodedParser());
* }
* </code>
* </pre>
*
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class UrlEncodedParser implements HttpParser {
/** {@code "application/x-www-form-urlencoded"} content type. */
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
/**
* Whether to disable response content logging (unless {@link Level#ALL} is loggable which forces
* all logging).
* <p>
* Useful for example if content has sensitive data such as an authentication token. Defaults to
* {@code false}.
*/
public boolean disableContentLogging;
/** Content type. Default value is {@link #CONTENT_TYPE}. */
public String contentType = CONTENT_TYPE;
public String getContentType() {
return contentType;
}
public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException {
if (disableContentLogging) {
response.disableContentLogging = true;
}
T newInstance = ClassInfo.newInstance(dataClass);
parse(response.parseAsString(), newInstance);
return newInstance;
}
/**
* Parses the given URL-encoded content into the given data object of data key name/value pairs,
* including support for repeating data key names.
*
* <p>
* Declared fields of a "primitive" type (as defined by {@link FieldInfo#isPrimitive(Class)} are
* parsed using {@link FieldInfo#parsePrimitiveValue(Class, String)} where the {@link Class}
* parameter is the declared field class. Declared fields of type {@link Collection} are used to
* support repeating data key names, so each member of the collection is an additional data key
* value. They are parsed the same as "primitive" fields, except that the generic type parameter
* of the collection is used as the {@link Class} parameter.
* </p>
*
* <p>
* If there is no declared field for an input parameter name, it will be ignored unless the input
* {@code data} parameter is a {@link Map}. If it is a map, the parameter value will be stored
* either as a string, or as a {@link ArrayList}<String> in the case of repeated parameters.
* </p>
*
* @param content URL-encoded content
* @param data data key name/value pairs
*/
@SuppressWarnings("unchecked")
public static void parse(String content, Object data) {
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else if (map != null) {
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
/**
* Wraps another source of HTTP content without modifying the content, but also possibly logging
* this content.
*
* <p>
* Content is only logged if {@link Level#CONFIG} is loggable.
*
* @author Yaniv Inbar
*/
final class LogContent implements HttpContent {
private final HttpContent httpContent;
private final String contentType;
private final String contentEncoding;
private final long contentLength;
/**
* @param httpContent another source of HTTP content
*/
LogContent(
HttpContent httpContent, String contentType, String contentEncoding, long contentLength) {
this.httpContent = httpContent;
this.contentType = contentType;
this.contentLength = contentLength;
this.contentEncoding = contentEncoding;
}
public void writeTo(OutputStream out) throws IOException {
ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
httpContent.writeTo(debugStream);
byte[] debugContent = debugStream.toByteArray();
HttpTransport.LOGGER.config(new String(debugContent));
out.write(debugContent);
}
public String getEncoding() {
return contentEncoding;
}
public long getLength() {
return contentLength;
}
public String getType() {
return contentType;
}
/**
* Returns whether the given content type is text rather than binary data.
*
* @param contentType content type or {@code null}
* @return whether it is not {@code null} and text-based
* @since 1.1
*/
public static boolean isTextBasedContentType(String contentType) {
// TODO: refine this further
return contentType != null
&& (contentType.startsWith("text/") || contentType.startsWith("application/"));
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
/**
* HTTP request execute intercepter invoked at the start of {@link HttpRequest#execute()}.
* <p>
* Useful for example for signing HTTP requests during authentication. Care should be taken to
* ensure that intercepters not interfere with each other since there are no guarantees regarding
* their independence. In particular, the order in which the intercepters are invoked is important.
*
* @since 1.0
* @author Yaniv Inbar
*/
public interface HttpExecuteIntercepter {
/**
* Invoked at the start of {@link HttpRequest#execute()}.
*
* @throws IOException any I/O exception
*/
void intercept(HttpRequest request) throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.util.ArrayMap;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* HTTP transport.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class HttpTransport {
static final Logger LOGGER = Logger.getLogger(HttpTransport.class.getName());
/**
* Low level HTTP transport interface to use or {@code null} to use the default as specified in
* {@link #useLowLevelHttpTransport()}.
*/
private static LowLevelHttpTransport lowLevelHttpTransport;
// TODO: lowLevelHttpTransport: system property or environment variable?
/**
* Sets to the given low level HTTP transport.
* <p>
* Must be set before the first HTTP transport is constructed or else the default will be used as
* specified in {@link #useLowLevelHttpTransport()}.
*
* @param lowLevelHttpTransport low level HTTP transport or {@code null} to use the default as
* specified in {@link #useLowLevelHttpTransport()}
*/
public static void setLowLevelHttpTransport(LowLevelHttpTransport lowLevelHttpTransport) {
HttpTransport.lowLevelHttpTransport = lowLevelHttpTransport;
}
/**
* Returns the low-level HTTP transport to use. If
* {@link #setLowLevelHttpTransport(LowLevelHttpTransport)} hasn't been called, it uses the
* default depending on the classpath:
* <ul>
* <li>Google App Engine: uses {@code com.google.api.client.appengine.UrlFetchTransport}</li>
* <li>Apache HTTP Client (e.g. Android): uses {@code
* com.google.api.client.apache.ApacheHttpTransport}</li>
* <li>Otherwise: uses the standard {@code com.google.api.client.javanet.NetHttpTransport}</li>
* </ul>
* <p>
* Warning: prior to version 1.2 the default was always based on {@code
* com.google.api.client.javanet.NetHttpTransport} regardless of environment.
* </p>
*/
public static LowLevelHttpTransport useLowLevelHttpTransport() {
LowLevelHttpTransport lowLevelHttpTransportInterface = HttpTransport.lowLevelHttpTransport;
if (lowLevelHttpTransportInterface == null) {
boolean isAppEngineSdkOnClasspath = false;
try {
// check for Google App Engine
Class.forName("com.google.appengine.api.urlfetch.URLFetchServiceFactory");
isAppEngineSdkOnClasspath = true;
lowLevelHttpTransport =
lowLevelHttpTransportInterface = (LowLevelHttpTransport) Class.forName(
"com.google.api.client.appengine.UrlFetchTransport").getField("INSTANCE").get(null);
} catch (Exception e0) {
boolean isApacheHttpClientOnClasspath = false;
try {
// check for Apache HTTP client
Class.forName("org.apache.http.client.HttpClient");
isApacheHttpClientOnClasspath = true;
lowLevelHttpTransport =
lowLevelHttpTransportInterface =
(LowLevelHttpTransport) Class.forName(
"com.google.api.client.apache.ApacheHttpTransport").getField("INSTANCE").get(
null);
} catch (Exception e1) {
// use standard {@code java.net} transport.
try {
lowLevelHttpTransport =
lowLevelHttpTransportInterface =
(LowLevelHttpTransport) Class.forName(
"com.google.api.client.javanet.NetHttpTransport").getField("INSTANCE").get(
null);
} catch (Exception e2) {
StringBuilder buf =
new StringBuilder("Missing required low-level HTTP transport package.\n");
if (isAppEngineSdkOnClasspath) {
buf.append("For Google App Engine, the required package is "
+ "\"com.google.api.client.appengine\".\n");
}
if (isApacheHttpClientOnClasspath) {
boolean isAndroidOnClasspath = false;
try {
Class.forName("android.util.Log");
isAndroidOnClasspath = true;
} catch (Exception e3) {
}
if (isAndroidOnClasspath) {
buf.append("For Android, the preferred package is "
+ "\"com.google.api.client.apache\".\n");
} else {
buf.append("For Apache HTTP Client, the preferred package is "
+ "\"com.google.api.client.apache\".\n");
}
}
if (isAppEngineSdkOnClasspath || isApacheHttpClientOnClasspath) {
buf.append("Alternatively, use");
} else {
buf.append("Use");
}
buf.append(" package \"com.google.api.client.javanet\".");
throw new IllegalStateException(buf.toString());
}
}
}
if (LOGGER.isLoggable(Level.CONFIG)) {
LOGGER.config("Using low-level HTTP transport: "
+ lowLevelHttpTransportInterface.getClass().getName());
}
}
return lowLevelHttpTransportInterface;
}
/**
* Sets a proxy server for all the subsequent requests.
*
* @param host Proxy host
* @param host Proxy port
* @param host Proxy type (HTTP or SOCKS)
*/
public static void setProxy(String host, int port, Proxy.Type type) {
HttpTransport.useLowLevelHttpTransport().setProxy(host, port, type);
}
/** Removes the proxy settings. */
public static void removeProxy() {
HttpTransport.useLowLevelHttpTransport().removeProxy();
}
/**
* Default HTTP headers. These transport default headers are put into a request's headers when its
* build method is called.
*/
public HttpHeaders defaultHeaders = new HttpHeaders();
/** Map from content type to HTTP parser. */
private final ArrayMap<String, HttpParser> contentTypeToParserMap = ArrayMap.create();
/**
* HTTP request execute intercepters. The intercepters will be invoked in the order of the
* {@link List#iterator()}.
*/
public List<HttpExecuteIntercepter> intercepters = new ArrayList<HttpExecuteIntercepter>(1);
/**
* Adds an HTTP response content parser.
* <p>
* If there is already a previous parser defined for this new parser (as defined by
* {@link #getParser(String)} then the previous parser will be removed.
*/
public void addParser(HttpParser parser) {
String contentType = getNormalizedContentType(parser.getContentType());
contentTypeToParserMap.put(contentType, parser);
}
/**
* Returns the HTTP response content parser to use for the given content type or {@code null} if
* none is defined.
*
* @param contentType content type or {@code null} for {@code null} result
*/
public HttpParser getParser(String contentType) {
if (contentType == null) {
return null;
}
contentType = getNormalizedContentType(contentType);
return contentTypeToParserMap.get(contentType);
}
private String getNormalizedContentType(String contentType) {
int semicolon = contentType.indexOf(';');
return semicolon == -1 ? contentType : contentType.substring(0, semicolon);
}
public HttpTransport() {
useLowLevelHttpTransport();
}
/** Builds a request without specifying the HTTP method. */
public HttpRequest buildRequest() {
return new HttpRequest(this, null);
}
/** Builds a {@code DELETE} request. */
public HttpRequest buildDeleteRequest() {
return new HttpRequest(this, "DELETE");
}
/** Builds a {@code GET} request. */
public HttpRequest buildGetRequest() {
return new HttpRequest(this, "GET");
}
/** Builds a {@code POST} request. */
public HttpRequest buildPostRequest() {
return new HttpRequest(this, "POST");
}
/** Builds a {@code PUT} request. */
public HttpRequest buildPutRequest() {
return new HttpRequest(this, "PUT");
}
/** Builds a {@code PATCH} request. */
public HttpRequest buildPatchRequest() {
return new HttpRequest(this, "PATCH");
}
/** Builds a {@code HEAD} request. */
public HttpRequest buildHeadRequest() {
return new HttpRequest(this, "HEAD");
}
/**
* Removes HTTP request execute intercepters of the given class or subclasses.
*
* @param intercepterClass intercepter class
*/
public void removeIntercepters(Class<?> intercepterClass) {
Iterator<HttpExecuteIntercepter> iterable = intercepters.iterator();
while (iterable.hasNext()) {
HttpExecuteIntercepter intercepter = iterable.next();
if (intercepterClass.isAssignableFrom(intercepter.getClass())) {
iterable.remove();
}
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
import java.io.OutputStream;
/**
* Serializes HTTP request content into an output stream.
*
* @since 1.0
* @author Yaniv Inbar
*/
public interface HttpContent {
/**
* Returns the content length or less than zero if not known.
*
* @throws IOException
*/
long getLength() throws IOException;
/**
* Returns the content encoding (for example {@code "gzip"}) or {@code null} for none.
*/
String getEncoding();
/** Returns the content type. */
String getType();
/**
* Writes the content to the given output stream.
*
* @throws IOException
*/
void writeTo(OutputStream out) throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.Strings;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
/**
* HTTP response.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class HttpResponse {
/** HTTP response content or {@code null} before {@link #getContent()}. */
private InputStream content;
/** Content encoding or {@code null}. */
public final String contentEncoding;
/**
* Content length or less than zero if not known. May be reset by {@link #getContent()} if
* response had GZip compression.
*/
private long contentLength;
/** Content type or {@code null} for none. */
public final String contentType;
/**
* HTTP headers.
* <p>
* If a header name is used for multiple headers, only the last one is retained.
* <p>
* This field's value is instantiated using the same class as that of the
* {@link HttpTransport#defaultHeaders}.
*/
public final HttpHeaders headers;
/** Whether received a successful status code {@code >= 200 && < 300}. */
public final boolean isSuccessStatusCode;
/** Low-level HTTP response. */
private LowLevelHttpResponse response;
/** Status code. */
public final int statusCode;
/** Status message or {@code null}. */
public final String statusMessage;
/** HTTP transport. */
public final HttpTransport transport;
/**
* Whether to disable response content logging during {@link #getContent()} (unless
* {@link Level#ALL} is loggable which forces all logging).
* <p>
* Useful for example if content has sensitive data such as an authentication token. Defaults to
* {@code false}.
*/
public boolean disableContentLogging;
@SuppressWarnings("unchecked")
HttpResponse(HttpTransport transport, LowLevelHttpResponse response) {
this.transport = transport;
this.response = response;
contentLength = response.getContentLength();
contentType = response.getContentType();
contentEncoding = response.getContentEncoding();
int code = response.getStatusCode();
statusCode = code;
isSuccessStatusCode = isSuccessStatusCode(code);
String message = response.getReasonPhrase();
statusMessage = message;
Logger logger = HttpTransport.LOGGER;
boolean loggable = logger.isLoggable(Level.CONFIG);
StringBuilder logbuf = null;
if (loggable) {
logbuf = new StringBuilder();
logbuf.append("-------------- RESPONSE --------------").append(Strings.LINE_SEPARATOR);
String statusLine = response.getStatusLine();
if (statusLine != null) {
logbuf.append(statusLine);
} else {
logbuf.append(code);
if (message != null) {
logbuf.append(' ').append(message);
}
}
logbuf.append(Strings.LINE_SEPARATOR);
}
// headers
int size = response.getHeaderCount();
Class<? extends HttpHeaders> headersClass = transport.defaultHeaders.getClass();
ClassInfo classInfo = ClassInfo.of(headersClass);
HttpHeaders headers = this.headers = ClassInfo.newInstance(headersClass);
HashMap<String, String> fieldNameMap = HttpHeaders.getFieldNameMap(headersClass);
for (int i = 0; i < size; i++) {
String headerName = response.getHeaderName(i);
String headerValue = response.getHeaderValue(i);
if (loggable) {
logbuf.append(headerName + ": " + headerValue).append(Strings.LINE_SEPARATOR);
}
String fieldName = fieldNameMap.get(headerName);
if (fieldName == null) {
fieldName = headerName;
}
// use field information if available
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
// collection is used for repeating headers of the same name
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(headers);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(headers, collection);
}
// parse value based on collection type parameter
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, headerValue));
} else {
// parse value based on field type
fieldInfo.setValue(headers, FieldInfo.parsePrimitiveValue(type, headerValue));
}
} else {
// store header values in an array list
ArrayList<String> listValue = (ArrayList<String>) headers.get(fieldName);
if (listValue == null) {
listValue = new ArrayList<String>();
headers.set(fieldName, listValue);
}
listValue.add(headerValue);
}
}
if (loggable) {
logger.config(logbuf.toString());
}
}
/**
* Returns the content of the HTTP response.
* <p>
* The result is cached, so subsequent calls will be fast.
*
* @return input stream content of the HTTP response or {@code null} for none
* @throws IOException I/O exception
*/
public InputStream getContent() throws IOException {
LowLevelHttpResponse response = this.response;
if (response == null) {
return content;
}
InputStream content = this.response.getContent();
this.response = null;
if (content != null) {
byte[] debugContentByteArray = null;
Logger logger = HttpTransport.LOGGER;
boolean loggable =
!disableContentLogging && logger.isLoggable(Level.CONFIG) || logger.isLoggable(Level.ALL);
if (loggable) {
ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
InputStreamContent.copy(content, debugStream);
debugContentByteArray = debugStream.toByteArray();
content = new ByteArrayInputStream(debugContentByteArray);
logger.config("Response size: " + debugContentByteArray.length + " bytes");
}
// gzip encoding
String contentEncoding = this.contentEncoding;
if (contentEncoding != null && contentEncoding.contains("gzip")) {
content = new GZIPInputStream(content);
contentLength = -1;
if (loggable) {
ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
InputStreamContent.copy(content, debugStream);
debugContentByteArray = debugStream.toByteArray();
content = new ByteArrayInputStream(debugContentByteArray);
}
}
if (loggable) {
// print content using a buffered input stream that can be re-read
String contentType = this.contentType;
if (debugContentByteArray.length != 0 && LogContent.isTextBasedContentType(contentType)) {
logger.config(new String(debugContentByteArray));
}
}
this.content = content;
}
return content;
}
/**
* Gets the content of the HTTP response from {@link #getContent()} and ignores the content if
* there is any.
*
* @throws IOException I/O exception
*/
public void ignore() throws IOException {
InputStream content = getContent();
if (content != null) {
content.close();
}
}
/**
* Returns the HTTP response content parser to use for the content type of this HTTP response or
* {@code null} for none.
*/
public HttpParser getParser() {
return transport.getParser(contentType);
}
/**
* Parses the content of the HTTP response from {@link #getContent()} and reads it into a data
* class of key/value pairs using the parser returned by {@link #getParser()} .
*
* @return parsed data class or {@code null} for no content
* @throws IOException I/O exception
* @throws IllegalArgumentException if no parser is defined for the given content type or if there
* is no content type defined in the HTTP response
*/
public <T> T parseAs(Class<T> dataClass) throws IOException {
HttpParser parser = getParser();
if (parser == null) {
InputStream content = getContent();
if (contentType == null) {
if (content != null) {
throw new IllegalArgumentException(
"Missing Content-Type header in response: " + parseAsString());
}
return null;
}
throw new IllegalArgumentException("No parser defined for Content-Type: " + contentType);
}
return parser.parse(this, dataClass);
}
/**
* Parses the content of the HTTP response from {@link #getContent()} and reads it into a string.
* <p>
* Since this method returns {@code ""} for no content, a simpler check for no content is to check
* if {@link #getContent()} is {@code null}.
*
* @return parsed string or {@code ""} for no content
* @throws IOException I/O exception
*/
public String parseAsString() throws IOException {
InputStream content = getContent();
if (content == null) {
return "";
}
try {
long contentLength = this.contentLength;
int bufferSize = contentLength == -1 ? 4096 : (int) contentLength;
int length = 0;
byte[] buffer = new byte[bufferSize];
byte[] tmp = new byte[4096];
int bytesRead;
while ((bytesRead = content.read(tmp)) != -1) {
if (length + bytesRead > bufferSize) {
bufferSize = Math.max(bufferSize << 1, length + bytesRead);
byte[] newbuffer = new byte[bufferSize];
System.arraycopy(buffer, 0, newbuffer, 0, length);
buffer = newbuffer;
}
System.arraycopy(tmp, 0, buffer, length, bytesRead);
length += bytesRead;
}
return new String(buffer, 0, length);
} finally {
content.close();
}
}
/**
* Returns whether the given HTTP response status code is a success code {@code >= 200 and < 300}.
*/
public static boolean isSuccessStatusCode(int statusCode) {
return statusCode >= 200 && statusCode < 300;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
import java.io.InputStream;
/**
* Low-level HTTP response.
* <p>
* This allows providing a different implementation of the HTTP response that is more compatible
* with the Java environment used.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class LowLevelHttpResponse {
/** Returns the HTTP response content input stream or {@code null} for none. */
public abstract InputStream getContent() throws IOException;
/**
* Returns the content encoding (for example {@code "gzip"}) or {@code null} for none.
*/
public abstract String getContentEncoding();
/** Returns the content length or {@code 0} for none. */
public abstract long getContentLength();
/** Returns the content type or {@code null} for none. */
public abstract String getContentType();
/** Returns the response status line or {@code null} for none. */
public abstract String getStatusLine();
/** Returns the response status code or {@code 0} for none. */
public abstract int getStatusCode();
/** Returns the HTTP reason phrase or {@code null} for none. */
public abstract String getReasonPhrase();
/**
* Returns the number of HTTP response headers.
* <p>
* Note that multiple headers of the same name need to be supported, in which case each header
* value is treated as a separate header.
*/
public abstract int getHeaderCount();
/** Returns the HTTP response header name at the given zero-based index. */
public abstract String getHeaderName(int index);
/** Returns the HTTP response header value at the given zero-based index. */
public abstract String getHeaderValue(int index);
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import com.google.api.client.util.Strings;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* HTTP request.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class HttpRequest {
/** User agent suffix for all requests. */
private static final String USER_AGENT_SUFFIX = "Google-API-Java-Client/1.2.3-alpha";
/**
* HTTP request headers.
* <p>
* Its value is initialized by calling {@code clone()} on the
* {@link HttpTransport#defaultHeaders}. Therefore, it is initialized to be of the same Java
* class, i.e. of the same {@link Object#getClass()}.
*/
public HttpHeaders headers;
/**
* Whether to disable request content logging during {@link #execute()} (unless {@link Level#ALL}
* is loggable which forces all logging).
* <p>
* Useful for example if content has sensitive data such as an authentication information.
* Defaults to {@code false}.
*/
public boolean disableContentLogging;
/** HTTP request content or {@code null} for none. */
public HttpContent content;
/** HTTP transport. */
public final HttpTransport transport;
/** HTTP request method. Must be one of: "DELETE", "GET", "HEAD", "PATCH", "PUT", or "POST". */
public String method;
// TODO: support more HTTP methods?
/** HTTP request URL. */
public GenericUrl url;
/**
* @param transport HTTP transport
* @param method HTTP request method (may be {@code null}
*/
HttpRequest(HttpTransport transport, String method) {
this.transport = transport;
headers = transport.defaultHeaders.clone();
this.method = method;
}
/** Sets the {@link #url} based on the given encoded URL string. */
public void setUrl(String encodedUrl) {
url = new GenericUrl(encodedUrl);
}
/**
* Execute the HTTP request and returns the HTTP response.
* <p>
* Note that regardless of the returned status code, the HTTP response content has not been parsed
* yet, and must be parsed by the calling code.
* <p>
* Almost all details of the request and response are logged if {@link Level#CONFIG} is loggable.
* The only exception is the value of the {@code Authorization} header which is only logged if
* {@link Level#ALL} is loggable.
*
* @return HTTP response for an HTTP success code
* @throws HttpResponseException for an HTTP error code
* @see HttpResponse#isSuccessStatusCode
*/
public HttpResponse execute() throws IOException {
Preconditions.checkNotNull(method);
Preconditions.checkNotNull(url);
HttpTransport transport = this.transport;
// first run the execute intercepters
for (HttpExecuteIntercepter intercepter : transport.intercepters) {
intercepter.intercept(this);
}
// build low-level HTTP request
LowLevelHttpTransport lowLevelHttpTransport = HttpTransport.useLowLevelHttpTransport();
String method = this.method;
GenericUrl url = this.url;
String urlString = url.build();
LowLevelHttpRequest lowLevelHttpRequest;
if (method.equals("DELETE")) {
lowLevelHttpRequest = lowLevelHttpTransport.buildDeleteRequest(urlString);
} else if (method.equals("GET")) {
lowLevelHttpRequest = lowLevelHttpTransport.buildGetRequest(urlString);
} else if (method.equals("HEAD")) {
if (!lowLevelHttpTransport.supportsHead()) {
throw new IllegalArgumentException("HTTP transport doesn't support HEAD");
}
lowLevelHttpRequest = lowLevelHttpTransport.buildHeadRequest(urlString);
} else if (method.equals("PATCH")) {
if (!lowLevelHttpTransport.supportsPatch()) {
throw new IllegalArgumentException("HTTP transport doesn't support PATCH");
}
lowLevelHttpRequest = lowLevelHttpTransport.buildPatchRequest(urlString);
} else if (method.equals("POST")) {
lowLevelHttpRequest = lowLevelHttpTransport.buildPostRequest(urlString);
} else if (method.equals("PUT")) {
lowLevelHttpRequest = lowLevelHttpTransport.buildPutRequest(urlString);
} else {
throw new IllegalArgumentException("illegal method: " + method);
}
Logger logger = HttpTransport.LOGGER;
boolean loggable = logger.isLoggable(Level.CONFIG);
StringBuilder logbuf = null;
// log method and URL
if (loggable) {
logbuf = new StringBuilder();
logbuf.append("-------------- REQUEST --------------").append(Strings.LINE_SEPARATOR);
logbuf.append(method).append(' ').append(urlString).append(Strings.LINE_SEPARATOR);
}
// add to user agent
HttpHeaders headers = this.headers;
if (headers.userAgent == null) {
headers.userAgent = USER_AGENT_SUFFIX;
} else {
headers.userAgent += " " + USER_AGENT_SUFFIX;
}
// headers
HashSet<String> headerNames = new HashSet<String>();
for (Map.Entry<String, Object> headerEntry : this.headers.entrySet()) {
String name = headerEntry.getKey();
String lowerCase = name.toLowerCase();
if (!headerNames.add(lowerCase)) {
throw new IllegalArgumentException(
"multiple headers of the same name (headers are case insensitive): " + lowerCase);
}
Object value = headerEntry.getValue();
if (value != null) {
if (value instanceof Collection<?>) {
for (Object repeatedValue : (Collection<?>) value) {
addHeader(logger, logbuf, lowLevelHttpRequest, name, repeatedValue);
}
} else {
addHeader(logger, logbuf, lowLevelHttpRequest, name, value);
}
}
}
// content
HttpContent content = this.content;
if (content != null) {
// check if possible to log content or gzip content
String contentEncoding = content.getEncoding();
long contentLength = content.getLength();
String contentType = content.getType();
if (contentLength != 0 && contentEncoding == null
&& LogContent.isTextBasedContentType(contentType)) {
// log content?
if (loggable && !disableContentLogging || logger.isLoggable(Level.ALL)) {
content = new LogContent(content, contentType, contentEncoding, contentLength);
}
// gzip?
if (contentLength >= 256) {
content = new GZipContent(content, contentType);
contentEncoding = content.getEncoding();
contentLength = content.getLength();
}
}
// append content headers to log buffer
if (loggable) {
logbuf.append("Content-Type: " + contentType).append(Strings.LINE_SEPARATOR);
if (contentEncoding != null) {
logbuf.append("Content-Encoding: " + contentEncoding).append(Strings.LINE_SEPARATOR);
}
if (contentLength >= 0) {
logbuf.append("Content-Length: " + contentLength).append(Strings.LINE_SEPARATOR);
}
}
lowLevelHttpRequest.setContent(content);
}
// log from buffer
if (loggable) {
logger.config(logbuf.toString());
}
// execute
HttpResponse response = new HttpResponse(transport, lowLevelHttpRequest.execute());
if (!response.isSuccessStatusCode) {
throw new HttpResponseException(response);
}
return response;
}
private static void addHeader(Logger logger, StringBuilder logbuf,
LowLevelHttpRequest lowLevelHttpRequest, String name, Object value) {
String stringValue = value.toString();
if (logbuf != null) {
logbuf.append(name).append(": ");
if ("Authorization".equals(name) && !logger.isLoggable(Level.ALL)) {
logbuf.append("<Not Logged>");
} else {
logbuf.append(stringValue);
}
logbuf.append(Strings.LINE_SEPARATOR);
}
lowLevelHttpRequest.addHeader(name, stringValue);
}
}
|
Java
|
/*
*
* Copyright (c) 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth;
import com.google.api.client.util.Base64;
import com.google.api.client.util.Strings;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
/**
* Utility methods for {@code "RSA-SHA1"} signing method.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class RsaSha {
private static final String BEGIN = "-----BEGIN PRIVATE KEY-----";
private static final String END = "-----END PRIVATE KEY-----";
private RsaSha() {
}
/**
* Retrieves the private key from the specified key store.
*
* @param keyStream input stream to the key store file
* @param storePass password protecting the key store file
* @param alias alias under which the private key is stored
* @param keyPass password protecting the private key
* @return the private key from the specified key store
* @throws GeneralSecurityException if the key store cannot be loaded
* @throws IOException if the file cannot be accessed
*/
public static PrivateKey getPrivateKeyFromKeystore(
InputStream keyStream, String storePass, String alias, String keyPass)
throws IOException, GeneralSecurityException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try {
keyStore.load(keyStream, storePass.toCharArray());
return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
} finally {
keyStream.close();
}
}
/**
* Reads a {@code PKCS#8} format private key from a given file.
*
* @throws NoSuchAlgorithmException
*/
public static PrivateKey getPrivateKeyFromPk8(File file)
throws IOException, GeneralSecurityException {
byte[] privKeyBytes = new byte[(int) file.length()];
DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
try {
inputStream.readFully(privKeyBytes);
} finally {
inputStream.close();
}
String str = new String(privKeyBytes);
if (str.startsWith(BEGIN) && str.endsWith(END)) {
str = str.substring(BEGIN.length(), str.lastIndexOf(END));
}
KeyFactory fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(Strings.toBytesUtf8(str)));
return fac.generatePrivate(privKeySpec);
}
/**
* Signs the given data using the given private key.
*
* @throws GeneralSecurityException general security exception
*/
public static String sign(PrivateKey privateKey, String data) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(Strings.toBytesUtf8(data));
return Strings.fromBytesUtf8(Base64.encode(signature.sign()));
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* OAuth 2.0 authorization as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10">The OAuth 2.0 Protocol
* (draft-ietf-oauth-v2-10)</a> (see detailed package specification).
*
* <p>
* Before using this library, you may need to register your application with the authorization
* server to receive a client ID and client secret.
* </p>
*
* <p>
* Typical steps for the OAuth 2 authorization flow:
* <ul>
* <li>Redirect end user in the browser to the authorization page using
* {@link com.google.api.client.auth.oauth2.AuthorizationRequestUrl} to grant your application
* access to their protected data.</li>
* <li>Process the authorization response using
* {@link com.google.api.client.auth.oauth2.AuthorizationResponse} to parse the authorization code
* and/or access token.</li>
* <li>Request an access token, depending on the access grant type:
* <ul>
* <li>Authorization code:
* {@link com.google.api.client.auth.oauth2.AccessTokenRequest.AuthorizationCodeGrant}</li>
* <li>Resource Owner Password Credentials: {@link
* com.google.api.client.auth.oauth2.AccessTokenRequest.ResourceOwnerPasswordCredentialsGrant}</li>
* <li>Assertion: {@link com.google.api.client.auth.oauth2.AccessTokenRequest.AssertionGrant}</li>
* <li>Refresh Token: {@link com.google.api.client.auth.oauth2.AccessTokenRequest.RefreshTokenGrant}
* </li>
* <li>None (e.g. client owns protected resource):
* {@link com.google.api.client.auth.oauth2.AccessTokenRequest}</li>
* </ul>
* </li>
* </ul>
* </p>
*
* <p>
* This package depends on theses packages:
* </p>
* <ul>
* <li>{@link com.google.api.client.http}</li>
* <li>{@link com.google.api.client.json}</li>
* <li>{@link com.google.api.client.util}</li>
* </ul>
*
* <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>
* <p>
* <b>Upgrade warning: in version 1.1 of the library, the implementation was based on draft 07 of
* the specification, but as of version 1.2 it has been replaced with an implementation based on
* draft 10. Thus, this implementation is not backwards compatible, and is not safe as a drop-in
* replacement.</b>
* </p>
*
* @since 1.2
* @author Yaniv Inbar
*/
package com.google.api.client.auth.oauth2;
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the
* application to access their protected resources as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-3">Obtaining End-User
* Authorization</a>.
* <p>
* Use {@link AuthorizationResponse} to parse the redirect response after the end user grants/denies
* the request.
* </p>
* <p>
* Sample usage for a web application:
*
* <pre>
* <code>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
AuthorizationRequestUrl result = new AuthorizationRequestUrl(BASE_AUTHORIZATION_URL);
AuthorizationRequestUrl.ResponseType.CODE.set(result);
result.clientId = CLIENT_ID;
result.redirectUri = REDIRECT_URL;
result.scope = SCOPE;
response.sendRedirect(result.build());
return;
}
* </code>
* </pre>
*
* @since 1.2
* @author Yaniv Inbar
*/
public class AuthorizationRequestUrl extends GenericUrl {
/**
* Response type enumeration that may be used for setting the
* {@link AuthorizationRequestUrl#responseType}.
* <p>
* Call {@link #set(AuthorizationRequestUrl)} to set the response type on an authorization request
* URL.
* </p>
*/
public enum ResponseType {
/** Authorization code. */
CODE,
/** Access token. */
TOKEN,
/** Authorization code and access token. */
CODE_AND_TOKEN;
/**
* Sets the response type on an authorization request URL.
*
* @param url authorization request URL
*/
public void set(AuthorizationRequestUrl url) {
url.responseType = this.toString().toLowerCase();
}
}
/**
* (REQUIRED) The requested response: an access token, an authorization code, or both. The
* parameter value MUST be set to "token" for requesting an access token, "code" for requesting an
* authorization code, or "code_and_token" to request both. The authorization server MAY decline
* to provide one or more of these response types. For convenience, you may use
* {@link ResponseType} to set this value.
*/
@Key("response_type")
public String responseType;
/** (REQUIRED) The client identifier. */
@Key("client_id")
public String clientId;
/**
* (REQUIRED, unless a redirection URI has been established between the client and authorization
* server via other means) An absolute URI to which the authorization server will redirect the
* user-agent to when the end-user authorization step is completed. The authorization server
* SHOULD require the client to pre-register their redirection URI.
*/
@Key("redirect_uri")
public String redirectUri;
/**
* (OPTIONAL) The scope of the access request expressed as a list of space-delimited strings. The
* value of the "scope" parameter is defined by the authorization server. If the value contains
* multiple space-delimited strings, their order does not matter, and each string adds an
* additional access range to the requested scope.
*/
@Key
public String scope;
/**
* (OPTIONAL) An opaque value used by the client to maintain state between the request and
* callback. The authorization server includes this value when redirecting the user-agent back to
* the client.
*/
@Key
public String state;
/**
* @param encodedAuthorizationServerUrl encoded authorization server URL
*/
public AuthorizationRequestUrl(String encodedAuthorizationServerUrl) {
super(encodedAuthorizationServerUrl);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.http.UrlEncodedParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
import java.net.URI;
import java.net.URISyntaxException;
/**
* OAuth 2.0 parser for the redirect URL after end user grants or denies authorization as specified
* in <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-3.1">Authorization
* Response</a>.
* <p>
* Check if {@link #error} is {@code null} to check if the end-user granted authorization.
* </p>
* <p>
* Sample usage for a web application:
*
* <pre><code>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
StringBuffer fullUrlBuf = request.getRequestURL();
if (request.getQueryString() != null) {
fullUrlBuf.append('?').append(request.getQueryString());
}
AuthorizationResponse authResponse = new AuthorizationResponse(fullUrlBuf.toString());
// check for user-denied error
if (authResponse.error != null) {
// authorization denied...
} else {
// request access token using authResponse.code...
}
}
* </code></pre>
* </p>
* <p>
* Sample usage for an installed application:
*
* <pre><code>
static void processRedirectUrl(HttpTransport transport, String redirectUrl) {
AuthorizationResponse response = new AuthorizationResponse(redirectUrl);
if (response.error != null) {
throw new RuntimeException("Authorization denied");
}
AccessProtectedResource.usingAuthorizationHeader(transport, response.accessToken);
}
* </code></pre>
* </p>
*
* @since 1.2
* @author Yaniv Inbar
*/
public class AuthorizationResponse extends GenericData {
/**
* Error codes listed in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-3.2.1">Error Codes</a>.
*/
public enum KnownError {
/**
* The request is missing a required parameter, includes an unsupported parameter or parameter
* value, or is otherwise malformed.
*/
INVALID_REQUEST,
/** The client identifier provided is invalid. */
INVALID_CLIENT,
/** The client is not authorized to use the requested response type. */
UNAUTHORIZED_CLIENT,
/** The redirection URI provided does not match a pre-registered value. */
REDIRECT_URI_MISMATCH,
/** The end-user or authorization server denied the request. */
ACCESS_DENIED,
/** The requested response type is not supported by the authorization server. */
UNSUPPORTED_RESPONSE_TYPE,
/** The requested scope is invalid, unknown, or malformed. */
INVALID_SCOPE;
}
/**
* (REQUIRED if the end user grants authorization and the response type is "code" or
* "code_and_token", otherwise MUST NOT be included) The authorization code generated by the
* authorization server. The authorization code SHOULD expire shortly after it is issued. The
* authorization server MUST invalidate the authorization code after a single usage. The
* authorization code is bound to the client identifier and redirection URI.
*/
@Key
public String code;
/**
* (REQUIRED if the end user grants authorization and the response type is "token" or
* "code_and_token", otherwise MUST NOT be included) The access token issued by the authorization
* server.
*/
@Key("access_token")
public String accessToken;
/**
* (OPTIONAL) The duration in seconds of the access token lifetime if an access token is included.
* For example, the value "3600" denotes that the access token will expire in one hour from the
* time the response was generated by the authorization server.
*/
@Key("expires_in")
public Long expiresIn;
/**
* (OPTIONAL) The scope of the access token as a list of space- delimited strings if an access
* token is included. The value of the "scope" parameter is defined by the authorization server.
* If the value contains multiple space-delimited strings, their order does not matter, and each
* string adds an additional access range to the requested scope. The authorization server SHOULD
* include the parameter if the requested scope is different from the one requested by the client.
*/
@Key
public String scope;
/**
* (REQUIRED if the end user denies authorization) A single error code.
*
* @see #getErrorCodeIfKnown()
*/
@Key
public String error;
/**
* (OPTIONAL) A human-readable text providing additional information, used to assist in the
* understanding and resolution of the error occurred.
*/
@Key("error_description")
public String errorDescription;
/**
* (OPTIONAL) A URI identifying a human-readable web page with information about the error, used
* to provide the end-user with additional information about the error.
*/
@Key("error_uri")
public String errorUri;
/**
* (REQUIRED if the "state" parameter was present in the client authorization request) Set to the
* exact value received from the client.
*/
@Key
public String state;
/**
* @param redirectUrl encoded redirect URL
* @throws IllegalArgumentException URI syntax exception
*/
public AuthorizationResponse(String redirectUrl) {
try {
URI uri = new URI(redirectUrl);
// need to check for parameters both in the URL query and the URL fragment
UrlEncodedParser.parse(uri.getRawQuery(), this);
UrlEncodedParser.parse(uri.getRawFragment(), this);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Returns a known error code if {@link #error} is one of the error codes listed in the OAuth 2
* specification or {@code null} if the {@link #error} is {@code null} or not known.
*/
public final KnownError getErrorCodeIfKnown() {
if (error != null) {
try {
return KnownError.valueOf(error.toUpperCase());
} catch (IllegalArgumentException e) {
// ignore; most likely due to an unrecognized error code
}
}
return null;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
/**
* OAuth 2.0 access token success response content as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.2">Access Token Response</a>.
* <p>
* Use {@link AccessProtectedResource} to authorize executed HTTP requests based on the
* {@link #accessToken}, for example {@link AccessProtectedResource}.{@link
* AccessProtectedResource#usingAuthorizationHeader(com.google.api.client.http.HttpTransport,
* String) usingAuthorizationHeader}{@code (transport, response.accessToken)}.
* </p>
*
* @since 1.2
* @author Yaniv Inbar
*/
public class AccessTokenResponse extends GenericData {
/** (REQUIRED) The access token issued by the authorization server. */
@Key("access_token")
public String accessToken;
/**
* (OPTIONAL) The duration in seconds of the access token lifetime. For example, the value "3600"
* denotes that the access token will expire in one hour from the time the response was generated
* by the authorization server.
*/
@Key("expires_in")
public Long expiresIn;
/**
* (OPTIONAL) The refresh token used to obtain new access tokens. The authorization server SHOULD
* NOT issue a refresh token when the access grant type is set to "none".
*/
@Key("refresh_token")
public String refreshToken;
/**
* (OPTIONAL) The scope of the access token as a list of space- delimited strings. The value of
* the "scope" parameter is defined by the authorization server. If the value contains multiple
* space-delimited strings, their order does not matter, and each string adds an additional access
* range to the requested scope. The authorization server SHOULD include the parameter if the
* requested scope is different from the one requested by the client.
*/
@Key
public String scope;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.GenericData;
import java.util.Arrays;
import java.util.List;
/**
* OAuth 2.0 methods for specifying the access token parameter as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5">Accessing a Protected
* Resource</a>.
*
* @author Yaniv Inbar
* @since 1.2
*/
public final class AccessProtectedResource {
/**
* Sets the {@code "Authorization"} header using the given access token for every executed HTTP
* request for the given HTTP transport.
* <p>
* Any existing HTTP request execute intercepters for setting the OAuth 2 access token will be
* removed.
* </p>
*
* @param transport HTTP transport
* @param accessToken access token
*/
public static void usingAuthorizationHeader(HttpTransport transport, String accessToken) {
new UsingAuthorizationHeader().authorize(transport, accessToken);
}
/**
* Sets the {@code "oauth_token"} URI query parameter using the given access token for every
* executed HTTP request for the given HTTP transport.
* <p>
* Any existing HTTP request execute intercepters for setting the OAuth 2 access token will be
* removed.
*
* @param transport HTTP transport
* @param accessToken access token
*/
public static void usingQueryParameter(HttpTransport transport, String accessToken) {
new UsingQueryParameter().authorize(transport, accessToken);
}
/**
* Sets the {@code "oauth_token"} parameter in the form-encoded HTTP body using the given access
* token for every executed HTTP request for the given HTTP transport.
* <p>
* Any existing HTTP request execute intercepters for setting the OAuth 2 access token will be
* removed. Requirements:
* <ul>
* <li>The HTTP method must be "POST", "PUT", or "DELETE".</li>
* <li>The HTTP content must be {@code null} or {@link UrlEncodedContent}.</li>
* <li>The {@link UrlEncodedContent#data} must be {@code null} or {@link GenericData}.</li>
* </ul>
*
* @param transport HTTP transport
* @param accessToken access token
*/
public static void usingFormEncodedBody(HttpTransport transport, String accessToken) {
new UsingFormEncodedBody().authorize(transport, accessToken);
}
/**
* Abstract class to inject an access token parameter for every executed HTTP request .
*/
static abstract class AccessTokenIntercepter implements HttpExecuteIntercepter {
/** Access token to use. */
String accessToken;
void authorize(HttpTransport transport, String accessToken) {
this.accessToken = accessToken;
transport.removeIntercepters(AccessTokenIntercepter.class);
transport.intercepters.add(this);
}
}
static final class UsingAuthorizationHeader extends AccessTokenIntercepter {
public void intercept(HttpRequest request) {
request.headers.authorization = "OAuth " + accessToken;
}
}
static final class UsingQueryParameter extends AccessTokenIntercepter {
public void intercept(HttpRequest request) {
request.url.set("oauth_token", accessToken);
}
}
static final class UsingFormEncodedBody extends AccessTokenIntercepter {
private static final List<String> ALLOWED_METHODS = Arrays.asList("POST", "PUT", "DELETE");
public void intercept(HttpRequest request) {
if (!ALLOWED_METHODS.contains(request.method)) {
throw new IllegalArgumentException(
"expected one of these HTTP methods: " + ALLOWED_METHODS);
}
// URL-encoded content (cast exception if not the right class)
UrlEncodedContent content = (UrlEncodedContent) request.content;
if (content == null) {
content = new UrlEncodedContent();
request.content = content;
}
// Generic data (cast exception if not the right class)
GenericData data = (GenericData) content.data;
if (data == null) {
data = new GenericData();
content.data = data;
}
data.put("oauth_token", accessToken);
}
}
private AccessProtectedResource() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
import java.io.IOException;
/**
* OAuth 2.0 request for an access token as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4">Obtaining an Access Token</a>.
* <p>
* This class may be used directly when no access grant is included, such as when the client is
* requesting access to the protected resources under its control. Otherwise, use one of the
* subclasses, which add custom parameters to specify the access grant. Call {@link #execute()} to
* execute the request from which the {@link AccessTokenResponse} may be parsed. On error, use
* {@link AccessTokenErrorResponse} instead.
* <p>
* Sample usage when the client is requesting access to the protected resources under its control:
*
* <pre>
* <code>
static void requestAccessToken() throws IOException {
try {
AccessTokenRequest request = new AccessTokenRequest();
request.authorizationServerUrl = BASE_AUTHORIZATION_URL;
request.clientId = CLIENT_ID;
request.clientSecret = CLIENT_SECRET;
AccessTokenResponse response = request.execute().parseAs(AccessTokenResponse.class);
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
* </code>
* </pre>
* </p>
*
* @since 1.2
* @author Yaniv Inbar
*/
public class AccessTokenRequest extends GenericData {
/**
* OAuth 2.0 Web Server Flow: request an access token based on a verification code as specified in
* <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.1">Authorization
* Code</a>.
* <p>
* Sample usage:
*
* <pre>
* <code>
static void requestAccessToken(String code, String redirectUrl) throws IOException {
try {
AuthorizationCodeGrant request = new AuthorizationCodeGrant();
request.authorizationServerUrl = BASE_AUTHORIZATION_URL;
request.clientId = CLIENT_ID;
request.clientSecret = CLIENT_SECRET;
request.code = code;
request.redirectUri = redirectUrl;
AccessTokenResponse response = request.execute().parseAs(AccessTokenResponse.class);
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
* </code>
* </pre>
* </p>
*/
public static class AuthorizationCodeGrant extends AccessTokenRequest {
/**
* (REQUIRED) The authorization code received from the authorization server.
*/
@Key
public String code;
/** (REQUIRED) The redirection URI used in the initial request. */
@Key("redirect_uri")
public String redirectUri;
public AuthorizationCodeGrant() {
grantType = "authorization_code";
}
}
/**
* OAuth 2.0 Username and Password Flow: request an access token based on resource owner
* credentials used in the as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.2">Resource Owner Password
* Credentials</a>.
* <p>
* Sample usage:
*
* <pre>
* <code>
static void requestAccessToken(String code, String redirectUrl) throws IOException {
try {
ResourceOwnerPasswordCredentialsGrant request = new ResourceOwnerPasswordCredentialsGrant();
request.authorizationServerUrl = BASE_AUTHORIZATION_URL;
request.clientId = CLIENT_ID;
request.clientSecret = CLIENT_SECRET;
request.username = username;
request.password = password;
AccessTokenResponse response = request.execute().parseAs(AccessTokenResponse.class);
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
* </code>
* </pre>
* </p>
*/
public static class ResourceOwnerPasswordCredentialsGrant extends AccessTokenRequest {
/** (REQUIRED) The resource owner's username. */
@Key
public String username;
/** (REQUIRED) The resource owner's password. */
public String password;
public ResourceOwnerPasswordCredentialsGrant() {
grantType = "password";
}
}
/**
* OAuth 2.0 Assertion Flow: request an access token based on as assertion as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.3">Assertion</a>.
* <p>
* Sample usage:
*
* <pre>
* <code>
static void requestAccessToken(String assertion) throws IOException {
try {
AssertionGrant request = new AssertionGrant();
request.authorizationServerUrl = BASE_AUTHORIZATION_URL;
request.clientId = CLIENT_ID;
request.clientSecret = CLIENT_SECRET;
request.assertionType = ASSERTION_TYPE;
request.assertion = assertion;
AccessTokenResponse response = request.execute().parseAs(AccessTokenResponse.class);
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
* </code>
* </pre>
* </p>
*/
public static class AssertionGrant extends AccessTokenRequest {
/**
* (REQUIRED) The format of the assertion as defined by the authorization server. The value MUST
* be an absolute URI.
*/
@Key("assertion_type")
public String assertionType;
/** (REQUIRED) The assertion. */
@Key
public String assertion;
public AssertionGrant() {
grantType = "assertion";
}
}
/**
* OAuth 2.0 request to refresh an access token as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.4">Refresh Token</a>.
* <p>
* Sample usage:
*
* <pre>
* <code>
static void requestAccessToken(String refreshToken) throws IOException {
try {
RefreshTokenGrant request = new RefreshTokenGrant();
request.authorizationServerUrl = BASE_AUTHORIZATION_URL;
request.clientId = CLIENT_ID;
request.clientSecret = CLIENT_SECRET;
request.refreshToken = refreshToken;
AccessTokenResponse response = request.execute().parseAs(AccessTokenResponse.class);
System.out.println("Access token: " + response.accessToken);
} catch (HttpResponseException e) {
AccessTokenErrorResponse response = e.response.parseAs(AccessTokenErrorResponse.class);
System.out.println("Error: " + response.error);
}
}
* </code>
* </pre>
* </p>
*/
public static class RefreshTokenGrant extends AccessTokenRequest {
/**
* (REQUIRED) The refresh token associated with the access token to be refreshed.
*/
@Key("refresh_token")
public String refreshToken;
public RefreshTokenGrant() {
grantType = "refresh_token";
}
}
/**
* (REQUIRED) The access grant type included in the request. Value MUST be one of
* "authorization_code", "password", "assertion", "refresh_token", or "none".
*/
@Key("grant_type")
public String grantType = "none";
/**
* (REQUIRED, unless the client identity can be establish via other means, for example assertion)
* The client identifier.
*/
@Key("client_id")
public String clientId;
/**
* (REQUIRED) The client secret.
*/
public String clientSecret;
/**
* (OPTIONAL) The scope of the access request expressed as a list of space-delimited strings. The
* value of the "scope" parameter is defined by the authorization server. If the value contains
* multiple space-delimited strings, their order does not matter, and each string adds an
* additional access range to the requested scope. If the access grant being used already
* represents an approved scope (e.g. authorization code, assertion), the requested scope MUST be
* equal or lesser than the scope previously granted.
*/
@Key
public String scope;
/** Encoded authorization server URL. */
public String authorizationServerUrl;
/**
* Defaults to {@code true} to use Basic Authentication as recommended in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-2.1">Client Password
* Credentials</a>, but may be set to {@code false} for for specifying the password in the request
* body using the {@code "clientSecret"} parameter in the HTTP body.
*/
public boolean useBasicAuthorization = true;
/**
* Executes request for an access token, and returns the HTTP response.
*
* @return HTTP response, which can then be parsed using {@link HttpResponse#parseAs(Class)} with
* {@link AccessTokenResponse}
* @throws HttpResponseException for an HTTP error response, which can then be parsed using
* {@link HttpResponse#parseAs(Class)} on {@link HttpResponseException#response} using
* {@link AccessTokenErrorResponse}
* @throws IOException I/O exception
*/
public final HttpResponse execute() throws IOException {
HttpTransport transport = new HttpTransport();
transport.addParser(new JsonHttpParser());
HttpRequest request = transport.buildPostRequest();
if (useBasicAuthorization) {
request.headers.setBasicAuthentication(clientId, clientSecret);
} else {
put("client_secret", clientSecret);
}
request.setUrl(authorizationServerUrl);
UrlEncodedContent content = new UrlEncodedContent();
content.data = this;
request.content = content;
return request.execute();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth2;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
/**
* OAuth 2.0 access token error response as specified in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.3">Error Response</a>.
*
* @since 1.2
* @author Yaniv Inbar
*/
public class AccessTokenErrorResponse extends GenericData {
/**
* Error codes listed in <a
* href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.3.1">Error Codes</a>.
*/
public enum KnownError {
/**
* The request is missing a required parameter, includes an unsupported parameter or parameter
* value, repeats a parameter, includes multiple credentials, utilizes more than one mechanism
* for authenticating the client, or is otherwise malformed.
*/
INVALID_REQUEST,
/**
* The client identifier provided is invalid, the client failed to authenticate, the client did
* not include its credentials, provided multiple client credentials, or used unsupported
* credentials type.
*/
INVALID_CLIENT,
/**
* The authenticated client is not authorized to use the access grant type provided.
*/
UNAUTHORIZED_CLIENT,
/**
*The provided access grant is invalid, expired, or revoked (e.g. invalid assertion, expired
* authorization token, bad end-user password credentials, or mismatching authorization code and
* redirection URI).
*/
INVALID_GRANT,
/**
* The access grant included - its type or another attribute - is not supported by the
* authorization server.
*/
UNSUPPORTED_GRANT_TYPE,
/**
* The requested scope is invalid, unknown, malformed, or exceeds the previously granted scope.
*/
INVALID_SCOPE;
}
/**
* (REQUIRED) A single error code.
*
* @see #getErrorCodeIfKnown()
*/
@Key
public String error;
/**
* (OPTIONAL) A human-readable text providing additional information, used to assist in the
* understanding and resolution of the error occurred.
*/
@Key("error_description")
public String errorDescription;
/**
* (OPTIONAL) A URI identifying a human-readable web page with information about the error, used
* to provide the end-user with additional information about the error.
*/
@Key("error_uri")
public String errorUri;
/**
* Returns a known error code if {@link #error} is one of the error codes listed in the OAuth 2
* specification or {@code null} if the {@link #error} is {@code null} or not known.
*/
public final KnownError getErrorCodeIfKnown() {
if (error != null) {
try {
return KnownError.valueOf(error.toUpperCase());
} catch (IllegalArgumentException e) {
// ignore; most likely due to an unrecognized error code
}
}
return null;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth;
import com.google.api.client.util.Base64;
import com.google.api.client.util.Strings;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Utility methods for {@code "HMAC-SHA1"} signing method.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class HmacSha {
/**
* Signs the given data using the given secret key.
*
* @throws GeneralSecurityException general security exception
*/
public static String sign(String key, String data) throws GeneralSecurityException {
SecretKey secretKey = new SecretKeySpec(Strings.toBytesUtf8(key), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] encoded = Base64.encode(mac.doFinal(Strings.toBytesUtf8(data)));
return Strings.fromBytesUtf8(encoded);
}
private HmacSha() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.auth.HmacSha;
import java.security.GeneralSecurityException;
/**
* OAuth {@code "HMAC-SHA1"} signature method.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class OAuthHmacSigner implements OAuthSigner {
/** Client-shared secret or {@code null} for none. */
public String clientSharedSecret;
/** Token-shared secret or {@code null} for none. */
public String tokenSharedSecret;
public String getSignatureMethod() {
return "HMAC-SHA1";
}
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
StringBuilder keyBuf = new StringBuilder();
String clientSharedSecret = this.clientSharedSecret;
if (clientSharedSecret != null) {
keyBuf.append(OAuthParameters.escape(clientSharedSecret));
}
keyBuf.append('&');
String tokenSharedSecret = this.tokenSharedSecret;
if (tokenSharedSecret != null) {
keyBuf.append(OAuthParameters.escape(tokenSharedSecret));
}
return HmacSha.sign(keyBuf.toString(), signatureBaseString);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.http.HttpTransport;
/**
* Generic OAuth 1.0a URL to request to exchange the temporary credentials token (or "request
* token") for a long-lived credentials token (or "access token") from an authorization server.
* <p>
* Use {@link #execute()} to execute the request. The long-lived access token acquired with this
* request is found in {@link OAuthCredentialsResponse#token} . This token must be stored. It may
* then be used to authorize HTTP requests to protected resources by setting the
* {@link OAuthParameters#token}, and invoking
* {@link OAuthParameters#signRequestsUsingAuthorizationHeader(HttpTransport)}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class OAuthGetAccessToken extends AbstractOAuthGetToken {
/**
* Required temporary token. It is retrieved from the {@link OAuthCredentialsResponse#token}
* returned from {@link OAuthGetTemporaryToken#execute()}.
*/
public String temporaryToken;
/**
* Required verifier code received from the server when the temporary token was authorized. It is
* retrieved from {@link OAuthCallbackUrl#verifier}.
*/
public String verifier;
/**
* @param authorizationServerUrl encoded authorization server URL
*/
public OAuthGetAccessToken(String authorizationServerUrl) {
super(authorizationServerUrl);
}
@Override
public OAuthParameters createParameters() {
OAuthParameters result = super.createParameters();
result.token = temporaryToken;
result.verifier = verifier;
return result;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.UrlEncodedParser;
import java.io.IOException;
/**
* Generic OAuth 1.0a URL to request a temporary or long-lived token from an authorization server.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class AbstractOAuthGetToken extends GenericUrl {
/**
* Required identifier portion of the client credentials (equivalent to a username).
*/
public String consumerKey;
/** Required OAuth signature algorithm. */
public OAuthSigner signer;
/** {@code true} for POST request or the default {@code false} for GET request. */
protected boolean usePost;
/**
* @param authorizationServerUrl encoded authorization server URL
*/
protected AbstractOAuthGetToken(String authorizationServerUrl) {
super(authorizationServerUrl);
}
/**
* Executes the HTTP request for a temporary or long-lived token.
*
* @return OAuth credentials response object
* @throws HttpResponseException for an HTTP error code
* @throws IOException I/O exception
*/
public final OAuthCredentialsResponse execute() throws IOException {
HttpTransport transport = new HttpTransport();
createParameters().signRequestsUsingAuthorizationHeader(transport);
HttpRequest request = usePost ? transport.buildPostRequest() : transport.buildGetRequest();
request.url = this;
HttpResponse response = request.execute();
response.disableContentLogging = true;
OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse();
UrlEncodedParser.parse(response.parseAsString(), oauthResponse);
return oauthResponse;
}
/**
* Returns a new instance of the OAuth authentication provider. Subclasses may override by calling
* this super implementation and then adding OAuth parameters.
*/
public OAuthParameters createParameters() {
OAuthParameters result = new OAuthParameters();
result.consumerKey = consumerKey;
result.signer = signer;
return result;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* OAuth 1.0a URL builder for an authorization web page to allow the end user to authorize the
* temporary token.
* <p>
* The {@link #temporaryToken} should be set from the {@link OAuthCredentialsResponse#token}
* returned by {@link OAuthGetTemporaryToken#execute()}. Use {@link #build()} to build the
* authorization URL. If a {@link OAuthGetTemporaryToken#callback} was specified, after the end user
* grants the authorization, the authorization server will redirect to that callback URL. To parse
* the response, use {@link OAuthCallbackUrl}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class OAuthAuthorizeTemporaryTokenUrl extends GenericUrl {
/**
* The temporary credentials token obtained from temporary credentials request in the
* "oauth_token" parameter. It is found in the {@link OAuthCredentialsResponse#token} returned by
* {@link OAuthGetTemporaryToken#execute()}.
*/
@Key("oauth_token")
public String temporaryToken;
/**
* @param encodedUserAuthorizationUrl encoded user authorization URL
*/
public OAuthAuthorizeTemporaryTokenUrl(String encodedUserAuthorizationUrl) {
super(encodedUserAuthorizationUrl);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
/**
* Generic OAuth 1.0a URL to request a temporary credentials token (or "request token") from an
* authorization server.
* <p>
* Use {@link #execute()} to execute the request. The temporary token acquired with this request is
* found in {@link OAuthCredentialsResponse#token}. This temporary token is used in
* {@link OAuthAuthorizeTemporaryTokenUrl#temporaryToken} to direct the end user to an authorization
* page to allow the end user to authorize the temporary token.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class OAuthGetTemporaryToken extends AbstractOAuthGetToken {
/**
* Optional absolute URI back to which the server will redirect the resource owner when the
* Resource Owner Authorization step is completed or {@code null} for none.
*/
public String callback;
/**
* @param authorizationServerUrl encoded authorization server URL
*/
public OAuthGetTemporaryToken(String authorizationServerUrl) {
super(authorizationServerUrl);
}
@Override
public OAuthParameters createParameters() {
OAuthParameters result = super.createParameters();
result.callback = callback;
return result;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.escape.PercentEscaper;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpTransport;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
/**
* OAuth 1.0a parameter manager.
* <p>
* The only required non-computed fields are {@link #signer} and {@link #consumerKey}. Use
* {@link #token} to specify token or temporary credentials.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class OAuthParameters {
/** Secure random number generator to sign requests. */
private static final SecureRandom RANDOM = new SecureRandom();
/** Required OAuth signature algorithm. */
public OAuthSigner signer;
/**
* Absolute URI back to which the server will redirect the resource owner when the Resource Owner
* Authorization step is completed.
*/
public String callback;
/**
* Required identifier portion of the client credentials (equivalent to a username).
*/
public String consumerKey;
/** Required nonce value. Should be computed using {@link #computeNonce()}. */
public String nonce;
/** Realm. */
public String realm;
/** Signature. Required but normally computed using {@link #computeSignature}. */
public String signature;
/**
* Name of the signature method used by the client to sign the request. Required, but normally
* computed using {@link #computeSignature}.
*/
public String signatureMethod;
/**
* Required timestamp value. Should be computed using {@link #computeTimestamp()}.
*/
public String timestamp;
/**
* Token value used to associate the request with the resource owner or {@code null} if the
* request is not associated with a resource owner.
*/
public String token;
/** The verification code received from the server. */
public String verifier;
/**
* Must either be "1.0" or {@code null} to skip. Provides the version of the authentication
* process as defined in this specification.
*/
public String version;
private static final PercentEscaper ESCAPER = new PercentEscaper("-_.~", false);
/**
* Computes a nonce based on the hex string of a random non-negative long, setting the value of
* the {@link #nonce} field.
*/
public void computeNonce() {
nonce = Long.toHexString(Math.abs(RANDOM.nextLong()));
}
/**
* Computes a timestamp based on the current system time, setting the value of the
* {@link #timestamp} field.
*/
public void computeTimestamp() {
timestamp = Long.toString(System.currentTimeMillis() / 1000);
}
/**
* Computes a new signature based on the fields and the given request method and URL, setting the
* values of the {@link #signature} and {@link #signatureMethod} fields.
*
* @throws GeneralSecurityException general security exception
*/
public void computeSignature(String requestMethod, GenericUrl requestUrl)
throws GeneralSecurityException {
OAuthSigner signer = this.signer;
String signatureMethod = this.signatureMethod = signer.getSignatureMethod();
// oauth_* parameters (except oauth_signature)
TreeMap<String, String> parameters = new TreeMap<String, String>();
putParameterIfValueNotNull(parameters, "oauth_callback", callback);
putParameterIfValueNotNull(parameters, "oauth_consumer_key", consumerKey);
putParameterIfValueNotNull(parameters, "oauth_nonce", nonce);
putParameterIfValueNotNull(parameters, "oauth_signature_method", signatureMethod);
putParameterIfValueNotNull(parameters, "oauth_timestamp", timestamp);
putParameterIfValueNotNull(parameters, "oauth_token", token);
putParameterIfValueNotNull(parameters, "oauth_verifier", verifier);
putParameterIfValueNotNull(parameters, "oauth_version", version);
// parse request URL for query parameters
for (Map.Entry<String, Object> fieldEntry : requestUrl.entrySet()) {
Object value = fieldEntry.getValue();
if (value != null) {
String name = fieldEntry.getKey();
if (value instanceof Collection<?>) {
for (Object repeatedValue : (Collection<?>) value) {
putParameter(parameters, name, repeatedValue);
}
} else {
putParameter(parameters, name, value);
}
}
}
// normalize parameters
StringBuilder parametersBuf = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (first) {
first = false;
} else {
parametersBuf.append('&');
}
parametersBuf.append(entry.getKey());
String value = entry.getValue();
if (value != null) {
parametersBuf.append('=').append(value);
}
}
String normalizedParameters = parametersBuf.toString();
// normalize URL, removing any query parameters and possibly port
GenericUrl normalized = new GenericUrl();
String scheme = normalized.scheme = requestUrl.scheme;
normalized.host = requestUrl.host;
normalized.pathParts = requestUrl.pathParts;
int port = requestUrl.port;
if ("http".equals(scheme) && port == 80 || "https".equals(scheme) && port == 443) {
port = -1;
}
normalized.port = port;
String normalizedPath = normalized.build();
// signature base string
StringBuilder buf = new StringBuilder();
buf.append(escape(requestMethod)).append('&');
buf.append(escape(normalizedPath)).append('&');
buf.append(escape(normalizedParameters));
String signatureBaseString = buf.toString();
signature = signer.computeSignature(signatureBaseString);
}
/**
* Returns the {@code Authorization} header value to use with the OAuth parameter values found in
* the fields.
*/
public String getAuthorizationHeader() {
StringBuilder buf = new StringBuilder("OAuth");
appendParameter(buf, "realm", realm);
appendParameter(buf, "oauth_callback", callback);
appendParameter(buf, "oauth_consumer_key", consumerKey);
appendParameter(buf, "oauth_nonce", nonce);
appendParameter(buf, "oauth_signature", signature);
appendParameter(buf, "oauth_signature_method", signatureMethod);
appendParameter(buf, "oauth_timestamp", timestamp);
appendParameter(buf, "oauth_token", token);
appendParameter(buf, "oauth_verifier", verifier);
appendParameter(buf, "oauth_version", version);
// hack: we have to remove the extra ',' at the end
return buf.substring(0, buf.length() - 1);
}
private void appendParameter(StringBuilder buf, String name, String value) {
if (value != null) {
buf.append(' ').append(escape(name)).append("=\"").append(escape(value)).append("\",");
}
}
private void putParameterIfValueNotNull(
TreeMap<String, String> parameters, String key, String value) {
if (value != null) {
putParameter(parameters, key, value);
}
}
private void putParameter(TreeMap<String, String> parameters, String key, Object value) {
parameters.put(escape(key), value == null ? null : escape(value.toString()));
}
/** Returns the escaped form of the given value using OAuth escaping rules. */
public static String escape(String value) {
return ESCAPER.escape(value);
}
/**
* Performs OAuth HTTP request signing via the {@code Authorization} header as the final HTTP
* request execute intercepter for the given HTTP transport.
*/
public void signRequestsUsingAuthorizationHeader(HttpTransport transport) {
for (HttpExecuteIntercepter intercepter : transport.intercepters) {
if (intercepter.getClass() == OAuthAuthorizationHeaderIntercepter.class) {
((OAuthAuthorizationHeaderIntercepter) intercepter).oauthParameters = this;
return;
}
}
OAuthAuthorizationHeaderIntercepter newIntercepter = new OAuthAuthorizationHeaderIntercepter();
newIntercepter.oauthParameters = this;
transport.intercepters.add(newIntercepter);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* Generic URL that parses the callback URL after a temporary token has been authorized by the end
* user.
* <p>
* The {@link #verifier} is required in order to exchange the authorized temporary token for a
* long-lived access token in {@link OAuthGetAccessToken#verifier}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class OAuthCallbackUrl extends GenericUrl {
/** The temporary credentials identifier received from the client. */
@Key("oauth_token")
public String token;
/** The verification code. */
@Key("oauth_verifier")
public String verifier;
public OAuthCallbackUrl(String encodedUrl) {
super(encodedUrl);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.auth.RsaSha;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
/**
* OAuth {@code "RSA-SHA1"} signature method.
* <p>
* The private key may be retrieved using the utilities in {@link RsaSha}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class OAuthRsaSigner implements OAuthSigner {
/** Private key. */
public PrivateKey privateKey;
public String getSignatureMethod() {
return "RSA-SHA1";
}
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
return RsaSha.sign(privateKey, signatureBaseString);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.util.Key;
/**
* Data to parse a success response to a request for temporary or token credentials.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class OAuthCredentialsResponse {
/** Credentials token. */
@Key("oauth_token")
public String token;
/**
* Credentials shared-secret for use with {@code "HMAC-SHA1"} signature algorithm. Used for
* {@link OAuthHmacSigner#tokenSharedSecret}.
*/
@Key("oauth_token_secret")
public String tokenSecret;
/**
* {@code "true"} for temporary credentials request or {@code null} for a token credentials
* request. The parameter is used to differentiate from previous versions of the protocol.
*/
@Key("oauth_callback_confirmed")
public Boolean callbackConfirmed;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import java.security.GeneralSecurityException;
/**
* OAuth signature method.
*
* @since 1.0
* @author Yaniv Inbar
*/
public interface OAuthSigner {
/** Returns the signature method. */
String getSignatureMethod();
/**
* Returns the signature computed from the given signature base string.
*
* @throws GeneralSecurityException general security exception
*/
String computeSignature(String signatureBaseString) throws GeneralSecurityException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.auth.oauth;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* @author Yaniv Inbar
*/
final class OAuthAuthorizationHeaderIntercepter implements HttpExecuteIntercepter {
OAuthParameters oauthParameters;
public void intercept(HttpRequest request) throws IOException {
oauthParameters.computeNonce();
oauthParameters.computeTimestamp();
try {
oauthParameters.computeSignature(request.method, request.url);
} catch (GeneralSecurityException e) {
IOException io = new IOException();
io.initCause(e);
throw io;
}
request.headers.authorization = oauthParameters.getAuthorizationHeader();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpTransport;
import java.util.HashSet;
/**
* HTTP request execute intercepter for Google API's that wraps HTTP requests -- other than GET or
* POST -- inside of a POST request and uses {@code "X-HTTP-Method-Override"} header to specify the
* actual HTTP method.
* <p>
* It is useful when a firewall only allows the GET and POST methods, or if the underlying HTTP
* library ({@link LowLevelHttpTransport}) does not support the HTTP method.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class MethodOverrideIntercepter implements HttpExecuteIntercepter {
/**
* HTTP methods that need to be overridden.
* <p>
* Any HTTP method not supported by the low level HTTP transport returned by
* {@link HttpTransport#useLowLevelHttpTransport()} is automatically added.
*/
public static final HashSet<String> overriddenMethods = new HashSet<String>();
static {
if (!HttpTransport.useLowLevelHttpTransport().supportsPatch()) {
overriddenMethods.add("PATCH");
}
if (!HttpTransport.useLowLevelHttpTransport().supportsHead()) {
overriddenMethods.add("HEAD");
}
}
public void intercept(HttpRequest request) {
String method = request.method;
if (overriddenMethods.contains(method)) {
request.method = "POST";
request.headers.set("X-HTTP-Method-Override", method);
}
}
/**
* Sets this as the first HTTP request execute intercepter for the given HTTP transport.
*/
public static void setAsFirstFor(HttpTransport transport) {
transport.removeIntercepters(MethodOverrideIntercepter.class);
transport.intercepters.add(0, new MethodOverrideIntercepter());
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.xml.atom;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.xml.AbstractXmlHttpContent;
import com.google.api.client.xml.atom.Atom;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
/**
* 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:
*
* <pre>
* <code>
* static void setContent(HttpRequest request,
* XmlNamespaceDictionary namespaceDictionary, Object originalEntry,
* Object patchedEntry) {
* AtomPatchRelativeToOriginalContent content =
* new AtomPatchRelativeToOriginalContent();
* content.namespaceDictionary = namespaceDictionary;
* content.originalEntry = originalEntry;
* content.patchedEntry = patchedEntry;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomPatchRelativeToOriginalContent extends AbstractXmlHttpContent {
/** Key/value pair data for the updated/patched Atom entry. */
public Object patchedEntry;
/** Key/value pair data for the original unmodified Atom entry. */
public Object originalEntry;
@Override
protected void writeTo(XmlSerializer serializer) throws IOException {
ArrayMap<String, Object> patch = GData.computePatch(patchedEntry, originalEntry);
namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "entry", patch);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.xml.atom;
import com.google.api.client.xml.XmlHttpParser;
import com.google.api.client.xml.atom.AtomContent;
/**
* Serializes Atom XML PATCH HTTP content based on the data key/value mapping object for an Atom
* entry.
* <p>
* Default value for {@link #contentType} is {@link XmlHttpParser#CONTENT_TYPE}.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request,
* XmlNamespaceDictionary namespaceDictionary, Object entry) {
* AtomPatchContent content = new AtomPatchContent();
* content.namespaceDictionary = namespaceDictionary;
* content.entry = entry;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AtomPatchContent extends AtomContent {
public AtomPatchContent() {
contentType = XmlHttpParser.CONTENT_TYPE;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.xml.atom;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
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 parser when the entry class can be computed from the kind.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class MultiKindFeedParser<T> extends AbstractAtomFeedParser<T> {
private final HashMap<String, Class<?>> kindToEntryClassMap = new HashMap<String, Class<?>>();
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 = ClassInfo.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 = this.parser;
String kind = parser.getAttributeValue(GDataHttp.GD_NAMESPACE, "kind");
Class<?> entryClass = this.kindToEntryClassMap.get(kind);
if (entryClass == null) {
throw new IllegalArgumentException("unrecognized kind: " + kind);
}
Object result = ClassInfo.newInstance(entryClass);
Xml.parseElement(parser, result, namespaceDictionary, null);
return result;
}
public static <T, I> MultiKindFeedParser<T> create(HttpResponse response,
XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<?>... entryClasses)
throws XmlPullParserException, IOException {
InputStream content = response.getContent();
try {
Atom.checkContentType(response.contentType);
XmlPullParser parser = Xml.createParser();
parser.setInput(content, null);
MultiKindFeedParser<T> result = new MultiKindFeedParser<T>();
result.parser = parser;
result.inputStream = content;
result.feedClass = feedClass;
result.namespaceDictionary = namespaceDictionary;
result.setEntryClasses(entryClasses);
return result;
} finally {
content.close();
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.xml.atom;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.DataUtil;
import com.google.api.client.util.FieldInfo;
import com.google.api.client.util.GenericData;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeSet;
/**
* Utilities for working with the Atom XML of Google Data API's.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GData {
/**
* 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}.
*/
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}.
*/
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.getKeyNames())) {
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo.isFinal) {
continue;
}
if (++numFields[0] != 1) {
fieldsBuf.append(',');
}
fieldsBuf.append(name);
// TODO: handle Java arrays?
Class<?> fieldClass = fieldInfo.type;
if (Collection.class.isAssignableFrom(fieldClass)) {
// TODO: handle Java collection of Java collection or Java map?
fieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
}
// TODO: implement support for map when server implements support for *:*
if (fieldClass != null) {
if (fieldInfo.isPrimitive) {
if (name.charAt(0) != '@' && !name.equals("text()")) {
// TODO: wait for bug fix from server
// buf.append("/text()");
}
} else if (!Collection.class.isAssignableFrom(fieldClass)
&& !Map.class.isAssignableFrom(fieldClass)) {
int[] subNumFields = new int[1];
int openParenIndex = fieldsBuf.length();
fieldsBuf.append('(');
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(')');
}
}
public static ArrayMap<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;
}
public static ArrayMap<String, Object> computePatchInternal(
FieldsMask fieldsMask, Object patchedObject, Object originalObject) {
ArrayMap<String, Object> result = ArrayMap.create();
Map<String, Object> patchedMap = DataUtil.mapOf(patchedObject);
Map<String, Object> originalMap = DataUtil.mapOf(originalObject);
HashSet<String> fieldNames = new HashSet<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 (FieldInfo.isPrimitive(type)) {
if (originalValue != null && originalValue.equals(patchedValue)) {
continue;
}
fieldsMask.append(name);
// TODO: 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: implement
throw new UnsupportedOperationException(
"not yet implemented: support for patching collections");
} else {
if (originalValue == null) { // TODO: test
fieldsMask.append(name);
result.add(name, DataUtil.mapOf(patchedValue));
} else if (patchedValue == null) { // TODO: 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 GData() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.xml.atom;
/**
* @since 1.0
* @author Yaniv Inbar
*/
public class GDataHttp {
public static final String GD_NAMESPACE = "http://schemas.google.com/g/2005";
private GDataHttp() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
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.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GoogleUrl extends GenericUrl {
/** Whether to pretty print the output. */
@Key
public Boolean prettyprint;
/** Alternate wire format. */
@Key
public String alt;
/** Partial fields mask. */
@Key
public String fields;
public GoogleUrl() {
}
/**
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
*/
public GoogleUrl(String encodedUrl) {
super(encodedUrl);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
import com.google.api.client.http.HttpTransport;
/**
* HTTP transport for Google API's. It's only purpose is to allow for method overriding when the
* firewall does not accept DELETE, PATCH or PUT methods.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleTransport {
/**
* Creates and returns a new HTTP transport with basic default behaviors for working with Google
* API's.
* <p>
* Includes:
* <ul>
* <li>Setting the {@link HttpTransport#defaultHeaders} to a new instance of
* {@link GoogleHeaders}.</li>
* <li>Adding a {@link MethodOverrideIntercepter} as the first HTTP execute intercepter to use
* HTTP method override for unsupported HTTP methods (calls
* {@link MethodOverrideIntercepter#setAsFirstFor(HttpTransport)}.</li>
* </ul>
* <p>
* Sample usage:
*
* <pre>
* <code>
static HttpTransport createTransport() {
HttpTransport transport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
headers.setApplicationName("Google-Sample/1.0");
headers.gdataVersion = "2";
return transport;
}
* </code>
* </pre>
*
* @return HTTP transport
*/
public static HttpTransport create() {
HttpTransport transport = new HttpTransport();
MethodOverrideIntercepter.setAsFirstFor(transport);
transport.defaultHeaders = new GoogleHeaders();
return transport;
}
private GoogleTransport() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.clientlogin;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.auth.AuthKeyValueParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.Key;
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 {
@Key("source")
public String applicationName;
@Key("service")
public String authTokenType;
@Key("Email")
public String username;
@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;
@Key("logintoken")
public String captchaToken;
@Key("logincaptcha")
public String captchaAnswer;
/** Key/value data to parse a success response. */
public static final class Response {
@Key("Auth")
public String auth;
public String getAuthorizationHeaderValue() {
return GoogleHeaders.getGoogleLoginValue(auth);
}
/**
* Sets the authorization header for the given Google transport using the authentication token.
*/
public void setAuthorizationHeader(HttpTransport googleTransport) {
googleTransport.defaultHeaders.authorization = GoogleHeaders.getGoogleLoginValue(auth);
}
}
/** 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 HttpResponseException if the authentication response has an error code, such as for a
* CAPTCHA challenge. Call {@link HttpResponseException#response exception.response}.
* {@link HttpResponse#parseAs(Class) parseAs}({@link ClientLogin.ErrorInfo
* ClientLoginAuthenticator.ErrorInfo}.class) to parse the response.
* @throws IOException some other kind of I/O exception
*/
public Response authenticate() throws HttpResponseException, IOException {
HttpTransport transport = new HttpTransport();
transport.addParser(AuthKeyValueParser.INSTANCE);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://www.google.com/accounts/ClientLogin");
UrlEncodedContent content = new UrlEncodedContent();
content.data = this;
request.disableContentLogging = true;
request.content = content;
return request.execute().parseAs(Response.class);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.oauth;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthGetTemporaryToken;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.util.Key;
/**
* Generic Google OAuth 1.0a URL to request a temporary credentials token (or "request token") from
* the Google Authorization server.
* <p>
* Use {@link #execute()} to execute the request. Google verifies that the requesting application
* has been registered with Google or is using an approved signature (in the case of installed
* applications). The temporary token acquired with this request is found in
* {@link OAuthCredentialsResponse#token} . This temporary token is used in
* {@link GoogleOAuthAuthorizeTemporaryTokenUrl#temporaryToken} to direct the end user to a Google
* Accounts web page to allow the end user to authorize the temporary token.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleOAuthGetTemporaryToken extends OAuthGetTemporaryToken {
/**
* Optional string identifying the application or {@code null} for none. This string is displayed
* to end users on Google's authorization confirmation page. For registered applications, the
* value of this parameter overrides the name set during registration and also triggers a message
* to the user that the identity can't be verified. For unregistered applications, this parameter
* enables them to specify an application name, In the case of unregistered applications, if this
* parameter is not set, Google identifies the application using the URL value of oauth_callback;
* if neither parameter is set, Google uses the string "anonymous".
*/
@Key("xoauth_displayname")
public String displayName;
/**
* Required URL identifying the service(s) to be accessed. The resulting token enables access to
* the specified service(s) only. Scopes are defined by each Google service; see the service's
* documentation for the correct value. To specify more than one scope, list each one separated
* with a space.
*/
@Key
public String scope;
public GoogleOAuthGetTemporaryToken() {
super("https://www.google.com/accounts/OAuthGetRequestToken");
}
@Override
public OAuthParameters createParameters() {
OAuthParameters result = super.createParameters();
result.callback = callback;
return result;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.oauth;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
/**
* Google's OAuth domain-wide delegation requires an e-mail address of the user whose data you are
* trying to access via {@link #requestorId} on every HTTP request.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleOAuthDomainWideDelegation implements HttpExecuteIntercepter {
/**
* Generic URL that extends {@link GoogleUrl} and also provides the {@link #requestorId}
* parameter.
*/
public static final class Url extends GoogleUrl {
/** Email address of the user whose data you are trying to access. */
@Key("xoauth_requestor_id")
public String requestorId;
/**
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
*/
public Url(String encodedUrl) {
super(encodedUrl);
}
}
/** Email address of the user whose data you are trying to access. */
public String requestorId;
public void intercept(HttpRequest request) {
request.url.set("xoauth_requestor_id", requestorId);
}
/**
* Performs OAuth HTTP request signing via query parameter for the {@code xoauth_requestor_id} and
* the {@code Authorization} header as the final HTTP request execute intercepter for the given
* HTTP request execute manager.
*
* @param transport HTTP transport
* @param parameters OAuth parameters; the {@link OAuthParameters#signer} and
* {@link OAuthParameters#consumerKey} should be set
*/
public void signRequests(HttpTransport transport, OAuthParameters parameters) {
transport.intercepters.add(this);
parameters.signRequestsUsingAuthorizationHeader(transport);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.oauth;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthGetAccessToken;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import java.io.IOException;
/**
* Generic Google OAuth 1.0a URL to request to exchange the temporary credentials token (or "request
* token") for a long-lived credentials token (or "access token") from the Google Authorization
* server.
* <p>
* Use {@link #execute()} to execute the request. The long-lived access token acquired with this
* request is found in {@link OAuthCredentialsResponse#token} . This token must be stored. It may
* then be used to authorize HTTP requests to protected resources in Google services by setting the
* {@link OAuthParameters#token}, and invoking
* {@link OAuthParameters#signRequestsUsingAuthorizationHeader(HttpTransport)}.
* <p>
* To revoke the stored access token, use {@link #revokeAccessToken}.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleOAuthGetAccessToken extends OAuthGetAccessToken {
public GoogleOAuthGetAccessToken() {
super("https://www.google.com/accounts/OAuthGetAccessToken");
}
/**
* Revokes the long-lived access token.
*
* @param parameters OAuth parameters
* @throws IOException I/O exception
*/
public static void revokeAccessToken(OAuthParameters parameters) throws IOException {
HttpTransport transport = new HttpTransport();
parameters.signRequestsUsingAuthorizationHeader(transport);
HttpRequest request = transport.buildGetRequest();
request.setUrl("https://www.google.com/accounts/AuthSubRevokeToken");
request.execute().ignore();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.oauth;
import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.auth.oauth.OAuthCallbackUrl;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthGetTemporaryToken;
import com.google.api.client.util.Key;
/**
* Google OAuth 1.0a URL builder for a Google Accounts web page to allow the end user to authorize
* the temporary token.
* <p>
* This only supports Google API's that use {@code
* "https://www.google.com/accounts/OAuthAuthorizeToken"} for authorizing temporary tokens.
* </p>
* <p>
* The {@link #temporaryToken} should be set from the {@link OAuthCredentialsResponse#token}
* returned by {@link GoogleOAuthGetTemporaryToken#execute()}. Use {@link #build()} to build the
* authorization URL. If a {@link OAuthGetTemporaryToken#callback} was specified, after the end user
* grants the authorization, the Google authorization server will redirect to that callback URL. To
* parse the response, use {@link OAuthCallbackUrl}.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleOAuthAuthorizeTemporaryTokenUrl extends OAuthAuthorizeTemporaryTokenUrl {
/**
* Optionally use {@code "mobile"} to for a mobile version of the approval page or {@code null}
* for normal.
*/
@Key("btmpl")
public String template;
/**
* Optional value identifying a particular Google Apps (hosted) domain account to be accessed (for
* example, 'mycollege.edu') or {@code null} or {@code "default"} for a regular Google account
* ('username@gmail.com').
*/
@Key("hd")
public String hostedDomain;
/**
* Optional ISO 639 country code identifying what language the approval page should be translated
* in (for example, 'hl=en' for English) or {@code null} for the user's selected language.
*/
@Key("hl")
public String language;
public GoogleOAuthAuthorizeTemporaryTokenUrl() {
super("https://www.google.com/accounts/OAuthAuthorizeToken");
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.storage;
import com.google.api.client.auth.HmacSha;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
/**
* Google Storage for Developers has a custom authentication method described in <a href=
* "https://code.google.com/apis/storage/docs/developer-guide.html#authentication"
* >Authentication</a> .
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class GoogleStorageAuthentication {
/**
* Sets the {@code "Authorization"} header for every executed HTTP request for the given HTTP
* transport.
* <p>
* Any existing HTTP request execute intercepter for Google Storage will be removed.
*
* @param transport HTTP transport
* @param accessKey 20 character access key that identifies the client accessing the stored data
* @param secret secret associated with the access key
*/
public static void authorize(HttpTransport transport, String accessKey, String secret) {
transport.removeIntercepters(Intercepter.class);
Intercepter intercepter = new Intercepter();
intercepter.accessKey = accessKey;
intercepter.secret = secret;
transport.intercepters.add(intercepter);
}
private static final String HOST = "commondatastorage.googleapis.com";
static class Intercepter implements HttpExecuteIntercepter {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
String accessKey;
String secret;
public void intercept(HttpRequest request) throws IOException {
HttpHeaders headers = request.headers;
StringBuilder messageBuf = new StringBuilder();
// canonical headers
// HTTP method
messageBuf.append(request.method).append('\n');
// content MD5
String contentMD5 = headers.contentMD5;
if (contentMD5 != null) {
messageBuf.append(contentMD5);
}
messageBuf.append('\n');
// content type
HttpContent content = request.content;
if (content != null) {
String contentType = content.getType();
messageBuf.append(contentType);
}
messageBuf.append('\n');
// date
Object date = headers.date;
if (date != null) {
messageBuf.append(headers.date);
}
messageBuf.append('\n');
// canonical extension headers
TreeMap<String, String> extensions = new TreeMap<String, String>();
for (Map.Entry<String, Object> headerEntry : headers.entrySet()) {
String name = headerEntry.getKey().toLowerCase();
Object value = headerEntry.getValue();
if (value != null && name.startsWith("x-goog-")) {
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Object repeatedValue : collectionValue) {
if (first) {
first = false;
} else {
buf.append(',');
}
buf.append(WHITESPACE_PATTERN.matcher(repeatedValue.toString()).replaceAll(" "));
}
extensions.put(name, buf.toString());
} else {
extensions.put(name, WHITESPACE_PATTERN.matcher(value.toString()).replaceAll(" "));
}
}
}
for (Map.Entry<String, String> extensionEntry : extensions.entrySet()) {
messageBuf
.append(extensionEntry.getKey())
.append(':')
.append(extensionEntry.getValue())
.append('\n');
}
// canonical resource
GenericUrl url = request.url;
String host = url.host;
if (!host.endsWith(HOST)) {
throw new IllegalArgumentException("missing host " + HOST);
}
int bucketNameLength = host.length() - HOST.length() - 1;
if (bucketNameLength > 0) {
String bucket = host.substring(0, bucketNameLength);
if (!bucket.equals("c")) {
messageBuf.append('/').append(bucket);
}
}
if (url.pathParts != null) {
messageBuf.append(url.getRawPath());
}
if (url.get("acl") != null) {
messageBuf.append("?acl");
} else if (url.get("location") != null) {
messageBuf.append("?location");
} else if (url.get("logging") != null) {
messageBuf.append("?logging");
} else if (url.get("requestPayment") != null) {
messageBuf.append("?requestPayment");
} else if (url.get("torrent") != null) {
messageBuf.append("?torrent");
}
try {
request.headers.authorization =
"GOOG1 " + accessKey + ":" + HmacSha.sign(secret, messageBuf.toString());
} catch (GeneralSecurityException e) {
IOException io = new IOException();
io.initCause(e);
throw io;
}
}
}
private GoogleStorageAuthentication() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.authsub;
import com.google.api.client.googleapis.auth.AuthKeyValueParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.security.PrivateKey;
/**
* AuthSub token manager for a single user.
* <p>
* To properly initialize, set:
* <ul>
* <li>{@link #setToken}: single-use or session token (required)</li>
* <li>{@link #transport}: Google transport (recommended)</li>
* <li>{@link #privateKey}: private key for secure AuthSub (recommended)</li>
* </ul>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AuthSubHelper {
/** Private key for secure AuthSub or {@code null} for non-secure AuthSub. */
private PrivateKey privateKey;
/**
* Google transport whose authorization header to set or {@code null} to ignore (for example if
* using an alternative HTTP library).
*/
private HttpTransport transport;
/** HTTP transport for AuthSub requests. */
private final HttpTransport authSubTransport = new HttpTransport();
/** Token (may be single use or session). */
private String token;
public AuthSubHelper() {
authSubTransport.addParser(AuthKeyValueParser.INSTANCE);
}
/**
* Key/value data to parse a success response for an AuthSubSessionToken request.
*/
public static final class SessionTokenResponse {
@Key("Token")
public String sessionToken;
}
/**
* Key/value data to parse a success response for an AuthSubTokenInfo request.
*/
public static final class TokenInfoResponse {
@Key("Secure")
public boolean secure;
@Key("Target")
public String target;
@Key("Scope")
public String scope;
}
/**
* Sets to the given private key for secure AuthSub or {@code null} for non-secure AuthSub.
* <p>
* Updates the authorization header of the Google transport (set using
* {@link #setTransport(HttpTransport)}).
*/
public void setPrivateKey(PrivateKey privateKey) {
if (privateKey != this.privateKey) {
this.privateKey = privateKey;
updateAuthorizationHeaders();
}
}
/**
* Sets to the given Google transport whose authorization header to set or {@code null} to ignore
* (for example if using an alternative HTTP library).
* <p>
* Updates the authorization header of the Google transport.
*/
public void setTransport(HttpTransport transport) {
if (transport != this.transport) {
this.transport = transport;
updateAuthorizationHeaders();
}
}
/**
* Sets to the given single-use or session token (or resets any existing token if {@code null}).
* <p>
* Any previous stored single-use or session token will be forgotten. Updates the authorization
* header of the Google transport (set using {@link #setTransport(HttpTransport)}).
*/
public void setToken(String token) {
if (token != this.token) {
this.token = token;
updateAuthorizationHeaders();
}
}
/**
* Exchanges the single-use token for a session token as described in <a href=
* "http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubSessionToken"
* >AuthSubSessionToken</a>. Sets the authorization header of the Google transport using the
* session token, and automatically sets the token used by this instance using
* {@link #setToken(String)}.
* <p>
* Note that Google allows at most 10 session tokens per use per web application, so the session
* token for each user must be persisted.
*
* @return session token
* @throws HttpResponseException if the authentication response has an error code
* @throws IOException some other kind of I/O exception
*/
public String exchangeForSessionToken() throws IOException {
HttpTransport authSubTransport = this.authSubTransport;
HttpRequest request = authSubTransport.buildGetRequest();
request.setUrl("https://www.google.com/accounts/AuthSubSessionToken");
SessionTokenResponse sessionTokenResponse =
request.execute().parseAs(SessionTokenResponse.class);
String sessionToken = sessionTokenResponse.sessionToken;
setToken(sessionToken);
return sessionToken;
}
/**
* Revokes the session token. Clears any existing authorization header of the Google transport and
* automatically resets the token by calling {@code setToken(null)}.
* <p>
* See <a href= "http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubRevokeToken"
* >AuthSubRevokeToken</a> for protocol details.
*
* @throws HttpResponseException if the authentication response has an error code
* @throws IOException some other kind of I/O exception
*/
public void revokeSessionToken() throws IOException {
HttpTransport authSubTransport = this.authSubTransport;
HttpRequest request = authSubTransport.buildGetRequest();
request.setUrl("https://www.google.com/accounts/AuthSubRevokeToken");
request.execute().ignore();
setToken(null);
}
/**
* Retries the token information as described in <a href=
* "http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubTokenInfo"
* >AuthSubTokenInfo</a>.
*
* @throws HttpResponseException if the authentication response has an error code
* @throws IOException some other kind of I/O exception
*/
public TokenInfoResponse requestTokenInfo() throws IOException {
HttpTransport authSubTransport = this.authSubTransport;
HttpRequest request = authSubTransport.buildGetRequest();
request.setUrl("https://www.google.com/accounts/AuthSubTokenInfo");
HttpResponse response = request.execute();
if (response.getParser() == null) {
throw new IllegalStateException(response.parseAsString());
}
return response.parseAs(TokenInfoResponse.class);
}
/** Updates the authorization headers. */
private void updateAuthorizationHeaders() {
HttpTransport transport = this.transport;
if (transport != null) {
setAuthorizationHeaderOf(transport);
}
HttpTransport authSubTransport = this.authSubTransport;
if (authSubTransport != null) {
setAuthorizationHeaderOf(authSubTransport);
}
}
/**
* Sets the authorization header for the given HTTP transport based on the current token.
*/
private void setAuthorizationHeaderOf(HttpTransport transoprt) {
transport.intercepters.add(new AuthSubIntercepter(token, privateKey));
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.authsub;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* Generic URL that builds an AuthSub request URL to retrieve a single-use token. See <a href=
* "http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubRequest" >documentation</a>.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AuthSubSingleUseTokenRequestUrl extends GenericUrl {
/**
* Generic URL with a token parameter that can be used to extract the AuthSub single-use token
* from the AuthSubRequest response.
*/
public static class ResponseUrl extends GenericUrl {
@Key
public String token;
public ResponseUrl(String url) {
super(url);
}
}
/**
* (required) URL the user should be redirected to after a successful login. This value should be
* a page on the web application site, and can include query parameters.
*/
@Key("next")
public String nextUrl;
/**
* (required) URL identifying the service(s) to be accessed; see documentation for the service for
* the correct value(s). The resulting token enables access to the specified service(s) only. To
* specify more than one scope, list each one separated with a space (encodes as "%20").
*/
@Key
public String scope;
/**
* Optionally use {@code "mobile"} to for a mobile version of the approval page or {@code null}
* for normal.
*/
@Key("btmpl")
public String template;
/**
* Optional value identifying a particular Google Apps (hosted) domain account to be accessed (for
* example, 'mycollege.edu') or {@code null} or {@code "default"} for a regular Google account
* ('username@gmail.com').
*/
@Key("hd")
public String hostedDomain;
/**
* Optional ISO 639 country code identifying what language the approval page should be translated
* in (for example, 'hl=en' for English) or {@code null} for the user's selected language.
*/
@Key("hl")
public String language;
/**
* (optional) Boolean flag indicating whether the authorization transaction should issue a secure
* token (1) or a non-secure token (0). Secure tokens are available to registered applications
* only.
*/
@Key
public int secure;
/**
* (optional) Boolean flag indicating whether the one-time-use token may be exchanged for a
* session token (1) or not (0).
*/
@Key
public int session;
public AuthSubSingleUseTokenRequestUrl() {
super("https://www.google.com/accounts/AuthSubRequest");
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.authsub;
import com.google.api.client.auth.RsaSha;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.SecureRandom;
/**
* @since 1.0
* @author Yaniv Inbar
*/
public class AuthSub {
/** Secure random number generator to sign requests. */
private static final SecureRandom RANDOM = new SecureRandom();
/**
* Returns {@code AuthSub} authorization header value based on the given authentication token.
*/
public static String getAuthorizationHeaderValue(String token) {
return getAuthSubTokenPrefix(token).toString();
}
/**
* Returns {@code AuthSub} authorization header value based on the given authentication token,
* private key, request method, and request URL.
*
* @throws GeneralSecurityException
*/
public static String getAuthorizationHeaderValue(
String token, PrivateKey privateKey, String requestMethod, String requestUrl)
throws GeneralSecurityException {
StringBuilder buf = getAuthSubTokenPrefix(token);
if (privateKey != null) {
String algorithm = privateKey.getAlgorithm();
if (!"RSA".equals(algorithm)) {
throw new IllegalArgumentException(
"Only supported algorithm for private key is RSA: " + algorithm);
}
long timestamp = System.currentTimeMillis() / 1000;
long nonce = Math.abs(RANDOM.nextLong());
String data = new StringBuilder()
.append(requestMethod)
.append(' ')
.append(requestUrl)
.append(' ')
.append(timestamp)
.append(' ')
.append(nonce)
.toString();
String sig = RsaSha.sign(privateKey, data);
buf
.append(" sigalg=\"rsa-sha1\" data=\"")
.append(data)
.append("\" sig=\"")
.append(sig)
.append('"');
}
return buf.toString();
}
private static StringBuilder getAuthSubTokenPrefix(String token) {
return new StringBuilder("AuthSub token=\"").append(token).append('"');
}
private AuthSub() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth.authsub;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
/**
* @author Yaniv Inbar
*/
final class AuthSubIntercepter implements HttpExecuteIntercepter {
private final String token;
private final PrivateKey privateKey;
AuthSubIntercepter(String token, PrivateKey privateKey) {
this.token = token;
this.privateKey = privateKey;
}
public void intercept(HttpRequest request) throws IOException {
try {
String header;
String token = this.token;
PrivateKey privateKey = this.privateKey;
if (token == null) {
header = null;
} else if (privateKey == null) {
header = AuthSub.getAuthorizationHeaderValue(token);
} else {
header = AuthSub.getAuthorizationHeaderValue(
token, privateKey, request.method, request.url.build());
}
request.headers.authorization = header;
} catch (GeneralSecurityException e) {
IOException wrap = new IOException();
wrap.initCause(e);
throw wrap;
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.auth;
import com.google.api.client.http.HttpParser;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Map;
/**
* HTTP parser for Google response to an Authorization request.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class AuthKeyValueParser implements HttpParser {
/** 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 {
T newInstance = ClassInfo.newInstance(dataClass);
ClassInfo classInfo = ClassInfo.of(dataClass);
response.disableContentLogging = true;
InputStream content = response.getContent();
try {
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);
}
}
} finally {
content.close();
}
return newInstance;
}
private AuthKeyValueParser() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonHttpParser;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import java.io.IOException;
/**
* Parses HTTP JSON-C response content into an data class of key/value pairs, assuming the data is
* wrapped in a {@code "data"} envelope.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setParser(GoogleTransport transport) {
* transport.addParser(new JsonCParser());
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonCParser extends JsonHttpParser {
@Override
public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException {
return Json.parseAndClose(parserForResponse(response), dataClass, null);
}
/**
* Returns a JSON parser to use for parsing the given HTTP response, skipped over the {@code
* "data"} envelope.
* <p>
* The parser will be closed if any throwable is thrown. The current token will be the value of
* the {@code "data"} key.
*
* @param response HTTP response
* @return JSON parser
* @throws IllegalArgumentException if content type is not {@link Json#CONTENT_TYPE} or if {@code
* "data"} key is not found
* @throws IOException I/O exception
*/
public static org.codehaus.jackson.JsonParser parserForResponse(HttpResponse response)
throws IOException {
// check for JSON content type
String contentType = response.contentType;
if (contentType == null || !contentType.startsWith(Json.CONTENT_TYPE)) {
throw new IllegalArgumentException(
"Wrong content type: expected <" + Json.CONTENT_TYPE + "> but got <" + contentType + ">");
}
// parse
boolean failed = true;
JsonParser parser = JsonHttpParser.parserForResponse(response);
try {
Json.skipToKey(parser, response.isSuccessStatusCode ? "data" : "error");
if (parser.getCurrentToken() == JsonToken.END_OBJECT) {
throw new IllegalArgumentException("data key not found");
}
failed = false;
return parser;
} finally {
if (failed) {
parser.close();
}
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.escape.CharEscapers;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceDefinition;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceMethod;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import com.google.api.client.util.DataUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Manages HTTP requests for a version of a Google API service with a simple interface based on the
* new experimental Discovery API.
*
* @since 1.1
* @author Yaniv Inbar
*/
public final class GoogleApi {
/**
* (Required) Name of the Google API, for example <code>buzz</code>.
*/
public String name;
/**
* (Required) Version of the Google API, for example <code>v1</code>.
*/
public String version;
/**
* HTTP transport required for building requests in {@link #buildRequest(String, Object)}.
* <p>
* It is initialized using {@link GoogleTransport#create()}.
*/
public HttpTransport transport = GoogleTransport.create();
/**
* Service definition, normally set by {@link #load()}.
*/
public ServiceDefinition serviceDefinition;
/**
* Forces the discovery document to be loaded, even if the service definition has already been
* loaded.
*/
public void load() throws IOException {
DiscoveryDocument doc = DiscoveryDocument.load(name);
serviceDefinition = doc.apiDefinition.get(version);
Preconditions.checkNotNull(serviceDefinition, "version not found: %s", version);
}
/**
* Creates an HTTP request based on the given method name and parameters.
* <p>
* If the discovery document has not yet been loaded, it will call {@link #load()}.
* </p>
*
* @param fullyQualifiedMethodName name of method as defined in Discovery document of format
* "resourceName.methodName"
* @param parameters user defined key / value data mapping or {@code null} for none
* @return HTTP request
* @throws IOException I/O exception reading
*/
public HttpRequest buildRequest(String fullyQualifiedMethodName, Object parameters)
throws IOException {
// load service method
String name = this.name;
String version = this.version;
HttpTransport transport = this.transport;
ServiceDefinition serviceDefinition = this.serviceDefinition;
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(version);
Preconditions.checkNotNull(transport);
Preconditions.checkNotNull(fullyQualifiedMethodName);
if (serviceDefinition == null) {
load();
}
ServiceMethod method = serviceDefinition.getResourceMethod(fullyQualifiedMethodName);
Preconditions.checkNotNull(method, "method not found: %s", fullyQualifiedMethodName);
// Create request for specified method
HttpRequest request = transport.buildRequest();
request.method = method.httpMethod;
HashMap<String, String> requestMap = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : DataUtil.mapOf(parameters).entrySet()) {
Object value = entry.getValue();
if (value != null) {
requestMap.put(entry.getKey(), value.toString());
}
}
GenericUrl url = new GenericUrl(serviceDefinition.baseUrl);
// parse path URL
String pathUrl = method.pathUrl;
StringBuilder pathBuf = new StringBuilder();
int cur = 0;
int length = pathUrl.length();
while (cur < length) {
int next = pathUrl.indexOf('{', cur);
if (next == -1) {
pathBuf.append(pathUrl.substring(cur));
break;
}
pathBuf.append(pathUrl.substring(cur, next));
int close = pathUrl.indexOf('}', next + 2);
String varName = pathUrl.substring(next + 1, close);
cur = close + 1;
String value = requestMap.remove(varName);
if (value == null) {
throw new IllegalArgumentException("missing required path parameter: " + varName);
}
pathBuf.append(CharEscapers.escapeUriPath(value));
}
url.appendRawPath(pathBuf.toString());
// all other parameters are assumed to be query parameters
url.putAll(requestMap);
request.url = url;
return request;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.json.CustomizeJsonParser;
import com.google.api.client.json.Json;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import java.io.IOException;
/**
* Abstract base class for a Google JSON-C feed parser when the feed class is known in advance.
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class AbstractJsonFeedParser<T> {
private boolean feedParsed;
final JsonParser parser;
final Class<T> feedClass;
AbstractJsonFeedParser(JsonParser parser, Class<T> feedClass) {
this.parser = parser;
this.feedClass = feedClass;
}
/**
* Parse the feed and return a new parsed instance of the feed class. This method can be skipped
* if all you want are the items.
*/
public T parseFeed() throws IOException {
boolean close = true;
try {
this.feedParsed = true;
T result = Json.parse(this.parser, this.feedClass, new StopAtItems());
close = false;
return result;
} finally {
if (close) {
close();
}
}
}
final class StopAtItems extends CustomizeJsonParser {
@Override
public boolean stopAt(Object context, String key) {
return "items".equals(key)
&& context.getClass().equals(AbstractJsonFeedParser.this.feedClass);
}
}
/**
* Parse the next item in the feed and return a new parsed instanceof of the item class. If there
* is no item to parse, it will return {@code null} and automatically close the parser (in which
* case there is no need to call {@link #close()}.
*/
public Object parseNextItem() throws IOException {
JsonParser parser = this.parser;
if (!this.feedParsed) {
this.feedParsed = true;
Json.skipToKey(parser, "items");
}
boolean close = true;
try {
if (parser.nextToken() == JsonToken.START_OBJECT) {
Object result = parseItemInternal();
close = false;
return result;
}
} finally {
if (close) {
close();
}
}
return null;
}
/** Closes the underlying parser. */
public void close() throws IOException {
this.parser.close();
}
abstract Object parseItemInternal() throws IOException;
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.Json;
import com.google.api.client.util.ClassInfo;
import com.google.api.client.util.FieldInfo;
import org.codehaus.jackson.JsonParser;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
/**
* Google JSON-C feed parser when the item class can be computed from the kind.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonMultiKindFeedParser<T> extends AbstractJsonFeedParser<T> {
private final HashMap<String, Class<?>> kindToItemClassMap = new HashMap<String, Class<?>>();
public JsonMultiKindFeedParser(JsonParser parser, Class<T> feedClass, Class<?>... itemClasses) {
super(parser, feedClass);
int numItems = itemClasses.length;
HashMap<String, Class<?>> kindToItemClassMap = this.kindToItemClassMap;
for (int i = 0; i < numItems; i++) {
Class<?> itemClass = itemClasses[i];
ClassInfo classInfo = ClassInfo.of(itemClass);
Field field = classInfo.getField("kind");
if (field == null) {
throw new IllegalArgumentException("missing kind field for " + itemClass.getName());
}
Object item = ClassInfo.newInstance(itemClass);
String kind = (String) FieldInfo.getFieldValue(field, item);
if (kind == null) {
throw new IllegalArgumentException(
"missing value for kind field in " + itemClass.getName());
}
kindToItemClassMap.put(kind, itemClass);
}
}
@Override
Object parseItemInternal() throws IOException {
parser.nextToken();
String key = parser.getCurrentName();
if (key != "kind") {
throw new IllegalArgumentException("expected kind field: " + key);
}
parser.nextToken();
String kind = parser.getText();
Class<?> itemClass = kindToItemClassMap.get(kind);
if (itemClass == null) {
throw new IllegalArgumentException("unrecognized kind: " + kind);
}
return Json.parse(parser, itemClass, null);
}
public static <T, I> JsonMultiKindFeedParser<T> use(
HttpResponse response, Class<T> feedClass, Class<?>... itemClasses) throws IOException {
return new JsonMultiKindFeedParser<T>(
JsonCParser.parserForResponse(response), feedClass, itemClasses);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonHttpContent;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.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>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request, Object data) {
* JsonCContent content = new JsonCContent();
* content.data = data;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonCContent extends JsonHttpContent {
@Override
public void writeTo(OutputStream out) throws IOException {
JsonGenerator generator = Json.JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
generator.writeStartObject();
generator.writeFieldName("data");
Json.serialize(generator, data);
generator.writeEndObject();
generator.close();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.Json;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.Key;
import org.codehaus.jackson.JsonParser;
import java.io.IOException;
import java.util.Map;
/**
* Manages a JSON-formatted document from the experimental Google Discovery API version 0.1.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class DiscoveryDocument {
/**
* Defines all versions of an API.
*
* @since 1.1
*/
public static final class APIDefinition extends ArrayMap<String, ServiceDefinition> {
}
/** Defines a specific version of an API. */
public static final class ServiceDefinition {
/**
* Base URL for service endpoint.
*
* @since 1.1
*/
@Key
public String baseUrl;
/** Map from the resource name to the resource definition. */
@Key
public Map<String, ServiceResource> resources;
/**
* Returns {@link ServiceMethod} definition for given method name. Method identifier is of
* format "resourceName.methodName".
*/
public ServiceMethod getResourceMethod(String methodIdentifier) {
int dot = methodIdentifier.indexOf('.');
String resourceName = methodIdentifier.substring(0, dot);
String methodName = methodIdentifier.substring(dot + 1);
ServiceResource resource = resources.get(resourceName);
return resource == null ? null : resource.methods.get(methodName);
}
/**
* Returns url for requested method. Method identifier is of format "resourceName.methodName".
*/
String getResourceUrl(String methodIdentifier) {
return baseUrl + getResourceMethod(methodIdentifier).pathUrl;
}
}
/** Defines a resource in a service definition. */
public static final class ServiceResource {
/** Map from method name to method definition. */
@Key
public Map<String, ServiceMethod> methods;
}
/** Defines a method of a service resource. */
public static final class ServiceMethod {
/**
* Path URL relative to base URL.
*
* @since 1.1
*/
@Key
public String pathUrl;
/** HTTP method name. */
@Key
public String httpMethod;
/** Map from parameter name to parameter definition. */
@Key
public Map<String, ServiceParameter> parameters;
/**
* Method type.
*
* @since 1.1
*/
@Key
public final String methodType = "rest";
}
/** Defines a parameter to a service method. */
public static final class ServiceParameter {
/** Whether the parameter is required. */
@Key
public boolean required;
}
/**
* Definition of all versions defined in this Google API.
*
* @since 1.1
*/
public final APIDefinition apiDefinition = new APIDefinition();
private DiscoveryDocument() {
}
/**
* Executes a request for the JSON-formatted discovery document for the API of the given name.
*
* @param apiName API name
* @return discovery document
* @throws IOException I/O exception executing request
*/
public static DiscoveryDocument load(String apiName) throws IOException {
GenericUrl discoveryUrl = new GenericUrl("https://www.googleapis.com/discovery/0.1/describe");
discoveryUrl.put("api", apiName);
HttpTransport transport = GoogleTransport.create();
HttpRequest request = transport.buildGetRequest();
request.url = discoveryUrl;
JsonParser parser = JsonCParser.parserForResponse(request.execute());
Json.skipToKey(parser, apiName);
DiscoveryDocument result = new DiscoveryDocument();
APIDefinition apiDefinition = result.apiDefinition;
Json.parseAndClose(parser, apiDefinition, null);
return result;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.json;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.Json;
import org.codehaus.jackson.JsonParser;
import java.io.IOException;
/**
* Google JSON-C feed parser when the item class is known in advance.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class JsonFeedParser<T, I> extends AbstractJsonFeedParser<T> {
private final Class<I> itemClass;
public JsonFeedParser(JsonParser parser, Class<T> feedClass, Class<I> itemClass) {
super(parser, feedClass);
this.itemClass = itemClass;
}
@SuppressWarnings("unchecked")
@Override
public I parseNextItem() throws IOException {
return (I) super.parseNextItem();
}
@Override
Object parseItemInternal() throws IOException {
return Json.parse(parser, itemClass, null);
}
public static <T, I> JsonFeedParser<T, I> use(
HttpResponse response, Class<T> feedClass, Class<I> itemClass) throws IOException {
JsonParser parser = JsonCParser.parserForResponse(response);
return new JsonFeedParser<T, I>(parser, feedClass, itemClass);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
import com.google.api.client.escape.PercentEscaper;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.util.Key;
/**
* HTTP headers for Google API's.
*
* @since 1.0
* @author Yaniv Inbar
*/
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")
public String gdataVersion;
/**
* Escaped {@code "Slug"} header value, which must be escaped using {@link #SLUG_ESCAPER}.
*
* @see #setSlugFromFileName(String)
*/
@Key("Slug")
public String slug;
/** {@code "X-GData-Client"} header. */
@Key("X-GData-Client")
public String gdataClient;
/**
* {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}.
*
* @see #setDeveloperId(String)
*/
@Key("X-GData-Key")
public String gdataKey;
/**
* {@code "x-goog-acl"} header that lets you apply predefined (canned) ACLs to a bucket or object
* when you upload it or create it.
*/
@Key("x-goog-acl")
public String googAcl;
/**
* {@code "x-goog-copy-source"} header that specifies the destination bucket and object for a copy
* operation.
*/
@Key("x-goog-copy-source")
public String googCopySource;
/**
* {@code "x-goog-copy-source-if-match"} header that specifies the conditions for a copy
* operation.
*/
@Key("x-goog-copy-source-if-match")
public String googCopySourceIfMatch;
/**
* {@code "x-goog-copy-source-if-none-match"} header that specifies the conditions for a copy
* operation.
*/
@Key("x-goog-copy-source-if-none-match")
public String googCopySourceIfNoneMatch;
/**
* {@code "x-goog-copy-source-if-modified-since"} header that specifies the conditions for a copy
* operation.
*/
@Key("x-goog-copy-source-if-modified-since")
public String googCopySourceIfModifiedSince;
/**
* {@code "x-goog-copy-source-if-unmodified-since"} header that specifies the conditions for a
* copy operation.
*/
@Key("x-goog-copy-source-if-unmodified-since")
public String googCopySourceIfUnmodifiedSince;
/**
* {@code "x-goog-date"} header that specifies a time stamp for authenticated requests.
*/
@Key("x-goog-date")
public String googDate;
/**
* {@code "x-goog-metadata-directive"} header that specifies metadata handling during a copy
* operation.
*/
@Key("x-goog-metadata-directive")
public String googMetadataDirective;
/** {@code "X-HTTP-Method-Override"} header. */
@Key("X-HTTP-Method-Override")
public String methodOverride;
/**
* 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) {
userAgent = 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) {
authorization = getGoogleLoginValue(authToken);
}
/**
* Returns Google Login {@code "Authorization"} header value based on the given authentication
* token.
*/
public static String getGoogleLoginValue(String authToken) {
return "GoogleLogin auth=" + authToken;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation to specify that a field is a data key, optionally providing the data key name
* to use.
* <p>
* If the data key name is not specifies, the default data key name is the field's name. For
* example:
*
* <pre><code>public class A {
*
* // uses data key name of "dataKeyNameMatchesFieldName"
* @Key
* public String dataKeyNameMatchesFieldName;
*
* // uses data key name of "some_other_name"
* @Key("some_other_name")
* private String dataKeyNameIsOverriden;
*
* // not a data key
* private String notADataKey;
* }</code></pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Key {
/**
* Override the data key name of the field or {@code "##default"} to use the field's name.
*/
String value() default "##default";
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Memory-efficient map of keys to values with list-style random-access semantics.
* <p>
* Conceptually, the keys and values are stored in a simpler array in order to minimize memory use
* and provide for fast access to a key/value at a certain index (for example {@link #getKey(int)}).
* However, traditional mapping operations like {@link #get(Object)} and
* {@link #put(Object, Object)} are slower because they need to look up all key/value pairs in the
* worst case.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class ArrayMap<K, V> extends AbstractMap<K, V> implements Cloneable {
int size;
private Object[] data;
private EntrySet entrySet;
/**
* Returns a new instance of an array map with initial capacity of zero. Equivalent to calling the
* default constructor, except without the need to specify the type parameters. For example:
* {@code ArrayMap<String, String> map = ArrayMap.create();}.
*/
public static <K, V> ArrayMap<K, V> create() {
return new ArrayMap<K, V>();
}
/**
* Returns a new instance of an array map of the given initial capacity. For example: {@code
* ArrayMap<String, String> map = ArrayMap.create(8);}.
*/
public static <K, V> ArrayMap<K, V> create(int initialCapacity) {
ArrayMap<K, V> result = create();
result.ensureCapacity(initialCapacity);
return result;
}
/**
* Returns a new instance of an array map of the given key value pairs in alternating order. For
* example: {@code ArrayMap<String, String> map = ArrayMap.of("key1", "value1", "key2", "value2",
* ...);}.
* <p>
* WARNING: there is no compile-time checking of the {@code keyValuePairs} parameter to ensure
* that the keys or values have the correct type, so if the wrong type is passed in, any problems
* will occur at runtime. Also, there is no checking that the keys are unique, which the caller
* must ensure is true.
*/
public static <K, V> ArrayMap<K, V> of(Object... keyValuePairs) {
ArrayMap<K, V> result = create(1);
int length = keyValuePairs.length;
if (1 == length % 2) {
throw new IllegalArgumentException(
"missing value for last key: " + keyValuePairs[length - 1]);
}
result.size = keyValuePairs.length / 2;
Object[] data = result.data = new Object[length];
System.arraycopy(keyValuePairs, 0, data, 0, length);
return result;
}
/** Returns the number of key-value pairs set. */
@Override
public final int size() {
return this.size;
}
/** Returns the key at the given index or {@code null} if out of bounds. */
public final K getKey(int index) {
if (index < 0 || index >= this.size) {
return null;
}
@SuppressWarnings("unchecked")
K result = (K) this.data[index << 1];
return result;
}
/** Returns the value at the given index or {@code null} if out of bounds. */
public final V getValue(int index) {
if (index < 0 || index >= this.size) {
return null;
}
return valueAtDataIndex(1 + (index << 1));
}
/**
* Sets the key/value mapping at the given index, overriding any existing key/value mapping.
* <p>
* There is no checking done to ensure that the key does not already exist. Therefore, this method
* is dangerous to call unless the caller can be certain the key does not already exist in the
* map.
*
* @return previous value or {@code null} for none
* @throws IndexOutOfBoundsException if index is negative
*/
public final V set(int index, K key, V value) {
if (index < 0) {
throw new IndexOutOfBoundsException();
}
int minSize = index + 1;
ensureCapacity(minSize);
int dataIndex = index << 1;
V result = valueAtDataIndex(dataIndex + 1);
setData(dataIndex, key, value);
if (minSize > this.size) {
this.size = minSize;
}
return result;
}
/**
* Sets the value at the given index, overriding any existing value mapping.
*
* @return previous value or {@code null} for none
* @throws IndexOutOfBoundsException if index is negative or {@code >=} size
*/
public final V set(int index, V value) {
int size = this.size;
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int valueDataIndex = 1 + (index << 1);
V result = valueAtDataIndex(valueDataIndex);
this.data[valueDataIndex] = value;
return result;
}
/**
* Adds the key/value mapping at the end of the list. Behaves identically to {@code set(size(),
* key, value)}.
*
* @throws IndexOutOfBoundsException if index is negative
*/
public final void add(K key, V value) {
set(this.size, key, value);
}
/**
* Removes the key/value mapping at the given index, or ignored if the index is out of bounds.
*
* @return previous value or {@code null} for none
*/
public final V remove(int index) {
return removeFromDataIndexOfKey(index << 1);
}
/** Returns whether there is a mapping for the given key. */
@Override
public final boolean containsKey(Object key) {
return -2 != getDataIndexOfKey(key);
}
/** Returns the index of the given key or {@code -1} if there is no such key. */
public final int getIndexOfKey(K key) {
return getDataIndexOfKey(key) >> 1;
}
/**
* Returns the value set for the given key or {@code null} if there is no such mapping or if the
* mapping value is {@code null}.
*/
@Override
public final V get(Object key) {
return valueAtDataIndex(getDataIndexOfKey(key) + 1);
}
/**
* Sets the value for the given key, overriding any existing value.
*
* @return previous value or {@code null} for none
*/
@Override
public final V put(K key, V value) {
int index = getIndexOfKey(key);
if (index == -1) {
index = this.size;
}
return set(index, key, value);
}
/**
* Removes the key-value pair of the given key, or ignore if the key cannot be found.
*
* @return previous value or {@code null} for none
*/
@Override
public final V remove(Object key) {
return removeFromDataIndexOfKey(getDataIndexOfKey(key));
}
/** Trims the internal array storage to minimize memory usage. */
public final void trim() {
setDataCapacity(this.size << 1);
}
/**
* Ensures that the capacity of the internal arrays is at least a given capacity.
*/
public final void ensureCapacity(int minCapacity) {
Object[] data = this.data;
int minDataCapacity = minCapacity << 1;
int oldDataCapacity = data == null ? 0 : data.length;
if (minDataCapacity > oldDataCapacity) {
int newDataCapacity = oldDataCapacity / 2 * 3 + 1;
if (newDataCapacity % 2 == 1) {
newDataCapacity++;
}
if (newDataCapacity < minDataCapacity) {
newDataCapacity = minDataCapacity;
}
setDataCapacity(newDataCapacity);
}
}
private void setDataCapacity(int newDataCapacity) {
if (newDataCapacity == 0) {
this.data = null;
return;
}
int size = this.size;
Object[] oldData = this.data;
if (size == 0 || newDataCapacity != oldData.length) {
Object[] newData = this.data = new Object[newDataCapacity];
if (size != 0) {
System.arraycopy(oldData, 0, newData, 0, size << 1);
}
}
}
private void setData(int dataIndexOfKey, K key, V value) {
Object[] data = this.data;
data[dataIndexOfKey] = key;
data[dataIndexOfKey + 1] = value;
}
private V valueAtDataIndex(int dataIndex) {
if (dataIndex < 0) {
return null;
}
@SuppressWarnings("unchecked")
V result = (V) this.data[dataIndex];
return result;
}
/**
* Returns the data index of the given key or {@code -2} if there is no such key.
*/
private int getDataIndexOfKey(Object key) {
int dataSize = this.size << 1;
Object[] data = this.data;
for (int i = 0; i < dataSize; i += 2) {
Object k = data[i];
if (key == null ? k == null : key.equals(k)) {
return i;
}
}
return -2;
}
/**
* Removes the key/value mapping at the given data index of key, or ignored if the index is out of
* bounds.
*/
private V removeFromDataIndexOfKey(int dataIndexOfKey) {
int dataSize = this.size << 1;
if (dataIndexOfKey < 0 || dataIndexOfKey >= dataSize) {
return null;
}
V result = valueAtDataIndex(dataIndexOfKey + 1);
Object[] data = this.data;
int moved = dataSize - dataIndexOfKey - 2;
if (moved != 0) {
System.arraycopy(data, dataIndexOfKey + 2, data, dataIndexOfKey, moved);
}
this.size--;
setData(dataSize - 2, null, null);
return result;
}
@Override
public void clear() {
this.size = 0;
this.data = null;
}
@Override
public final boolean containsValue(Object value) {
int dataSize = this.size << 1;
Object[] data = this.data;
for (int i = 1; i < dataSize; i += 2) {
Object v = data[i];
if (value == null ? v == null : value.equals(v)) {
return true;
}
}
return false;
}
@Override
public final Set<Map.Entry<K, V>> entrySet() {
EntrySet entrySet = this.entrySet;
if (entrySet == null) {
entrySet = this.entrySet = new EntrySet();
}
return entrySet;
}
@Override
public ArrayMap<K, V> clone() {
try {
@SuppressWarnings("unchecked")
ArrayMap<K, V> result = (ArrayMap<K, V>) super.clone();
result.entrySet = null;
Object[] data = this.data;
if (data != null) {
int length = data.length;
Object[] resultData = result.data = new Object[length];
System.arraycopy(data, 0, resultData, 0, length);
}
return result;
} catch (CloneNotSupportedException e) {
// won't happen
return null;
}
}
final class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public int size() {
return ArrayMap.this.size;
}
}
final class EntryIterator implements Iterator<Map.Entry<K, V>> {
private boolean removed;
private int nextIndex;
public boolean hasNext() {
return this.nextIndex < ArrayMap.this.size;
}
public Map.Entry<K, V> next() {
int index = this.nextIndex;
if (index == ArrayMap.this.size) {
throw new NoSuchElementException();
}
this.nextIndex++;
return new Entry(index);
}
public void remove() {
int index = this.nextIndex - 1;
if (this.removed || index < 0) {
throw new IllegalArgumentException();
}
ArrayMap.this.remove(index);
this.removed = true;
}
}
final class Entry implements Map.Entry<K, V> {
private int index;
Entry(int index) {
this.index = index;
}
public K getKey() {
return ArrayMap.this.getKey(this.index);
}
public V getValue() {
return ArrayMap.this.getValue(this.index);
}
public V setValue(V value) {
return ArrayMap.this.set(this.index, value);
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.WeakHashMap;
/**
* Parses field information to determine data key name/value pair associated with the field.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class FieldInfo {
private static final ThreadLocal<WeakHashMap<Field, FieldInfo>> CACHE =
new ThreadLocal<WeakHashMap<Field, FieldInfo>>() {
@Override
protected WeakHashMap<Field, FieldInfo> initialValue() {
return new WeakHashMap<Field, FieldInfo>();
}
};
/**
* Returns the field information for the given field.
*
* @param field field or {@code null} for {@code null} result
* @return field information or {@code null} if the field has no {@link Key} annotation or for
* {@code null} input
*/
public static FieldInfo of(Field field) {
if (field == null) {
return null;
}
WeakHashMap<Field, FieldInfo> cache = CACHE.get();
FieldInfo fieldInfo = cache.get(field);
if (fieldInfo == null && !Modifier.isStatic(field.getModifiers())) {
// ignore if field it has no @Key annotation
Key key = field.getAnnotation(Key.class);
if (key == null) {
return null;
}
String fieldName = key.value();
if ("##default".equals(fieldName)) {
fieldName = field.getName();
}
fieldInfo = new FieldInfo(field, fieldName);
cache.put(field, fieldInfo);
field.setAccessible(true);
}
return fieldInfo;
}
/** Whether the field is final. */
public final boolean isFinal;
/**
* Whether the field class is "primitive" as defined by {@link FieldInfo#isPrimitive(Class)}.
*/
public final boolean isPrimitive;
/** Field class. */
public final Class<?> type;
/** Field. */
public final Field field;
/** Data key name associated with the field. This string is interned. */
public final String name;
FieldInfo(Field field, String name) {
this.field = field;
this.name = name.intern();
isFinal = Modifier.isFinal(field.getModifiers());
Class<?> type = this.type = field.getType();
isPrimitive = FieldInfo.isPrimitive(type);
}
/**
* Returns the value of the field in the given object instance using reflection.
*/
public Object getValue(Object obj) {
return getFieldValue(field, obj);
}
/**
* Sets to the given value of the field in the given object instance using reflection.
* <p>
* If the field is final, it checks that value being set is identical to the existing value.
*/
public void setValue(Object obj, Object value) {
setFieldValue(field, obj, value);
}
/** Returns the class information of the field's declaring class. */
public ClassInfo getClassInfo() {
return ClassInfo.of(field.getDeclaringClass());
}
/**
* Returns whether the given field class is one of the supported primitive types like number and
* date/time.
*/
public static boolean isPrimitive(Class<?> fieldClass) {
return fieldClass.isPrimitive() || fieldClass == Character.class || fieldClass == String.class
|| fieldClass == Integer.class || fieldClass == Long.class || fieldClass == Short.class
|| fieldClass == Byte.class || fieldClass == Float.class || fieldClass == Double.class
|| fieldClass == BigInteger.class || fieldClass == BigDecimal.class
|| fieldClass == DateTime.class || fieldClass == Boolean.class;
}
// TODO: support java.net.URI as primitive type?
/**
* Returns whether to given value is {@code null} or its class is primitive as defined by
* {@link #isPrimitive(Class)}.
*/
public static boolean isPrimitive(Object fieldValue) {
return fieldValue == null || isPrimitive(fieldValue.getClass());
}
/**
* Returns the value of the given field in the given object instance using reflection.
*/
public static Object getFieldValue(Field field, Object obj) {
try {
return field.get(obj);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Sets to the given value of the given field in the given object instance using reflection.
* <p>
* If the field is final, it checks that value being set is identical to the existing value.
*/
public static void setFieldValue(Field field, Object obj, Object value) {
if (Modifier.isFinal(field.getModifiers())) {
Object finalValue = getFieldValue(field, obj);
if (value == null ? finalValue != null : !value.equals(finalValue)) {
throw new IllegalArgumentException(
"expected final value <" + finalValue + "> but was <" + value + "> on "
+ field.getName() + " field in " + obj.getClass().getName());
}
} else {
try {
field.set(obj, value);
} catch (SecurityException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* Parses the given string value based on the given primitive class.
* <p>
* Types are parsed as follows:
* <ul>
* <li>{@code null} or {@link String}: no parsing</li>
* <li>{@code char} or {@link Character}: {@link String#charAt(int) String.charAt}(0) (requires
* length to be exactly 1)</li>
* <li>{@code boolean} or {@link Boolean}: {@link Boolean#valueOf(String)}</li>
* <li>{@code byte} or {@link Byte}: {@link Byte#valueOf(String)}</li>
* <li>{@code short} or {@link Short}: {@link Short#valueOf(String)}</li>
* <li>{@code int} or {@link Integer}: {@link Integer#valueOf(String)}</li>
* <li>{@code long} or {@link Long}: {@link Long#valueOf(String)}</li>
* <li>{@code float} or {@link Float}: {@link Float#valueOf(String)}</li>
* <li>{@code double} or {@link Double}: {@link Double#valueOf(String)}</li>
* <li>{@link BigInteger}: {@link BigInteger#BigInteger(String) BigInteger(String)}</li>
* <li>{@link BigDecimal}: {@link BigDecimal#BigDecimal(String) BigDecimal(String)}</li>
* <li>{@link DateTime}: {@link DateTime#parseRfc3339(String)}</li>
* </ul>
* Note that this may not be the right behavior for some use cases.
*
* @param primitiveClass primitive class (see {@link #isPrimitive(Class)} or {@code null} to parse
* as a string
* @param stringValue string value to parse or {@code null} for {@code null} result
* @return parsed object or {@code null} for {@code null} input
* @throws IllegalArgumentException if the given class is not a primitive class as defined by
* {@link #isPrimitive(Class)}
*/
public static Object parsePrimitiveValue(Class<?> primitiveClass, String stringValue) {
if (stringValue == null || primitiveClass == null || primitiveClass == String.class) {
return stringValue;
}
if (primitiveClass == Character.class || primitiveClass == char.class) {
if (stringValue.length() != 1) {
throw new IllegalArgumentException(
"expected type Character/char but got " + primitiveClass);
}
return stringValue.charAt(0);
}
if (primitiveClass == Boolean.class || primitiveClass == boolean.class) {
return Boolean.valueOf(stringValue);
}
if (primitiveClass == Byte.class || primitiveClass == byte.class) {
return Byte.valueOf(stringValue);
}
if (primitiveClass == Short.class || primitiveClass == short.class) {
return Short.valueOf(stringValue);
}
if (primitiveClass == Integer.class || primitiveClass == int.class) {
return Integer.valueOf(stringValue);
}
if (primitiveClass == Long.class || primitiveClass == long.class) {
return Long.valueOf(stringValue);
}
if (primitiveClass == Float.class || primitiveClass == float.class) {
return Float.valueOf(stringValue);
}
if (primitiveClass == Double.class || primitiveClass == double.class) {
return Double.valueOf(stringValue);
}
if (primitiveClass == DateTime.class) {
return DateTime.parseRfc3339(stringValue);
}
if (primitiveClass == BigInteger.class) {
return new BigInteger(stringValue);
}
if (primitiveClass == BigDecimal.class) {
return new BigDecimal(stringValue);
}
throw new IllegalArgumentException("expected primitive class, but got: " + primitiveClass);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Map that uses {@link ClassInfo} to parse the key/value pairs into a map.
* <p>
* Iteration order of the keys is based on the sorted (ascending) key names.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class ReflectionMap extends AbstractMap<String, Object> {
final int size;
private EntrySet entrySet;
final ClassInfo classInfo;
final Object object;
public ReflectionMap(Object object) {
this.object = object;
ClassInfo classInfo = this.classInfo = ClassInfo.of(object.getClass());
size = classInfo.getKeyCount();
}
// TODO: implement more methods for faster implementation!
@Override
public Set<Map.Entry<String, Object>> entrySet() {
EntrySet entrySet = this.entrySet;
if (entrySet == null) {
entrySet = this.entrySet = new EntrySet();
}
return entrySet;
}
final class EntrySet extends AbstractSet<Map.Entry<String, Object>> {
@Override
public Iterator<Map.Entry<String, Object>> iterator() {
return new EntryIterator(classInfo, object);
}
@Override
public int size() {
return size;
}
}
static final class EntryIterator implements Iterator<Map.Entry<String, Object>> {
private final String[] fieldNames;
private final int numFields;
private int fieldIndex = 0;
private final Object object;
final ClassInfo classInfo;
EntryIterator(ClassInfo classInfo, Object object) {
this.classInfo = classInfo;
this.object = object;
// sort the keys
Collection<String> keyNames = this.classInfo.getKeyNames();
int size = numFields = keyNames.size();
if (size == 0) {
fieldNames = null;
} else {
String[] fieldNames = this.fieldNames = new String[size];
int i = 0;
for (String keyName : keyNames) {
fieldNames[i++] = keyName;
}
Arrays.sort(fieldNames);
}
}
public boolean hasNext() {
return fieldIndex < numFields;
}
public Map.Entry<String, Object> next() {
int fieldIndex = this.fieldIndex;
if (fieldIndex >= numFields) {
throw new NoSuchElementException();
}
String fieldName = fieldNames[fieldIndex];
this.fieldIndex++;
return new Entry(object, fieldName);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
static final class Entry implements Map.Entry<String, Object> {
private boolean isFieldValueComputed;
private final String fieldName;
private Object fieldValue;
private final Object object;
private final ClassInfo classInfo;
public Entry(Object object, String fieldName) {
classInfo = ClassInfo.of(object.getClass());
this.object = object;
this.fieldName = fieldName;
}
public String getKey() {
return fieldName;
}
public Object getValue() {
if (isFieldValueComputed) {
return fieldValue;
}
isFieldValueComputed = true;
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
return fieldValue = fieldInfo.getValue(object);
}
public Object setValue(Object value) {
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
Object oldValue = getValue();
fieldInfo.setValue(object, value);
fieldValue = value;
return oldValue;
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* Immutable representation of a date with an optional time and an optional time zone based on RFC
* 3339.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class DateTime {
private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
/**
* Date/time value expressed as the number of ms since the Unix epoch.
*
* If the time zone is specified, this value is normalized to UTC, so to format this date/time
* value, the time zone shift has to be applied.
*/
public final long value;
/** Specifies whether this is a date-only value. */
public final boolean dateOnly;
/**
* Time zone shift from UTC in minutes. If {@code null}, no time zone is set, and the time is
* always interpreted as local time.
*/
public final Integer tzShift;
public DateTime(Date date, TimeZone zone) {
long value = date.getTime();
dateOnly = false;
this.value = value;
tzShift = zone.getOffset(value) / 60000;
}
public DateTime(long value) {
this(false, value, null);
}
public DateTime(Date value) {
this(value.getTime());
}
public DateTime(long value, Integer tzShift) {
this(false, value, tzShift);
}
public DateTime(boolean dateOnly, long value, Integer tzShift) {
this.dateOnly = dateOnly;
this.value = value;
this.tzShift = tzShift;
}
/** Formats the value as an RFC 3339 date/time string. */
public String toStringRfc3339() {
StringBuilder sb = new StringBuilder();
Calendar dateTime = new GregorianCalendar(GMT);
long localTime = value;
Integer tzShift = this.tzShift;
if (tzShift != null) {
localTime += tzShift.longValue() * 60000;
}
dateTime.setTimeInMillis(localTime);
appendInt(sb, dateTime.get(Calendar.YEAR), 4);
sb.append('-');
appendInt(sb, dateTime.get(Calendar.MONTH) + 1, 2);
sb.append('-');
appendInt(sb, dateTime.get(Calendar.DAY_OF_MONTH), 2);
if (!dateOnly) {
sb.append('T');
appendInt(sb, dateTime.get(Calendar.HOUR_OF_DAY), 2);
sb.append(':');
appendInt(sb, dateTime.get(Calendar.MINUTE), 2);
sb.append(':');
appendInt(sb, dateTime.get(Calendar.SECOND), 2);
if (dateTime.isSet(Calendar.MILLISECOND)) {
sb.append('.');
appendInt(sb, dateTime.get(Calendar.MILLISECOND), 3);
}
}
if (tzShift != null) {
if (tzShift.intValue() == 0) {
sb.append('Z');
} else {
int absTzShift = tzShift.intValue();
if (tzShift > 0) {
sb.append('+');
} else {
sb.append('-');
absTzShift = -absTzShift;
}
int tzHours = absTzShift / 60;
int tzMinutes = absTzShift % 60;
appendInt(sb, tzHours, 2);
sb.append(':');
appendInt(sb, tzMinutes, 2);
}
}
return sb.toString();
}
@Override
public String toString() {
return toStringRfc3339();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof DateTime)) {
return false;
}
DateTime other = (DateTime) o;
return dateOnly == other.dateOnly && value == other.value;
}
/**
* Parses an RFC 3339 date/time value.
*/
public static DateTime parseRfc3339(String str) throws NumberFormatException {
try {
Calendar dateTime = new GregorianCalendar(GMT);
int year = Integer.parseInt(str.substring(0, 4));
int month = Integer.parseInt(str.substring(5, 7)) - 1;
int day = Integer.parseInt(str.substring(8, 10));
int tzIndex;
int length = str.length();
boolean dateOnly = length <= 10 || Character.toUpperCase(str.charAt(10)) != 'T';
if (dateOnly) {
dateTime.set(year, month, day);
tzIndex = 10;
} else {
int hourOfDay = Integer.parseInt(str.substring(11, 13));
int minute = Integer.parseInt(str.substring(14, 16));
int second = Integer.parseInt(str.substring(17, 19));
dateTime.set(year, month, day, hourOfDay, minute, second);
if (str.charAt(19) == '.') {
int milliseconds = Integer.parseInt(str.substring(20, 23));
dateTime.set(Calendar.MILLISECOND, milliseconds);
tzIndex = 23;
} else {
tzIndex = 19;
}
}
Integer tzShiftInteger = null;
long value = dateTime.getTimeInMillis();
if (length > tzIndex) {
int tzShift;
if (Character.toUpperCase(str.charAt(tzIndex)) == 'Z') {
tzShift = 0;
} else {
tzShift = Integer.parseInt(str.substring(tzIndex + 1, tzIndex + 3)) * 60
+ Integer.parseInt(str.substring(tzIndex + 4, tzIndex + 6));
if (str.charAt(tzIndex) == '-') {
tzShift = -tzShift;
}
value -= tzShift * 60000;
}
tzShiftInteger = tzShift;
}
return new DateTime(dateOnly, value, tzShiftInteger);
} catch (StringIndexOutOfBoundsException e) {
throw new NumberFormatException("Invalid date/time format.");
}
}
/** Appends a zero-padded number to a string builder. */
private static void appendInt(StringBuilder sb, int num, int numDigits) {
if (num < 0) {
sb.append('-');
num = -num;
}
int x = num;
while (x > 0) {
x /= 10;
numDigits--;
}
for (int i = 0; i < numDigits; i++) {
sb.append('0');
}
if (num != 0) {
sb.append(num);
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.io.UnsupportedEncodingException;
/**
* Utilities for strings.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class Strings {
/**
* Line separator to use for this OS, i.e. {@code "\n"} or {@code "\r\n"}.
*/
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/**
* Returns a new byte array that is the result of encoding the given string into a sequence of
* bytes using the {@code "UTF-8"} charset.
*
* @param string given string
* @return resultant byte array
* @since 1.2
*/
public static byte[] toBytesUtf8(String string) {
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException exception) {
// UTF-8 encoding guaranteed to be supported by JVM
throw new RuntimeException(exception);
}
}
/**
* Returns a new {@code String} by decoding the specified array of bytes using the {@code "UTF-8"}
* charset.
*
* <p>
* The length of the new {@code String} is a function of the charset, and hence may not be equal
* to the length of the byte array.
* </p>
*
* @param bytes bytes to be decoded into characters
* @return resultant string
* @since 1.2
*/
public static String fromBytesUtf8(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException exception) {
// UTF-8 encoding guaranteed to be supported by JVM
throw new RuntimeException(exception);
}
}
private Strings() {
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.