code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* Copyright (c) 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/escape/CharEscapers.java
|
Java
|
asf20
| 6,675
|
/*
* 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);
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/escape/PercentEscaper.java
|
Java
|
asf20
| 9,604
|
/*
* 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];
}
};
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/escape/Platform.java
|
Java
|
asf20
| 1,412
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/escape/UnicodeEscaper.java
|
Java
|
asf20
| 11,414
|
<body>
HTTP Transport library for Google API's based on the {@code java.net} package.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/javanet/package.html
|
HTML
|
asf20
| 382
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/javanet/NetHttpResponse.java
|
Java
|
asf20
| 3,112
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/javanet/NetHttpTransport.java
|
Java
|
asf20
| 2,408
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/javanet/NetHttpRequest.java
|
Java
|
asf20
| 2,754
|
<body>
Android XML utilities.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.xml}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/android/xml/package.html
|
HTML
|
asf20
| 324
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/android/xml/AndroidXmlParserFactory.java
|
Java
|
asf20
| 1,103
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/LowLevelHttpTransport.java
|
Java
|
asf20
| 3,706
|
<body>
Subset of HTTP 1.1 needed from the specification in
<a href="http://tools.ietf.org/html/rfc2616">RFC 2616: Hypertext Transfer
Protocol -- HTTP/1.1</a>
. Additionally, it includes
<a href="http://tools.ietf.org/html/rfc5789">PATCH Method for HTTP</a>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.escape}</li>
<li>{@link com.google.api.client.repackaged.com.google.common.base}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/package.html
|
HTML
|
asf20
| 677
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/LowLevelHttpRequest.java
|
Java
|
asf20
| 1,598
|
/*
* 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();
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/InputStreamContent.java
|
Java
|
asf20
| 5,268
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpResponseException.java
|
Java
|
asf20
| 1,595
|
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\"";
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/MultipartRelatedContent.java
|
Java
|
asf20
| 3,055
|
/*
* 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
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpHeaders.java
|
Java
|
asf20
| 5,555
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpParser.java
|
Java
|
asf20
| 1,346
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/UrlEncodedContent.java
|
Java
|
asf20
| 3,208
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/GenericUrl.java
|
Java
|
asf20
| 10,434
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/GZipContent.java
|
Java
|
asf20
| 1,500
|
/*
* 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;
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/UrlEncodedParser.java
|
Java
|
asf20
| 5,899
|
/*
* 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/"));
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/LogContent.java
|
Java
|
asf20
| 2,462
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpExecuteIntercepter.java
|
Java
|
asf20
| 1,318
|
/*
* 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();
}
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpTransport.java
|
Java
|
asf20
| 9,250
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpContent.java
|
Java
|
asf20
| 1,300
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpResponse.java
|
Java
|
asf20
| 10,909
|
/*
* 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);
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/LowLevelHttpResponse.java
|
Java
|
asf20
| 2,290
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/http/HttpRequest.java
|
Java
|
asf20
| 8,518
|
<body>
Utilities for authentication and authorization.
<p>This package depends on theses packages:</p>
<ul>
<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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/package.html
|
HTML
|
asf20
| 350
|
/*
*
* 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()));
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/RsaSha.java
|
Java
|
asf20
| 3,706
|
/*
* 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;
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/package-info.java
|
Java
|
asf20
| 2,944
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AuthorizationRequestUrl.java
|
Java
|
asf20
| 4,261
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AuthorizationResponse.java
|
Java
|
asf20
| 6,656
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AccessTokenResponse.java
|
Java
|
asf20
| 2,517
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AccessProtectedResource.java
|
Java
|
asf20
| 4,912
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AccessTokenRequest.java
|
Java
|
asf20
| 10,941
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth2/AccessTokenErrorResponse.java
|
Java
|
asf20
| 3,460
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/HmacSha.java
|
Java
|
asf20
| 1,518
|
<body>
OAuth 1.0 authorization as specified in
<a href="http://tools.ietf.org/html/rfc5849">RFC 5849: The OAuth 1.0
Protocol</a>
(see detailed package specification).
<p>There are a few features not supported by this implementation:</p>
<ul>
<li>{@code PLAINTEXT} signature algorithm</li>
<li>{@code "application/x-www-form-urlencoded"} HTTP request body</li>
<li>{@code "oauth_*"} parameters specified in the HTTP request URL
(instead assumes they are specified in the {@code Authorization} header)</li>
</ul>
<p>Before using this library, you may need to set up your application as
follows:</p>
<ol>
<li>For web applications, you may need to first register your application
with the authorization server. It may provide two pieces of information you
need:
<ul>
<li>OAuth Consumer Key: use this as the {@code consumerKey} on every
OAuth request, for example in {@link
com.google.api.client.auth.oauth.AbstractOAuthGetToken#consumerKey}.</li>
<li>OAuth Consumer Secret: use this as the {@link
com.google.api.client.auth.oauth.OAuthHmacSigner#clientSharedSecret} when
using the {@code "HMAC-SHA1"} signature method.</li>
</ul>
</li>
<li>For an installed application, an unregistered web application, or a
web application running on localhost, you must use the {@code "HMAC-SHA1"}
signature method. The documentation for the authorization server will need to
provide you with the {@code consumerKey} and {@code clientSharedSecret} to
use.</li>
<li>For the {@code "HMAC-SHA1"} signature method, use {@link
com.google.api.client.auth.oauth.OAuthHmacSigner}.</li>
<li>For the {@code "RSA-SHA1"} signature method, use {@link
com.google.api.client.auth.oauth.OAuthRsaSigner}.</li>
</ol>
<p>After the set up has been completed, the typical application flow is:</p>
<ol>
<li>Request a temporary credentials token from the Authorization server
using {@link com.google.api.client.auth.oauth.OAuthGetTemporaryToken}. A
callback URL should be specified for web applications, but does not need to be
specified for installed applications.</li>
<li>Direct the end user to an authorization web page to allow the end
user to authorize the temporary token using using {@link
com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl}.</li>
<li>After the user has granted the authorization:
<ul>
<li>For web applications, the user's browser will be redirected to the
callback URL which may be parsed using {@link
com.google.api.client.auth.oauth.OAuthCallbackUrl}.</li>
<li>For installed applications, see the authorization server's
documentation for figuring out the verification code.</li>
</ul>
</li>
<li>Request to exchange the temporary token for a long-lived access token
from the Authorization server using {@link
com.google.api.client.auth.oauth.OAuthGetAccessToken}. This access token must
be stored.</li>
<li>Use the stored access token to authorize HTTP requests to protected
resources by setting the {@link
com.google.api.client.auth.oauth.OAuthParameters#token} and invoking {@link
com.google.api.client.auth.oauth.OAuthParameters#signRequestsUsingAuthorizationHeader}.</li>
</ol>
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.auth}</li>
<li>{@link com.google.api.client.escape}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/package.html
|
HTML
|
asf20
| 3,639
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthHmacSigner.java
|
Java
|
asf20
| 1,699
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthGetAccessToken.java
|
Java
|
asf20
| 2,180
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/AbstractOAuthGetToken.java
|
Java
|
asf20
| 2,858
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthAuthorizeTemporaryTokenUrl.java
|
Java
|
asf20
| 1,897
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthGetTemporaryToken.java
|
Java
|
asf20
| 1,794
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthParameters.java
|
Java
|
asf20
| 8,722
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthCallbackUrl.java
|
Java
|
asf20
| 1,375
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthRsaSigner.java
|
Java
|
asf20
| 1,273
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthCredentialsResponse.java
|
Java
|
asf20
| 1,412
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthSigner.java
|
Java
|
asf20
| 1,104
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/auth/oauth/OAuthAuthorizationHeaderIntercepter.java
|
Java
|
asf20
| 1,402
|
<body>
Google API's.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.escape}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/package.html
|
HTML
|
asf20
| 411
|
/*
* 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());
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/MethodOverrideIntercepter.java
|
Java
|
asf20
| 2,481
|
<body>
Google's Atom XML implementation (see detailed package specification).
<h2>Package Specification</h2>
<p>User-defined Partial XML data models allow you to defined Plain Old Java
Objects (POJO's) to define how the library should parse/serialize XML. Each
field that should be included must have an @{@link
com.google.api.client.util.Key} annotation. The field can be of any visibility
(private, package private, protected, or public) and must not be static.</p>
<p>The optional value parameter of this @{@link
com.google.api.client.util.Key} annotation specifies the XPath name to use to
represent the field. For example, an XML attribute <code>a</code> has an XPath
name of <code>@a</code>, an XML element <code><a></code> has an XPath name
of <code>a</code>, and an XML text content has an XPath name of <code>text()</code>.
These are named based on their usage with the <a
href="http://code.google.com/apis/gdata/docs/2.0/reference.html#PartialResponse">partial
response/update syntax</a> for Google API's. If the @{@link
com.google.api.client.util.Key} annotation is missing, the default is to use the
Atom XML namespace and the Java field's name as the local XML name. By default,
the field name is used as the JSON key. Any unrecognized XML is normally simply
ignored and not stored. If the ability to store unknown keys is important, use
{@link com.google.api.client.xml.GenericXml}.</p>
<p>Let's take a look at a typical partial Atom XML album feed from the
Picasa Web Albums Data API:</p>
<pre><code>
<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'
xmlns:gphoto='http://schemas.google.com/photos/2007'>
<link rel='http://schemas.google.com/g/2005#post'
type='application/atom+xml'
href='http://picasaweb.google.com/data/feed/api/user/liz' />
<author>
<name>Liz</name>
</author>
<openSearch:totalResults>1</openSearch:totalResults>
<entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/photos/2007#album' />
<title>lolcats</title>
<summary>Hilarious Felines</summary>
<gphoto:access>public</gphoto:access>
</entry>
</feed>
</code></pre>
<p>Here's one possible way to design the Java data classes for this (each
class in its own Java file):</p>
<pre><code>
import com.google.api.client.util.*;
import java.util.List;
public class Link {
@Key("@href")
public String href;
@Key("@rel")
public String rel;
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
public class Category {
@Key("@scheme")
public String scheme;
@Key("@term")
public String term;
public static Category newKind(String kind) {
Category category = new Category();
category.scheme = "http://schemas.google.com/g/2005#kind";
category.term = "http://schemas.google.com/photos/2007#" + kind;
return category;
}
}
public class AlbumEntry {
@Key
public String summary;
@Key
public String title;
@Key("gphoto:access")
public String access;
public Category category = newKind("album");
private String getEditLink() {
return Link.find(links, "edit");
}
}
public class Author {
@Key
public String name;
}
public class AlbumFeed {
@Key
public Author author;
@Key("openSearch:totalResults")
public int totalResults;
@Key("entry")
public List<AlbumEntry> photos;
@Key("link")
public List<Link> links;
private String getPostLink() {
return Link.find(links, "http://schemas.google.com/g/2005#post");
}
}
</code></pre>
<p>You can also use the @{@link com.google.api.client.util.Key} annotation
to defined query parameters for a URL. For example:</p>
<pre><code>
public class PicasaUrl extends GoogleUrl {
@Key("max-results")
public Integer maxResults;
@Key
public String kinds;
public PicasaUrl(String url) {
super(url);
}
public static PicasaUrl fromRelativePath(String relativePath) {
PicasaUrl result = new PicasaUrl(PicasaWebAlbums.ROOT_URL);
result.path += relativePath;
return result;
}
}
</code></pre>
<p>To work with a Google API, you first need to set up the {@link
com.google.api.client.googleapis.GoogleTransport}. For example:</p>
<pre><code>
private static GoogleTransport setUpGoogleTransport() throws IOException {
GoogleTransport transport = new GoogleTransport();
transport.applicationName = "google-picasaatomsample-1.0";
transport.setVersionHeader(PicasaWebAlbums.VERSION);
AtomParser parser = new AtomParser();
parser.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
transport.addParser(parser);
// insert authentication code...
return transport;
}
</code></pre>
<p>Now that we have a transport, we can execute a partial GET request to the
Picasa Web Albums API and parse the result:</p>
<pre><code>
public static AlbumFeed executeGet(GoogleTransport transport, PicasaUrl url)
throws IOException {
url.fields = GData.getFieldsFor(AlbumFeed.class);
url.kinds = "photo";
url.maxResults = 5;
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(AlbumFeed.class);
}
</code></pre>
<p>If the server responds with an error the {@link
com.google.api.client.http.HttpRequest#execute} method will throw an {@link
com.google.api.client.http.HttpResponseException}, which has an {@link
com.google.api.client.http.HttpResponse} field which can be parsed the same way
as a success response inside of a catch block. For example:</p>
<pre><code>
try {
...
} catch (HttpResponseException e) {
if (e.response.getParser() != null) {
Error error = e.response.parseAs(Error.class);
// process error response
} else {
String errorContentString = e.response.parseAsString();
// process error response as string
}
throw e;
}
</code></pre>
<p>To update an album, we use the transport to execute an efficient partial
update request using the PATCH method to the Picasa Web Albums API:</p>
<pre><code>
public AlbumEntry executePatchRelativeToOriginal(GoogleTransport transport,
AlbumEntry original) throws IOException {
HttpRequest request = transport.buildPatchRequest();
request.setUrl(getEditLink());
request.headers.ifMatch = etag;
PatchRelativeToOriginalContent content =
new PatchRelativeToOriginalContent();
content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
content.originalEntry = original;
content.patchedEntry = this;
request.content = content;
return request.execute().parseAs(AlbumEntry.class);
}
private static AlbumEntry updateTitle(GoogleTransport transport,
AlbumEntry album) throws IOException {
AlbumEntry patched = album.clone();
patched.title = "An alternate title";
return patched.executePatchRelativeToOriginal(transport, album);
}
</code></pre>
<p>To insert an album, we use the transport to execute a POST request to the
Picasa Web Albums API:</p>
<pre><code>
public AlbumEntry insertAlbum(GoogleTransport transport, AlbumEntry entry)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.setUrl(getPostLink());
AtomContent content = new AtomContent();
content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY;
content.entry = entry;
request.content = content;
return request.execute().parseAs(AlbumEntry.class);
}
</code></pre>
<p>To delete an album, we use the transport to execute a DELETE request to
the Picasa Web Albums API:</p>
<pre><code>
public void executeDelete(GoogleTransport transport) throws IOException {
HttpRequest request = transport.buildDeleteRequest();
request.setUrl(getEditLink());
request.headers.ifMatch = etag;
request.execute().ignore();
}
</code></pre>
<p>NOTE: As you might guess, the library uses reflection to populate the
user-defined data model. It's not quite as fast as writing the wire format
parsing code yourself can potentially be, but it's a lot easier.</p>
<p>NOTE: If you prefer to use your favorite XML parsing library instead
(there are many of them), that's supported as well. Just call {@link
com.google.api.client.http.HttpRequest#execute()} and parse the returned byte
stream.</p>
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.http}</li>
<li>{@link com.google.api.client.util}</li>
<li>{@link com.google.api.client.xml}</li>
<li>{@link com.google.api.client.xml.atom}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/package.html
|
HTML
|
asf20
| 9,350
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/AtomPatchRelativeToOriginalContent.java
|
Java
|
asf20
| 2,117
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/AtomPatchContent.java
|
Java
|
asf20
| 1,484
|
/*
* 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();
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/MultiKindFeedParser.java
|
Java
|
asf20
| 3,614
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/GData.java
|
Java
|
asf20
| 8,537
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/xml/atom/GDataHttp.java
|
Java
|
asf20
| 823
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/GoogleUrl.java
|
Java
|
asf20
| 1,371
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/GoogleTransport.java
|
Java
|
asf20
| 2,094
|
<body>
Utilities for Google's authentication methods as described in
<a href="http://code.google.com/apis/accounts/docs/GettingStarted.html">Getting
Started with Account Authorization</a>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/package.html
|
HTML
|
asf20
| 531
|
<body>
Google's legacy ClientLogin authentication method as described in
<a href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html">ClientLogin
for Installed Applications</a>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.googleapis}</li>
<li>{@link com.google.api.client.googleapis.auth}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/clientlogin/package.html
|
HTML
|
asf20
| 646
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/clientlogin/ClientLogin.java
|
Java
|
asf20
| 4,155
|
<body>
Google's additions to OAuth 1.0a authorization as specified in
<a href="http://code.google.com/apis/accounts/docs/OAuth_ref.html">Google's
OAuth API Reference </a>
(see detailed package specification).
<h2>Package Specification</h2>
<p>Before using this library, you need to set up your application as
follows:</p>
<ol>
<li>For a web application, you should first register your application at
the <a href="https://www.google.com/accounts/ManageDomains">Manage Your
Domains</a> page. See detailed instructions at the <a
href="http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html">registration
page</a>. Take note of the following OAuth information you will need:
<ul>
<li>OAuth Consumer Key (same as your appspot domain): use this as the
{@code consumerKey} on every OAuth request, for example in {@link
com.google.api.client.auth.oauth.AbstractOAuthGetToken#consumerKey}.</li>
<li>OAuth Consumer Secret: use this as the {@link
com.google.api.client.auth.oauth.OAuthHmacSigner}.{@link
com.google.api.client.auth.oauth.OAuthHmacSigner#clientSharedSecret
clientSharedSecret} when using the {@code "HMAC-SHA1"} signature method.</li>
<li>Upload new X.509 cert: See the instructions for <a
href="http://code.google.com/apis/gdata/docs/auth/oauth.html#GeneratingKeyCert">generating
a self-signing private key and public certificate</a>. Use {@link
com.google.api.client.auth.oauth.OAuthRsaSigner} for this {@code "RSA-SHA1"}
signature method.
<ul>
<li>Example for generating private key and public certificate:<pre><code>
# Generate the RSA keys and certificate
keytool -genkey -v -alias Example -keystore ./Example.jks\
-keyalg RSA -sigalg SHA1withRSA\
-dname "CN=myappname.appspot.com, OU=Engineering, O=My_Company, L=Mountain View, ST=CA, C=US"\
-storepass changeme -keypass changeme
# Output the public certificate to a file
keytool -export -rfc -keystore ./Example.jks -storepass changeme \
-alias Example -file mycert.pem</code></pre></li>
</ul>
</li>
</ul>
</li>
<li>For an installed application, an unregistered web application, or a
web application running on localhost, you must use the {@code "HMAC-SHA1"}
signature method. Use {@code "anonymous"} for the {@code consumerKey} and
{@code clientSharedSecret}.</li>
</ol>
<p>After the set up has been completed, the typical application flow is:</p>
<ol>
<li>Request a temporary credentials token ("request token") from the
Google Authorization server using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken}. A
callback URL should be specified for web applications, but does not need to be
specified for installed applications.</li>
<li>Direct the end user to a Google Accounts web page to allow the end
user to authorize the temporary token using using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl}.</li>
<li>After the user has granted the authorization:
<ul>
<li>For web applications, the user's browser will be redirected to the
callback URL which may be parsed using {@link
com.google.api.client.auth.oauth.OAuthCallbackUrl}.</li>
<li>For installed applications, use {@code ""} for the verification
code.</li>
</ul>
</li>
<li>Request to exchange the temporary token for a long-lived access token
from the Google Authorization server using {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken}. This
access token must be stored.</li>
<li>Use the stored access token to authorize HTTP requests to protected
resources in Google services by setting the {@link
com.google.api.client.auth.oauth.OAuthParameters#token} and invoking {@link
com.google.api.client.auth.oauth.OAuthParameters#signRequestsUsingAuthorizationHeader}.</li>
<li>For 2-legged OAuth, use {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthDomainWideDelegation}
as a request execute intercepter to set the e-mail address of the user on
every HTTP request, or {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthDomainWideDelegation.Url}
as a generic URL builder with the requestor ID parameter.</li>
<li>To revoke an access token, use {@link
com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken#revokeAccessToken}.
Users can also manually revoke tokens from Google's <a
href="https://www.google.com/accounts/IssuedAuthSubTokens">change
authorized websites</a> page.</li>
</ol>
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.auth.oauth}</li>
<li>{@link com.google.api.client.googleapis}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/oauth/package.html
|
HTML
|
asf20
| 4,995
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/oauth/GoogleOAuthGetTemporaryToken.java
|
Java
|
asf20
| 3,043
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/oauth/GoogleOAuthDomainWideDelegation.java
|
Java
|
asf20
| 2,578
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/oauth/GoogleOAuthGetAccessToken.java
|
Java
|
asf20
| 2,410
|
/*
* 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");
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/oauth/GoogleOAuthAuthorizeTemporaryTokenUrl.java
|
Java
|
asf20
| 2,654
|
<body>
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>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.auth}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/storage/package.html
|
HTML
|
asf20
| 537
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/storage/GoogleStorageAuthentication.java
|
Java
|
asf20
| 5,959
|
<body>
Google's legacy AuthSub authorization as specified in
<a href="http://code.google.com/apis/accounts/docs/AuthSub.html">AuthSub for
Web Applications</a>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.auth}</li>
<li>{@link com.google.api.client.googleapis.auth}</li>
<li>{@link com.google.api.client.http}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/authsub/package.html
|
HTML
|
asf20
| 605
|
/*
* 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));
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/authsub/AuthSubHelper.java
|
Java
|
asf20
| 7,169
|
/*
* 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");
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/authsub/AuthSubSingleUseTokenRequestUrl.java
|
Java
|
asf20
| 3,140
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/authsub/AuthSub.java
|
Java
|
asf20
| 2,697
|
/*
* 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;
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/authsub/AuthSubIntercepter.java
|
Java
|
asf20
| 1,814
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/auth/AuthKeyValueParser.java
|
Java
|
asf20
| 2,974
|
<body>
Google's JSON-C as specified in
<a href="http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html">YouTube
Developer's Guide: JSON-C / JavaScript</a>
(see detailed package specification).
<h2>Package Specification</h2>
<p>User-defined Partial JSON data models allow you to defined Plain Old Java
Objects (POJO's) to define how the library should parse/serialize JSON. Each
field that should be included must have an @{@link
com.google.api.client.util.Key} annotation. The field can be of any visibility
(private, package private, protected, or public) and must not be static. By
default, the field name is used as the JSON key. To override this behavior,
simply specify the JSON key use the optional value parameter of the annotation,
for example {@code @Key("name")}. Any unrecognized keys from the JSON are
normally simply ignored and not stored. If the ability to store unknown keys is
important, use {@link com.google.api.client.json.GenericJson}.</p>
<p>Let's take a look at a typical partial JSON-C video feed from the YouYube
Data API:</p>
<pre><code>
"data":{
"updated":"2010-01-07T19:58:42.949Z",
"totalItems":800,
"startIndex":1,
"itemsPerPage":1,
"items":[
{"id":"hYB0mn5zh2c",
"updated":"2010-01-07T13:26:50.000Z",
"title":"Google Developers Day US - Maps API Introduction",
"description":"Google Maps API Introduction ...",
"tags":[
"GDD07","GDD07US","Maps"
],
"player":{
"default":"http://www.youtube.com/watch?v\u003dhYB0mn5zh2c"
},
...
}
]
}
</code></pre>
<p>Here's one possible way to design the Java data classes for this (each
class in its own Java file):</p>
<pre><code>
import com.google.api.client.util.*;
import java.util.List;
public class VideoFeed {
@Key public int itemsPerPage;
@Key public int startIndex;
@Key public int totalItems;
@Key public DateTime updated;
@Key public List<Video> items;
}
public class Video {
@Key public String id;
@Key public String title;
@Key public DateTime updated;
@Key public String description;
@Key public List<String> tags;
@Key public Player player;
}
public class Player {
// "default" is a Java keyword, so need to specify the JSON key manually
@Key("default")
public String defaultUrl;
}
</code></pre>
<p>You can also use the @{@link com.google.api.client.util.Key} annotation
to defined query parameters for a URL. For example:</p>
<pre><code>
public class YouTubeUrl extends GoogleUrl {
@Key
public String author;
@Key("max-results")
public Integer maxResults;
public YouTubeUrl(String encodedUrl) {
super(encodedUrl);
this.alt = "jsonc";
}
</code></pre>
<p>To work with the YouTube API, you first need to set up the {@link
com.google.api.client.googleapis.GoogleTransport}. For example:</p>
<pre><code>
private static GoogleTransport setUpGoogleTransport() throws IOException {
GoogleTransport transport = new GoogleTransport();
transport.applicationName = "google-youtubejsoncsample-1.0";
transport.setVersionHeader(YouTube.VERSION);
transport.addParser(new JsonParser());
// insert authentication code...
return transport;
}
</code></pre>
<p>Now that we have a transport, we can execute a request to the YouTube API
and parse the result:</p>
<pre><code>
public static VideoFeed list(GoogleTransport transport, YouTubeUrl url)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(VideoFeed.class);
}
</code></pre>
<p>If the server responds with an error the {@link
com.google.api.client.http.HttpRequest#execute} method will throw an {@link
com.google.api.client.http.HttpResponseException}, which has an {@link
com.google.api.client.http.HttpResponse} field which can be parsed the same way
as a success response inside of a catch block. For example:</p>
<pre><code>
try {
...
} catch (HttpResponseException e) {
if (e.response.getParser() != null) {
Error error = e.response.parseAs(Error.class);
// process error response
} else {
String errorContentString = e.response.parseAsString();
// process error response as string
}
throw e;
}
</code></pre>
<p>NOTE: As you might guess, the library uses reflection to populate the
user-defined data model. It's not quite as fast as writing the wire format
parsing code yourself can potentially be, but it's a lot easier.</p>
<p>NOTE: If you prefer to use your favorite JSON parsing library instead
(there are many of them listed for example on <a href="http://json.org">json.org</a>),
that's supported as well. Just call {@link
com.google.api.client.http.HttpRequest#execute()} and parse the returned byte
stream.</p>
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.escape}</li>
<li>{@link com.google.api.client.googleapis}</li>
<li>{@link com.google.api.client.http}</li>
<li>{@link com.google.api.client.json}</li>
<li>{@link com.google.api.client.repackaged.com.google.common.base}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/package.html
|
HTML
|
asf20
| 5,511
|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
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();
}
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/JsonCParser.java
|
Java
|
asf20
| 2,869
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/GoogleApi.java
|
Java
|
asf20
| 5,049
|
/*
* 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;
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/AbstractJsonFeedParser.java
|
Java
|
asf20
| 2,859
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/JsonMultiKindFeedParser.java
|
Java
|
asf20
| 2,918
|
/*
* 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();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/JsonCContent.java
|
Java
|
asf20
| 1,689
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/DiscoveryDocument.java
|
Java
|
asf20
| 4,530
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/json/JsonFeedParser.java
|
Java
|
asf20
| 1,709
|
/*
* 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;
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/googleapis/GoogleHeaders.java
|
Java
|
asf20
| 4,525
|
<body>
General utilities used throughout this library.
<p><b>Warning: this package is experimental, and its content may be
changed in incompatible ways or possibly entirely removed in a future version of
the library</b></p>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/package.html
|
HTML
|
asf20
| 244
|
/*
* 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";
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/Key.java
|
Java
|
asf20
| 1,668
|
/*
* 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);
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/ArrayMap.java
|
Java
|
asf20
| 11,893
|
/*
* 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);
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/FieldInfo.java
|
Java
|
asf20
| 9,039
|
/*
* 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;
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/ReflectionMap.java
|
Java
|
asf20
| 4,208
|
/*
* 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);
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/DateTime.java
|
Java
|
asf20
| 6,201
|
/*
* 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() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/Strings.java
|
Java
|
asf20
| 2,151
|
/*
* 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.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.WeakHashMap;
/**
* Parses class information to determine data key name/value pairs associated with the class.
*
* @since 1.0
* @author Yaniv Inbar
*/
public final class ClassInfo {
private static final ThreadLocal<WeakHashMap<Class<?>, ClassInfo>> CACHE =
new ThreadLocal<WeakHashMap<Class<?>, ClassInfo>>() {
@Override
protected WeakHashMap<Class<?>, ClassInfo> initialValue() {
return new WeakHashMap<Class<?>, ClassInfo>();
}
};
/** Class. */
public final Class<?> clazz;
/** Map from data key name to its field information or {@code null} for none. */
private final IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap;
/**
* Returns the class information for the given class.
*
* @param clazz class or {@code null} for {@code null} result
* @return class information or {@code null} for {@code null} input
*/
public static ClassInfo of(Class<?> clazz) {
if (clazz == null) {
return null;
}
WeakHashMap<Class<?>, ClassInfo> cache = CACHE.get();
ClassInfo classInfo = cache.get(clazz);
if (classInfo == null) {
classInfo = new ClassInfo(clazz);
cache.put(clazz, classInfo);
}
return classInfo;
}
/**
* Returns the information for the given data key name.
*
* @param keyName data key name or {@code null} for {@code null} result
* @return field information or {@code null} for none or for {@code null} input
*/
public FieldInfo getFieldInfo(String keyName) {
if (keyName == null) {
return null;
}
IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap;
if (keyNameToFieldInfoMap == null) {
return null;
}
return keyNameToFieldInfoMap.get(keyName.intern());
}
/**
* Returns the field for the given data key name.
*
* @param keyName data key name or {@code null} for {@code null} result
* @return field or {@code null} for none or for {@code null} input
*/
public Field getField(String keyName) {
FieldInfo fieldInfo = getFieldInfo(keyName);
return fieldInfo == null ? null : fieldInfo.field;
}
/**
* Returns the number of data key name/value pairs associated with this data class.
*/
public int getKeyCount() {
IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap;
if (keyNameToFieldInfoMap == null) {
return 0;
}
return keyNameToFieldInfoMap.size();
}
/** Returns the data key names associated with this data class. */
public Collection<String> getKeyNames() {
IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap;
if (keyNameToFieldInfoMap == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(keyNameToFieldInfoMap.keySet());
}
/** Creates a new instance of the given class using reflection. */
public static <T> T newInstance(Class<T> clazz) {
T newInstance;
try {
newInstance = clazz.newInstance();
} catch (IllegalAccessException e) {
throw handleExceptionForNewInstance(e, clazz);
} catch (InstantiationException e) {
throw handleExceptionForNewInstance(e, clazz);
}
return newInstance;
}
private static IllegalArgumentException handleExceptionForNewInstance(
Exception e, Class<?> clazz) {
StringBuilder buf =
new StringBuilder("unable to create new instance of class ").append(clazz.getName());
if (Modifier.isAbstract(clazz.getModifiers())) {
buf.append(" (and) because it is abstract");
}
if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) {
buf.append(" (and) because it is not static");
}
if (!Modifier.isPublic(clazz.getModifiers())) {
buf.append(" (and) because it is not public");
} else {
try {
clazz.getConstructor();
} catch (NoSuchMethodException e1) {
buf.append(" (and) because it has no public default constructor");
}
}
throw new IllegalArgumentException(buf.toString(), e);
}
/**
* Returns a new instance of the given collection class.
* <p>
* If a concrete collection class in the The class of the returned collection instance depends on
* the input collection class as follows (first that matches):
* <ul>
* <li>{@code null} or {@link ArrayList} is an instance of the collection class: returns an
* {@link ArrayList}</li>
* <li>Concrete subclass of {@link Collection}: returns an instance of that collection class</li>
* <li>{@link HashSet} is an instance of the collection class: returns a {@link HashSet}</li>
* <li>{@link TreeSet} is an instance of the collection class: returns a {@link TreeSet}</li>
* </ul>
*
* @param collectionClass collection class or {@code null} for {@link ArrayList}.
* @return new collection instance
*/
public static Collection<Object> newCollectionInstance(Class<?> collectionClass) {
if (collectionClass == null || collectionClass.isAssignableFrom(ArrayList.class)) {
return new ArrayList<Object>();
}
if (0 == (collectionClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE))) {
@SuppressWarnings("unchecked")
Collection<Object> result = (Collection<Object>) ClassInfo.newInstance(collectionClass);
return result;
}
if (collectionClass.isAssignableFrom(HashSet.class)) {
return new HashSet<Object>();
}
if (collectionClass.isAssignableFrom(TreeSet.class)) {
return new TreeSet<Object>();
}
throw new IllegalArgumentException(
"no default collection class defined for class: " + collectionClass.getName());
}
/** Returns a new instance of the given map class. */
public static Map<String, Object> newMapInstance(Class<?> mapClass) {
if (mapClass != null
&& 0 == (mapClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE))) {
@SuppressWarnings("unchecked")
Map<String, Object> result = (Map<String, Object>) ClassInfo.newInstance(mapClass);
return result;
}
if (mapClass == null || mapClass.isAssignableFrom(ArrayMap.class)) {
return ArrayMap.create();
}
if (mapClass.isAssignableFrom(TreeMap.class)) {
return new TreeMap<String, Object>();
}
throw new IllegalArgumentException(
"no default map class defined for class: " + mapClass.getName());
}
/**
* Returns the type parameter for the given field assuming it is of type collection.
*/
public static Class<?> getCollectionParameter(Field field) {
if (field != null) {
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) genericType).getActualTypeArguments();
if (typeArgs.length == 1 && typeArgs[0] instanceof Class<?>) {
return (Class<?>) typeArgs[0];
}
}
}
return null;
}
/**
* Returns the type parameter for the given field assuming it is of type map.
*/
public static Class<?> getMapValueParameter(Field field) {
if (field != null) {
return getMapValueParameter(field.getGenericType());
}
return null;
}
/**
* Returns the type parameter for the given genericType assuming it is of type map.
*/
public static Class<?> getMapValueParameter(Type genericType) {
if (genericType instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) genericType).getActualTypeArguments();
if (typeArgs.length == 2 && typeArgs[1] instanceof Class<?>) {
return (Class<?>) typeArgs[1];
}
}
return null;
}
private ClassInfo(Class<?> clazz) {
this.clazz = clazz;
// clone map from super class
Class<?> superClass = clazz.getSuperclass();
IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap =
new IdentityHashMap<String, FieldInfo>();
if (superClass != null) {
IdentityHashMap<String, FieldInfo> superKeyNameToFieldInfoMap =
ClassInfo.of(superClass).keyNameToFieldInfoMap;
if (superKeyNameToFieldInfoMap != null) {
keyNameToFieldInfoMap.putAll(superKeyNameToFieldInfoMap);
}
}
Field[] fields = clazz.getDeclaredFields();
int fieldsSize = fields.length;
for (int fieldsIndex = 0; fieldsIndex < fieldsSize; fieldsIndex++) {
Field field = fields[fieldsIndex];
FieldInfo fieldInfo = FieldInfo.of(field);
if (fieldInfo == null) {
continue;
}
String fieldName = fieldInfo.name;
FieldInfo conflictingFieldInfo = keyNameToFieldInfoMap.get(fieldName);
if (conflictingFieldInfo != null) {
throw new IllegalArgumentException(
"two fields have the same data key name: " + field + " and "
+ conflictingFieldInfo.field);
}
keyNameToFieldInfoMap.put(fieldName, fieldInfo);
}
if (keyNameToFieldInfoMap.isEmpty()) {
this.keyNameToFieldInfoMap = null;
} else {
this.keyNameToFieldInfoMap = keyNameToFieldInfoMap;
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/ClassInfo.java
|
Java
|
asf20
| 10,095
|
/*
* 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.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
/**
* Utilities for working with key/value data.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class DataUtil {
/**
* Returns the map to use for the given key/value data.
*
* @param data any key value data, represented by an object or a map, or {@code null}
* @return if {@code data} is a map returns {@code data}; else if {@code data} is {@code null},
* returns an empty map; else returns {@link ReflectionMap} on the data object
*/
public static Map<String, Object> mapOf(Object data) {
if (data == null) {
return Collections.emptyMap();
}
if (data instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, Object> result = (Map<String, Object>) data;
return result;
}
return new ReflectionMap(data);
}
/**
* Returns a deep clone of the given key/value data, such that the result is a completely
* independent copy.
* <p>
* Note that final fields cannot be changed and therefore their value won't be copied.
*
* @param data key/value data object or map to clone or {@code null} for a {@code null} return
* value
* @return deep clone or {@code null} for {@code null} input
*/
public static <T> T clone(T data) {
// don't need to clone primitive
if (FieldInfo.isPrimitive(data)) {
return data;
}
T copy;
if (data instanceof GenericData) {
// use clone method if possible
@SuppressWarnings("unchecked")
T copyTmp = (T) ((GenericData) data).clone();
copy = copyTmp;
} else if (data instanceof ArrayMap<?, ?>) {
// use ArrayMap's clone method if possible
@SuppressWarnings({"unchecked", "rawtypes"})
T copyTmp = (T) ((ArrayMap) data).clone();
copy = copyTmp;
} else {
// else new to use default constructor
@SuppressWarnings("unchecked")
T copyTmp = (T) ClassInfo.newInstance(data.getClass());
copy = copyTmp;
}
cloneInternal(data, copy);
return copy;
}
static void cloneInternal(Object src, Object dest) {
// TODO: support Java arrays?
Class<?> srcClass = src.getClass();
if (Collection.class.isAssignableFrom(srcClass)) {
@SuppressWarnings("unchecked")
Collection<Object> srcCollection = (Collection<Object>) src;
if (ArrayList.class.isAssignableFrom(srcClass)) {
@SuppressWarnings("unchecked")
ArrayList<Object> destArrayList = (ArrayList<Object>) dest;
destArrayList.ensureCapacity(srcCollection.size());
}
@SuppressWarnings("unchecked")
Collection<Object> destCollection = (Collection<Object>) dest;
for (Object srcValue : srcCollection) {
destCollection.add(clone(srcValue));
}
} else {
boolean isGenericData = GenericData.class.isAssignableFrom(srcClass);
if (isGenericData || !Map.class.isAssignableFrom(srcClass)) {
ClassInfo classInfo = ClassInfo.of(srcClass);
for (String fieldName : classInfo.getKeyNames()) {
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
// skip final fields
if (!fieldInfo.isFinal) {
// generic data already has primitive types copied by clone()
if (!isGenericData || !fieldInfo.isPrimitive) {
Object srcValue = fieldInfo.getValue(src);
if (srcValue != null) {
fieldInfo.setValue(dest, clone(srcValue));
}
}
}
}
} else if (ArrayMap.class.isAssignableFrom(srcClass)) {
@SuppressWarnings("unchecked")
ArrayMap<Object, Object> destMap = (ArrayMap<Object, Object>) dest;
@SuppressWarnings("unchecked")
ArrayMap<Object, Object> srcMap = (ArrayMap<Object, Object>) src;
int size = srcMap.size();
for (int i = 0; i < size; i++) {
Object srcValue = srcMap.getValue(i);
if (!FieldInfo.isPrimitive(srcValue)) {
destMap.set(i, clone(srcValue));
}
}
} else {
@SuppressWarnings("unchecked")
Map<String, Object> destMap = (Map<String, Object>) dest;
@SuppressWarnings("unchecked")
Map<String, Object> srcMap = (Map<String, Object>) src;
for (Map.Entry<String, Object> srcEntry : srcMap.entrySet()) {
destMap.put(srcEntry.getKey(), clone(srcEntry.getValue()));
}
}
}
}
private DataUtil() {
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/DataUtil.java
|
Java
|
asf20
| 5,161
|
/*
* 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;
// This code was copied from code at http://iharder.sourceforge.net/base64/
// Lots of extraneous features were removed: encodeObject, decodeToObject,
// encodeFromFile, encodeFileToFile, encodeToFile, InputStream, OutputStream,
// decode(String, ...), encode(ByteBuffer,...), encode3to4 not used, URL_SAFE
// and ORDERED *bets, options
// original class JavaDoc:
/*
* <p>Encodes and decodes to and from Base64 notation.</p> <p>Homepage: <a
* href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code> <br /> <code>byte[] myByteArray =
* Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass several pieces
* of information to the encoder. In the "higher level" methods such as encodeBytes( bytes, options
* ) the options parameter can be used to indicate such things as first gzipping the bytes before
* encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, Section 2.1,
* implementations should not add line feeds unless explicitly told to do so. I've got Base64 set to
* this behavior now, although earlier versions broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you might make a
* call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline
* characters.</p> <p>Also...</p> <code>String encoded = Base64.encodeBytes( crazyString.getBytes()
* );</code>
*
*
*
* <p> Change Log: </p> <ul> <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
* value 01111111, which is an invalid base 64 character but should not throw an
* ArrayIndexOutOfBoundsException either. Led to discovery of mishandling (or potential for better
* handling) of other bad input characters. You should now get an IOException if you try decoding
* something that has bad characters in it.</li> <li>v2.3.6 - Fixed bug when breaking lines and the
* final byte of the encoded string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li> <li>v2.3.5 - Fixed bug in
* {@code encodeFromFile} where estimated buffer size was wrong for files of size 31, 34, and 37
* bytes.</li> <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing the
* Base64.OutputStream closed the Base64 encoding (by padding with equals signs) too soon. Also
* added an option to suppress the automatic decoding of gzipped streams. Also added experimental
* support for specifying a class loader when using the {@code decodeToObject(java.lang.String, int,
* java.lang.ClassLoader)} method.</li> <li>v2.3.3 - Changed default char encoding to US-ASCII which
* reduces the internal Java footprint with its CharEncoders and so forth. Fixed some javadocs that
* were inconsistent. Removed imports and specified things like java.io.IOException explicitly
* inline.</li> <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output arrays: an
* oversized initial one and then a final, exact-sized one. Big win when using the {@code
* encodeBytesToBytes(byte[])} family of methods (and not using the gzip options which uses a
* different mechanism with streams and stuff).</li> <li>v2.3.1 - Added {@code
* encodeBytesToBytes(byte[], int, int, int)} and some similar helper methods to be more efficient
* with memory by not returning a String but just a byte array.</li> <li>v2.3 - <strong>This is not
* a drop-in replacement!</strong> This is two years of comments and bug fixes queued up and finally
* executed. Thanks to everyone who sent me stuff, and I'm sorry I wasn't able to distribute your
* fixes to everyone else. Much bad coding was cleaned up including throwing exceptions where
* necessary instead of returning null values or something similar. Here are some changes that may
* affect you: <ul> <li><em>Does not break lines, by default.</em> This is to keep in compliance
* with <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> <li><em>Throws exceptions
* instead of returning null values.</em> Because some operations (especially those that may permit
* the GZIP option) use IO streams, there is a possiblity of an java.io.IOException being thrown.
* After some discussion and thought, I've changed the behavior of the methods to throw
* java.io.IOExceptions rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry, it should have been done
* this way to begin with.</li> <li><em>Removed all references to System.out, System.err, and the
* like.</em> Shame on me. All I can say is sorry they were ever there.</li> <li><em>Throws
* NullPointerExceptions and IllegalArgumentExceptions</em> as needed such as when passed arrays are
* null or offsets are invalid.</li> <li>Cleaned up as much javadoc as I could to avoid any javadoc
* warnings. This was especially annoying before for people who were thorough in their own projects
* and then had gobs of javadoc warnings on this file.</li> </ul> <li>v2.2.1 - Fixed bug using
* URL_SAFE and ORDERED encodings. Fixed bug when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from one file to the next.
* Also added a main() method to support command line encoding/decoding from one file to the next.
* Also added these Base64 dialects: <ol> <li>The default is RFC3548 format.</li> <li>Calling
* Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates URL and file name friendly format
* as described in Section 4 of RFC3548. http://www.faqs.org/rfcs/rfc3548.html</li> <li>Calling
* Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates URL and file name friendly format
* that preserves lexical ordering as described in http://www.faqs.org/qa/rfcc-1940.html</li> </ol>
* Special thanks to Jim Kellerman at <a
* href="http://www.powerset.com/">http://www.powerset.com/</a> for contributing the new Base64
* dialects. </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added some convenience
* methods for reading and writing to and from files.</li> <li>v2.0.2 - Now specifies UTF-8 encoding
* in places where the code fails on systems with other encodings (like EBCDIC).</li> <li>v2.0.1 -
* Fixed an error when decoding a single byte, that is, when the encoded data was a single
* byte.</li> <li>v2.0 - I got rid of methods that used booleans to set options. Now everything is
* more consolidated and cleaner. The code now detects when data that's being decoded is
* gzip-compressed and will decompress it automatically. Generally things are cleaner. You'll
* probably have to change some method calls that you were making to support the new options format
* (<tt>int</tt>s that you "OR" together).</li> <li>v1.5.1 - Fixed bug when decompressing and
* decoding to a byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. Added the ability
* to "suspend" encoding in the Output Stream so you can turn on and off the encoding if you need to
* embed base64 data in an otherwise "normal" stream (like an XML file).</li> <li>v1.5 - Output
* stream pases on flush() command but doesn't do anything itself. This helps when using GZIP
* streams. Added the ability to GZip-compress objects before encoding them.</li> <li>v1.4 - Added
* helper methods to read/write files.</li> <li>v1.3.6 - Fixed OutputStream.flush() so that
* 'position' is reset.</li> <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in
* input stream where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> </ul>
*
* <p> I am placing this code in the Public Domain. Do with it as you will. This software comes with
* no guarantees or warranties but with plenty of well-wishing instead! Please visit <a
* href="http://iharder.net/base64">http://iharder.net/base64</a> periodically to check for updates
* or to contribute improvements. </p>
*
* @author Robert Harder
*
* @author rob@iharder.net
*
* @version 2.3.7
*/
public class Base64 {
/* ******** P R I V A T E F I E L D S ******** */
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] ALPHABET = {(byte) 'A',
(byte) 'B',
(byte) 'C',
(byte) 'D',
(byte) 'E',
(byte) 'F',
(byte) 'G',
(byte) 'H',
(byte) 'I',
(byte) 'J',
(byte) 'K',
(byte) 'L',
(byte) 'M',
(byte) 'N',
(byte) 'O',
(byte) 'P',
(byte) 'Q',
(byte) 'R',
(byte) 'S',
(byte) 'T',
(byte) 'U',
(byte) 'V',
(byte) 'W',
(byte) 'X',
(byte) 'Y',
(byte) 'Z',
(byte) 'a',
(byte) 'b',
(byte) 'c',
(byte) 'd',
(byte) 'e',
(byte) 'f',
(byte) 'g',
(byte) 'h',
(byte) 'i',
(byte) 'j',
(byte) 'k',
(byte) 'l',
(byte) 'm',
(byte) 'n',
(byte) 'o',
(byte) 'p',
(byte) 'q',
(byte) 'r',
(byte) 's',
(byte) 't',
(byte) 'u',
(byte) 'v',
(byte) 'w',
(byte) 'x',
(byte) 'y',
(byte) 'z',
(byte) '0',
(byte) '1',
(byte) '2',
(byte) '3',
(byte) '4',
(byte) '5',
(byte) '6',
(byte) '7',
(byte) '8',
(byte) '9',
(byte) '+',
(byte) '/'};
/**
* Translates a Base64 value to either its 6-bit reconstruction value or a negative number
* indicating some other meaning.
**/
private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5,
-5, // Whitespace: Tab and Linefeed
-9,
-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 14 - 26
-9,
-9,
-9,
-9,
-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,
-9,
-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,
53,
54,
55,
56,
57,
58,
59,
60,
61, // Numbers zero through nine
-9,
-9,
-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,
-9,
-9, // Decimal 62 - 64
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13, // Letters 'A' through 'N'
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25, // Letters 'O' through 'Z'
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 91 - 96
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38, // Letters 'a' through 'm'
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51, // Letters 'n' through 'z'
-9,
-9,
-9,
-9,
-9 // Decimal 123 - 127
,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 128 - 139
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 140 - 152
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 153 - 165
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 166 - 178
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 179 - 191
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 192 - 204
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 205 - 217
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 218 - 230
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 231 - 243
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9 // Decimal 244 - 255
};
/** Defeats instantiation. */
private Base64() {
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64
* bytes to <var>destination</var>. The source and destination arrays can be manipulated anywhere
* along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 3
* for the <var>source</var> array or <var>destOffset</var> + 4 for the <var>destination</var>
* array. The actual number of significant bytes in your array is given by <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible parameters.
* </p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
(numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0)
| (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16 : 0)
| (numSigBytes > 2 ? source[srcOffset + 2] << 24 >>> 24 : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f];
destination[destOffset + 3] = ALPHABET[inBuff & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Similar to {@link #encode(byte[])} but returns a byte array instead of instantiating a String.
* This is more efficient if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encode(byte[] source) {
return encode(source, 0, source.length);
}
/**
* Similar to {@link #encode(byte[], int, int)} but returns a byte array instead of instantiating
* a String. This is more efficient if you're working with I/O streams and have large data sets to
* encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encode(byte[] source, int off, int len) {
if (source == null) {
throw new NullPointerException("Cannot serialize a null array.");
} // end if: null
if (off < 0) {
throw new IllegalArgumentException("Cannot have negative offset: " + off);
} // end if: off < 0
if (len < 0) {
throw new IllegalArgumentException("Cannot have length offset: " + len);
} // end if: len < 0
if (off + len > source.length) {
throw new IllegalArgumentException(
String.format("Cannot have offset of %d and length of %d with array of length %d", off,
len, source.length));
} // end if: off < 0
// Else, don't compress. Better not to use streams at all then.
// int len43 = len * 4 / 3;
// byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = len / 3 * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e);
lineLength += 4;
} // end for: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if (e <= outBuff.length - 1) {
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
// System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
}
// System.err.println("No need to resize array.");
return outBuff;
// end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of
* them) to <var>destination</var>. The source and destination arrays can be manipulated anywhere
* along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 4
* for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var>
* array. This method returns the actual number of bytes that were converted from the Base64
* encoding.
* <p>
* This is the lowest level of the decoding methods with all possible parameters.
* </p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid or there is not enough
* room in the array.
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Source array was null.");
} // end if
if (destination == null) {
throw new NullPointerException("Destination array was null.");
} // end if
if (srcOffset < 0 || srcOffset + 3 >= source.length) {
throw new IllegalArgumentException(String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.",
source.length, srcOffset));
} // end if
if (destOffset < 0 || destOffset + 2 >= destination.length) {
throw new IllegalArgumentException(
String
.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset));
} // end if
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18
| (DECODABET[source[srcOffset + 1]] & 0xFF) << 12;
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff =
(DECODABET[source[srcOffset]] & 0xFF) << 18
| (DECODABET[source[srcOffset + 1]] & 0xFF) << 12
| (DECODABET[source[srcOffset + 2]] & 0xFF) << 6;
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff =
(DECODABET[source[srcOffset]] & 0xFF) << 18
| (DECODABET[source[srcOffset + 1]] & 0xFF) << 12
| (DECODABET[source[srcOffset + 2]] & 0xFF) << 6 | DECODABET[source[srcOffset + 3]]
& 0xFF;
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) outBuff;
return 3;
}
} // end decodeToBytes
/**
* Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores
* GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it is
* used internally as part of the decoding process. Special case: if len = 0, an empty array is
* returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping),
* consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode(byte[] source) throws java.io.IOException {
return decode(source, 0, source.length);
}
/**
* Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores
* GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it is
* used internally as part of the decoding process. Special case: if len = 0, an empty array is
* returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping),
* consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
@SuppressWarnings("cast")
public static byte[] decode(byte[] source, int off, int len) throws java.io.IOException {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Cannot decode null source array.");
} // end if
if (off < 0 || off + len > source.length) {
throw new IllegalArgumentException(String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.",
source.length, off, len));
} // end if
if (len == 0) {
return new byte[0];
} else if (len < 4) {
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was "
+ len);
} // end if
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for (i = off; i < off + len; i++) { // Loop through source
sbiDecode = DECODABET[source[i] & 0xFF];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if (sbiDecode >= WHITE_SPACE_ENC) {
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = source[i]; // Save non-whitespace
if (b4Posn > 3) { // Time to decode?
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (source[i] == EQUALS_SIGN) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException(
String.format("Bad Base64 input character decimal %d in array position %d",
(int) source[i] & 0xFF, i));
} // end else:
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} // end decode
} // end class Base64
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/Base64.java
|
Java
|
asf20
| 29,165
|
/*
* 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.Set;
/**
* Generic data that stores all unknown data key name/value pairs.
* <p>
* Subclasses can declare fields for known data keys 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.
* <p>
* Iteration order of the data keys is based on the sorted (ascending) key names of the declared
* fields, followed by the iteration order of all of the unknown data key name/value pairs.
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GenericData extends AbstractMap<String, Object> implements Cloneable {
// TODO: type parameter to specify value type?
private EntrySet entrySet;
/** Map of unknown fields. */
public ArrayMap<String, Object> unknownFields = ArrayMap.create();
// TODO: implement more methods for faster implementation
final ClassInfo classInfo = ClassInfo.of(getClass());
@Override
public int size() {
return classInfo.getKeyCount() + unknownFields.size();
}
@Override
public final Object get(Object name) {
if (!(name instanceof String)) {
return null;
}
String fieldName = (String) name;
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
if (fieldInfo != null) {
return fieldInfo.getValue(this);
}
return unknownFields.get(fieldName);
}
@Override
public final Object put(String name, Object value) {
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Object oldValue = fieldInfo.getValue(this);
fieldInfo.setValue(this, value);
return oldValue;
}
return unknownFields.put(name, value);
}
/**
* Sets the given field value (may be {@code null}) for the given field name. Any existing value
* for the field will be overwritten. It may be more slightly more efficient than
* {@link #put(String, Object)} because it avoids accessing the field's original value.
*/
public final void set(String name, Object value) {
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
fieldInfo.setValue(this, value);
return;
}
unknownFields.put(name, value);
}
@Override
public final void putAll(Map<? extends String, ?> map) {
for (Map.Entry<? extends String, ?> entry : map.entrySet()) {
set(entry.getKey(), entry.getValue());
}
}
@Override
public final Object remove(Object name) {
if (name instanceof String) {
String fieldName = (String) name;
FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
if (fieldInfo != null) {
throw new UnsupportedOperationException();
}
return unknownFields.remove(name);
}
return null;
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
EntrySet entrySet = this.entrySet;
if (entrySet == null) {
entrySet = this.entrySet = new EntrySet();
}
return entrySet;
}
@Override
public GenericData clone() {
try {
@SuppressWarnings("unchecked")
GenericData result = (GenericData) super.clone();
result.entrySet = null;
DataUtil.cloneInternal(this, result);
result.unknownFields = DataUtil.clone(unknownFields);
return result;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
final class EntrySet extends AbstractSet<Map.Entry<String, Object>> {
@Override
public Iterator<Map.Entry<String, Object>> iterator() {
return new EntryIterator();
}
@Override
public int size() {
return GenericData.this.size();
}
}
final class EntryIterator implements Iterator<Map.Entry<String, Object>> {
private boolean startedUnknown;
private final Iterator<Map.Entry<String, Object>> unknownIterator;
private final ReflectionMap.EntryIterator fieldIterator;
EntryIterator() {
fieldIterator = new ReflectionMap.EntryIterator(classInfo, GenericData.this);
unknownIterator = unknownFields.entrySet().iterator();
}
public boolean hasNext() {
return !startedUnknown && fieldIterator.hasNext() || unknownIterator.hasNext();
}
public Map.Entry<String, Object> next() {
if (!startedUnknown) {
ReflectionMap.EntryIterator fieldIterator = this.fieldIterator;
if (fieldIterator.hasNext()) {
return fieldIterator.next();
}
startedUnknown = true;
}
return unknownIterator.next();
}
public void remove() {
if (startedUnknown) {
unknownIterator.remove();
}
throw new UnsupportedOperationException();
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/util/GenericData.java
|
Java
|
asf20
| 5,485
|
<body>
JSON as specified in
<a href="http://tools.ietf.org/html/rfc4627">RFC 4627: The application/json
Media Type for JavaScript Object Notation (JSON)</a>
and
<a href="http://json.org/">Introducing JSON</a>
.
<p>This package depends on theses packages:</p>
<ul>
<li>{@link com.google.api.client.http}</li>
<li>{@link com.google.api.client.util}</li>
<li>{@link org.codehaus.jackson}</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>
@since 1.0
</body>
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/json/package.html
|
HTML
|
asf20
| 592
|
/*
* 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.json;
import com.google.api.client.http.HttpParser;
import com.google.api.client.http.HttpResponse;
import org.codehaus.jackson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
/**
* Parses HTTP JSON response content into an data class of key/value pairs.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setParser(HttpTransport transport) {
* transport.addParser(new JsonHttpParser());
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class JsonHttpParser implements HttpParser {
/** Content type. Default value is {@link Json#CONTENT_TYPE}. */
public String contentType = Json.CONTENT_TYPE;
public final String getContentType() {
return contentType;
}
public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException {
return Json.parseAndClose(JsonHttpParser.parserForResponse(response), dataClass, null);
}
/**
* Returns a JSON parser to use for parsing the given HTTP response.
* <p>
* The response content will be closed if any throwable is thrown. On success, the current token
* will be the first key in the JSON object.
*
* @param response HTTP response
* @return JSON parser
* @throws IllegalArgumentException if content type is not {@link Json#CONTENT_TYPE}
* @throws IOException I/O exception
*/
public static JsonParser parserForResponse(HttpResponse response) throws IOException {
InputStream content = response.getContent();
try {
JsonParser parser = Json.JSON_FACTORY.createJsonParser(content);
parser.nextToken();
content = null;
return parser;
} finally {
if (content != null) {
content.close();
}
}
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/json/JsonHttpParser.java
|
Java
|
asf20
| 2,345
|
/*
* 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.json;
import com.google.api.client.http.HttpContent;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import java.io.IOException;
import java.io.OutputStream;
/**
* Serializes JSON HTTP content based on the data key/value mapping object for an item.
* <p>
* Sample usage:
*
* <pre>
* <code>
* static void setContent(HttpRequest request, Object data) {
* JsonHttpContent content = new JsonHttpContent();
* content.data = data;
* request.content = content;
* }
* </code>
* </pre>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class JsonHttpContent implements HttpContent {
// TODO: ability to annotate fields as only needed for POST?
/** Content type. Default value is {@link Json#CONTENT_TYPE}. */
public String contentType = Json.CONTENT_TYPE;
/** Key/value pair data. */
public Object data;
public long getLength() {
// TODO
return -1;
}
public final String getEncoding() {
return null;
}
public String getType() {
return Json.CONTENT_TYPE;
}
public void writeTo(OutputStream out) throws IOException {
JsonGenerator generator = Json.JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
Json.serialize(generator, data);
generator.close();
}
}
|
11durong-mytest1
|
google-api-client/src/com/google/api/client/json/JsonHttpContent.java
|
Java
|
asf20
| 1,892
|