Google Api

This commit is contained in:
Paul Schneider 2017-06-20 02:47:52 +02:00
commit 83f9fc1bd8
123 changed files with 12961 additions and 60 deletions

View file

@ -0,0 +1,166 @@
/*
Copyright 2011 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Google.Apis.Util;
namespace Google.Apis.Requests.Parameters
{
/// <summary>A collection of parameters (key value pairs). May contain duplicate keys.</summary>
public class ParameterCollection : List<KeyValuePair<string, string>>
{
/// <summary>Constructs a new parameter collection.</summary>
public ParameterCollection() : base() { }
/// <summary>Constructs a new parameter collection from the given collection.</summary>
public ParameterCollection(IEnumerable<KeyValuePair<string, string>> collection) : base(collection) { }
/// <summary>Adds a single parameter to this collection.</summary>
public void Add(string key, string value)
{
Add(new KeyValuePair<string, string>(key, value));
}
/// <summary>Returns <c>true</c> if this parameter is set within the collection.</summary>
public bool ContainsKey(string key)
{
key.ThrowIfNullOrEmpty("key");
string value;
return TryGetValue(key, out value);
}
/// <summary>
/// Tries to find the a key within the specified key value collection. Returns true if the key was found.
/// If a pair was found the out parameter value will contain the value of that pair.
/// </summary>
public bool TryGetValue(string key, out string value)
{
key.ThrowIfNullOrEmpty("key");
foreach (KeyValuePair<string, string> pair in this)
{
// Check if this pair matches the specified key name.
if (pair.Key.Equals(key))
{
value = pair.Value;
return true;
}
}
// No result found.
value = null;
return false;
}
/// <summary>
/// Returns the value of the first matching key, or throws a KeyNotFoundException if the parameter is not
/// present within the collection.
/// </summary>
public string GetFirstMatch(string key)
{
string val;
if (!TryGetValue(key, out val))
{
throw new KeyNotFoundException("Parameter with the name '" + key + "' was not found.");
}
return val;
}
/// <summary>
/// Returns all matches for the specified key. May return an empty enumeration if the key is not present.
/// </summary>
public IEnumerable<string> GetAllMatches(string key)
{
key.ThrowIfNullOrEmpty("key");
foreach (KeyValuePair<string, string> pair in this)
{
// Check if this pair matches the specified key name.
if (pair.Key.Equals(key))
{
yield return pair.Value;
}
}
}
/// <summary>
/// Returns all matches for the specified key. May return an empty enumeration if the key is not present.
/// </summary>
public IEnumerable<string> this[string key]
{
get { return GetAllMatches(key); }
}
/// <summary>
/// Creates a parameter collection from the specified URL encoded query string.
/// Example:
/// The query string "foo=bar&amp;chocolate=cookie" would result in two parameters (foo and bar)
/// with the values "bar" and "cookie" set.
/// </summary>
public static ParameterCollection FromQueryString(string qs)
{
var collection = new ParameterCollection();
var qsParam = qs.Split('&');
foreach (var param in qsParam)
{
// Split the parameter into key and value.
var info = param.Split(new[] { '=' });
if (info.Length == 2)
{
collection.Add(Uri.UnescapeDataString(info[0]), Uri.UnescapeDataString(info[1]));
}
else
{
throw new ArgumentException(string.Format(
"Invalid query string [{0}]. Invalid part [{1}]", qs, param));
}
}
return collection;
}
/// <summary>
/// Creates a parameter collection from the specified dictionary.
/// If the value is an enumerable, a parameter pair will be added for each value.
/// Otherwise the value will be converted into a string using the .ToString() method.
/// </summary>
public static ParameterCollection FromDictionary(IDictionary<string, object> dictionary)
{
var collection = new ParameterCollection();
foreach (KeyValuePair<string, object> pair in dictionary)
{
// Try parsing the value of the pair as an enumerable.
var valueAsEnumerable = pair.Value as IEnumerable;
if (!(pair.Value is string) && valueAsEnumerable != null)
{
foreach (var value in valueAsEnumerable)
{
collection.Add(pair.Key, Util.Utilities.ConvertToString(value));
}
}
else
{
// Otherwise just convert it to a string.
collection.Add(pair.Key, pair.Value == null ? null : Util.Utilities.ConvertToString(pair.Value));
}
}
return collection;
}
}
}

View file

@ -0,0 +1,150 @@
/*
Copyright 2013 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Linq;
using System.Reflection;
using Google.Apis.Logging;
using Google.Apis.Util;
namespace Google.Apis.Requests.Parameters
{
/// <summary>
/// Utility class for iterating on <see cref="RequestParameterAttribute"/> properties in a request object.
/// </summary>
public static class ParameterUtils
{
private static readonly ILogger Logger = ApplicationContext.Logger.ForType(typeof(ParameterUtils));
/// <summary>
/// Creates a <see cref="System.Net.Http.FormUrlEncodedContent"/> with all the specified parameters in
/// the input request. It uses reflection to iterate over all properties with
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute.
/// </summary>
/// <param name="request">
/// A request object which contains properties with
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute. Those properties will be serialized
/// to the returned <see cref="System.Net.Http.FormUrlEncodedContent"/>.
/// </param>
/// <returns>
/// A <see cref="System.Net.Http.FormUrlEncodedContent"/> which contains the all the given object required
/// values.
/// </returns>
public static FormUrlEncodedContent CreateFormUrlEncodedContent(object request)
{
IList<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
IterateParameters(request, (type, name, value) =>
{
list.Add(new KeyValuePair<string, string>(name, value.ToString()));
});
return new FormUrlEncodedContent(list);
}
/// <summary>
/// Creates a parameter dictionary by using reflection to iterate over all properties with
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute.
/// </summary>
/// <param name="request">
/// A request object which contains properties with
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute. Those properties will be set
/// in the output dictionary.
/// </param>
public static IDictionary<string, object> CreateParameterDictionary(object request)
{
var dict = new Dictionary<string, object>();
IterateParameters(request, (type, name, value) =>
{
dict.Add(name, value);
});
return dict;
}
/// <summary>
/// Sets query parameters in the given builder with all all properties with the
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute.
/// </summary>
/// <param name="builder">The request builder</param>
/// <param name="request">
/// A request object which contains properties with
/// <see cref="Google.Apis.Util.RequestParameterAttribute"/> attribute. Those properties will be set in the
/// given request builder object
/// </param>
public static void InitParameters(RequestBuilder builder, object request)
{
IterateParameters(request, (type, name, value) =>
{
builder.AddParameter(type, name, value.ToString());
});
}
/// <summary>
/// Iterates over all <see cref="Google.Apis.Util.RequestParameterAttribute"/> properties in the request
/// object and invokes the specified action for each of them.
/// </summary>
/// <param name="request">A request object</param>
/// <param name="action">An action to invoke which gets the parameter type, name and its value</param>
private static void IterateParameters(object request, Action<RequestParameterType, string, object> action)
{
// Use reflection to build the parameter dictionary.
foreach (PropertyInfo property in request.GetType().GetProperties(BindingFlags.Instance |
BindingFlags.Public))
{
// Retrieve the RequestParameterAttribute.
RequestParameterAttribute attribute =
property.GetCustomAttributes(typeof(RequestParameterAttribute), false).FirstOrDefault() as
RequestParameterAttribute;
if (attribute == null)
{
continue;
}
// Get the name of this parameter from the attribute, if it doesn't exist take a lower-case variant of
// property name.
string name = attribute.Name ?? property.Name.ToLower();
var propertyType = property.PropertyType;
var value = property.GetValue(request, null);
// Call action with the type name and value.
if (propertyType.GetTypeInfo().IsValueType || value != null)
{
if (attribute.Type == RequestParameterType.UserDefinedQueries)
{
if (typeof(IEnumerable<KeyValuePair<string, string>>).IsAssignableFrom(value.GetType()))
{
foreach (var pair in (IEnumerable<KeyValuePair<string, string>>)value)
{
action(RequestParameterType.Query, pair.Key, pair.Value);
}
}
else
{
Logger.Warning("Parameter marked with RequestParameterType.UserDefinedQueries attribute " +
"was not of type IEnumerable<KeyValuePair<string, string>> and will be skipped.");
}
}
else
{
action(attribute.Type, name, value);
}
}
}
}
}
}

View file

@ -0,0 +1,48 @@
/*
Copyright 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.
*/
using System;
using System.Text.RegularExpressions;
using Google.Apis.Discovery;
using Google.Apis.Testing;
namespace Google.Apis.Requests.Parameters
{
/// <summary>Logic for validating a parameter.</summary>
public static class ParameterValidator
{
/// <summary>Validates a parameter value against the methods regex.</summary>
[VisibleForTestOnly]
public static bool ValidateRegex(IParameter param, string paramValue)
{
return string.IsNullOrEmpty(param.Pattern) || new Regex(param.Pattern).IsMatch(paramValue);
}
/// <summary>Validates if a parameter is valid.</summary>
public static bool ValidateParameter(IParameter parameter, string value)
{
// Fail if a required parameter is not present.
if (String.IsNullOrEmpty(value))
{
return !parameter.IsRequired;
}
// The parameter has value so validate the regex.
return ValidateRegex(parameter, value);
}
}
}

View file

@ -0,0 +1,308 @@
/*
Copyright 2012 Google Inc
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using Google.Apis.Http;
using Google.Apis.Logging;
using Google.Apis.Util;
namespace Google.Apis.Requests
{
/// <summary>Utility class for building a URI using <see cref="BuildUri"/> or a HTTP request using
/// <see cref="CreateRequest"/> from the query and path parameters of a REST call.</summary>
public class RequestBuilder
{
static RequestBuilder()
{
UriPatcher.PatchUriQuirks();
}
private static readonly ILogger Logger = ApplicationContext.Logger.ForType<RequestBuilder>();
/// <summary>Pattern to get the groups that are part of the path.</summary>
private static Regex PathParametersPattern = new Regex(@"{[^{}]*}*");
/// <summary>Supported HTTP methods.</summary>
private static IEnumerable<string> SupportedMethods = new List<string>
{
HttpConsts.Get, HttpConsts.Post, HttpConsts.Put, HttpConsts.Delete, HttpConsts.Patch
};
/// <summary>
/// A dictionary containing the parameters which will be inserted into the path of the URI. These parameters
/// will be substituted into the URI path where the path contains "{key}". See
/// http://tools.ietf.org/html/rfc6570 for more information.
/// </summary>
private IDictionary<string, IList<string>> PathParameters { get; set; }
/// <summary>
/// A dictionary containing the parameters which will apply to the query portion of this request.
/// </summary>
private List<KeyValuePair<string, string>> QueryParameters { get; set; }
/// <summary>The base URI for this request (usually applies to the service itself).</summary>
public Uri BaseUri { get; set; }
/// <summary>
/// The path portion of this request. It's appended to the <see cref="BaseUri"/> and the parameters are
/// substituted from the <see cref="PathParameters"/> dictionary.
/// </summary>
public string Path { get; set; }
/// <summary>The HTTP method used for this request.</summary>
private string method;
/// <summary>The HTTP method used for this request (such as GET, PUT, POST, etc...).</summary>
/// <remarks>The default Value is <see cref="Google.Apis.Http.HttpConsts.Get"/>.</remarks>
public string Method
{
get { return method; }
set
{
if (!SupportedMethods.Contains(value))
throw new ArgumentOutOfRangeException("Method");
method = value;
}
}
/// <summary>Construct a new request builder.</summary>
/// TODO(peleyal): Consider using the Factory pattern here.
public RequestBuilder()
{
PathParameters = new Dictionary<string, IList<string>>();
QueryParameters = new List<KeyValuePair<string, string>>();
Method = HttpConsts.Get;
}
/// <summary>Constructs a Uri as defined by the parts of this request builder.</summary>
public Uri BuildUri()
{
var restPath = BuildRestPath();
if (QueryParameters.Count > 0)
{
// In case the path already contains '?' - we should add '&'. Otherwise add '?'.
restPath.Append(restPath.ToString().Contains("?") ? "&" : "?");
// If parameter value is empty - just add the "name", otherwise "name=value"
restPath.Append(String.Join("&", QueryParameters.Select(
x => string.IsNullOrEmpty(x.Value) ?
Uri.EscapeDataString(x.Key) :
String.Format("{0}={1}", Uri.EscapeDataString(x.Key), Uri.EscapeDataString(x.Value)))
.ToArray()));
}
return new Uri(this.BaseUri, restPath.ToString());
}
/// <summary>Operator list that can appear in the path argument.</summary>
private const string OPERATORS = "+#./;?&|!@=";
/// <summary>
/// Builds the REST path string builder based on <see cref="PathParameters"/> and the URI template spec
/// http://tools.ietf.org/html/rfc6570.
/// </summary>
/// <returns></returns>
private StringBuilder BuildRestPath()
{
if (string.IsNullOrEmpty(Path))
{
return new StringBuilder(string.Empty);
}
var restPath = new StringBuilder(Path);
var matches = PathParametersPattern.Matches(restPath.ToString());
foreach (var match in matches)
{
var matchStr = match.ToString();
// Strip the first and last characters: '{' and '}'.
var content = matchStr.Substring(1, matchStr.Length - 2);
var op = string.Empty;
// If the content's first character is an operator, save and remove it from the content string.
if (OPERATORS.Contains(content[0].ToString()))
{
op = content[0].ToString();
content = content.Substring(1);
}
var newContent = new StringBuilder();
// Iterate over all possible parameters.
var parameters = content.Split(',');
for (var index = 0; index < parameters.Length; ++index)
{
var parameter = parameters[index];
var parameterName = parameter;
var containStar = false;
var numOfChars = 0;
// Check if it ends with '*'.
if (parameterName[parameterName.Length - 1] == '*')
{
containStar = true;
parameterName = parameterName.Substring(0, parameterName.Length - 1);
}
// Check if it contains :n which means we should only use the first n characters of this parameter.
if (parameterName.Contains(":"))
{
if (!int.TryParse(parameterName.Substring(parameterName.IndexOf(":") + 1), out numOfChars))
{
throw new ArgumentException(
string.Format("Can't parse number after ':' in Path \"{0}\". Parameter is \"{1}\"",
Path, parameterName), Path);
}
parameterName = parameterName.Substring(0, parameterName.IndexOf(":"));
}
// We can improve the following if statement, but for readability we will leave it like that.
var joiner = op;
var start = op;
switch (op)
{
case "+":
start = index == 0 ? "" : ",";
joiner = ",";
break;
case ".":
if (!containStar)
{
joiner = ",";
}
break;
case "/":
if (!containStar)
{
joiner = ",";
}
break;
case "#":
start = index == 0 ? "#" : ",";
joiner = ",";
break;
case "?":
start = (index == 0 ? "?" : "&") + parameterName + "=";
joiner = ",";
if (containStar)
{
joiner = "&" + parameterName + "=";
}
break;
case "&":
case ";":
start = op + parameterName + "=";
joiner = ",";
if (containStar)
{
joiner = op + parameterName + "=";
}
break;
// No operator, in that case just ','.
default:
if (index > 0)
{
start = ",";
}
joiner = ",";
break;
}
// Check if a path parameter equals the name which appears in the REST path.
if (PathParameters.ContainsKey(parameterName))
{
var value = string.Join(joiner, PathParameters[parameterName]);
// Check if we need to use a substring of the value.
if (numOfChars != 0 && numOfChars < value.Length)
{
value = value.Substring(0, numOfChars);
}
if (op != "+" && op != "#" && PathParameters[parameterName].Count == 1)
{
value = Uri.EscapeDataString(value);
}
value = start + value;
newContent.Append(value);
}
else
{
throw new ArgumentException(
string.Format("Path \"{0}\" misses a \"{1}\" parameter", Path, parameterName), Path);
}
}
if (op == ";")
{
if (newContent[newContent.Length - 1] == '=')
{
newContent = newContent.Remove(newContent.Length - 1, 1);
}
newContent = newContent.Replace("=;", ";");
}
restPath = restPath.Replace(matchStr, newContent.ToString());
}
return restPath;
}
/// <summary>Adds a parameter value.</summary>
/// <param name="type">Type of the parameter (must be 'Path' or 'Query').</param>
/// <param name="name">Parameter name.</param>
/// <param name="value">Parameter value.</param>
public void AddParameter(RequestParameterType type, string name, string value)
{
name.ThrowIfNull("name");
if (value == null)
{
Logger.Warning("Add parameter should not get null values. type={0}, name={1}", type, name);
return;
}
switch (type)
{
case RequestParameterType.Path:
if (!PathParameters.ContainsKey(name))
{
PathParameters[name] = new List<string> { value };
}
else
{
PathParameters[name].Add(value);
}
break;
case RequestParameterType.Query:
QueryParameters.Add(new KeyValuePair<string, string>(name, value));
break;
default:
throw new ArgumentOutOfRangeException("type");
}
}
/// <summary>Creates a new HTTP request message.</summary>
public HttpRequestMessage CreateRequest()
{
return new HttpRequestMessage(new HttpMethod(Method), BuildUri());
}
}
}

View file

@ -0,0 +1,82 @@
/*
Copyright 2011 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Collections.Generic;
using System.Text;
using Google.Apis.Util;
namespace Google.Apis.Requests
{
/// <summary>
/// Collection of server errors
/// </summary>
public class RequestError
{
/// <summary>
/// Enumeration of known error codes which may occur during a request.
/// </summary>
public enum ErrorCodes
{
/// <summary>
/// The ETag condition specified caused the ETag verification to fail.
/// Depending on the ETagAction of the request this either means that a change to the object has been
/// made on the server, or that the object in question is still the same and has not been changed.
/// </summary>
ETagConditionFailed = 412
}
/// <summary>
/// Contains a list of all errors
/// </summary>
public IList<SingleError> Errors { get; set; }
/// <summary>
/// The error code returned
/// </summary>
public int Code { get; set; }
/// <summary>
/// The error message returned
/// </summary>
public string Message { get; set; }
/// <summary>
/// Returns a string summary of this error
/// </summary>
/// <returns>A string summary of this error</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(GetType().FullName).Append(Message).AppendFormat(" [{0}]", Code).AppendLine();
if (Errors.IsNullOrEmpty())
{
sb.AppendLine("No individual errors");
}
else
{
sb.AppendLine("Errors [");
foreach (SingleError err in Errors)
{
sb.Append('\t').AppendLine(err.ToString());
}
sb.AppendLine("]");
}
return sb.ToString();
}
}
}

View file

@ -0,0 +1,60 @@
/*
Copyright 2011 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace Google.Apis.Requests
{
/// <summary>
/// A single server error
/// </summary>
public class SingleError
{
/// <summary>
/// The domain in which the error occured
/// </summary>
public string Domain { get; set; }
/// <summary>
/// The reason the error was thrown
/// </summary>
public string Reason { get; set; }
/// <summary>
/// The error message
/// </summary>
public string Message { get; set; }
/// <summary>
/// Type of the location
/// </summary>
public string LocationType { get; set; }
/// <summary>
/// Location where the error was thrown
/// </summary>
public string Location { get; set; }
/// <summary>
/// Returns a string summary of this error
/// </summary>
/// <returns>A string summary of this error</returns>
public override string ToString()
{
return string.Format(
"Message[{0}] Location[{1} - {2}] Reason[{3}] Domain[{4}]", Message, Location, LocationType, Reason,
Domain);
}
}
}