com.google.api.client.util.Data Java Examples

The following examples show how to use com.google.api.client.util.Data. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XmlNamespaceDictionary.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private void computeAliases(Object element, SortedSet<String> aliases) {
  for (Map.Entry<String, Object> entry : Data.mapOf(element).entrySet()) {
    Object value = entry.getValue();
    if (value != null) {
      String name = entry.getKey();
      if (!Xml.TEXT_CONTENT.equals(name)) {
        int colon = name.indexOf(':');
        boolean isAttribute = name.charAt(0) == '@';
        if (colon != -1 || !isAttribute) {
          String alias = colon == -1 ? "" : name.substring(name.charAt(0) == '@' ? 1 : 0, colon);
          aliases.add(alias);
        }
        Class<?> valueClass = value.getClass();
        if (!isAttribute && !Data.isPrimitive(valueClass) && !valueClass.isEnum()) {
          if (value instanceof Iterable<?> || valueClass.isArray()) {
            for (Object subValue : Types.iterableOf(value)) {
              computeAliases(subValue, aliases);
            }
          } else {
            computeAliases(value, aliases);
          }
        }
      }
    }
  }
}
 
Example #2
Source File: UrlEncodedContent.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void writeTo(OutputStream out) throws IOException {
  Writer writer = new BufferedWriter(new OutputStreamWriter(out, getCharset()));
  boolean first = true;
  for (Map.Entry<String, Object> nameValueEntry : Data.mapOf(data).entrySet()) {
    Object value = nameValueEntry.getValue();
    if (value != null) {
      String name = CharEscapers.escapeUri(nameValueEntry.getKey());
      Class<? extends Object> valueClass = value.getClass();
      if (value instanceof Iterable<?> || valueClass.isArray()) {
        for (Object repeatedValue : Types.iterableOf(value)) {
          first = appendParam(first, writer, name, repeatedValue);
        }
      } else {
        first = appendParam(first, writer, name, value);
      }
    }
  }
  writer.flush();
}
 
Example #3
Source File: UrlEncodedContent.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private static boolean appendParam(boolean first, Writer writer, String name, Object value)
    throws IOException {
  // ignore nulls
  if (value == null || Data.isNull(value)) {
    return first;
  }
  // append value
  if (first) {
    first = false;
  } else {
    writer.write("&");
  }
  writer.write(name);
  String stringValue =
      CharEscapers.escapeUri(
          value instanceof Enum<?> ? FieldInfo.of((Enum<?>) value).getName() : value.toString());
  if (stringValue.length() != 0) {
    writer.write("=");
    writer.write(stringValue);
  }
  return first;
}
 
Example #4
Source File: Xml.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private static Object parseValue(Type valueType, List<Type> context, String value) {
  valueType = Data.resolveWildcardTypeOrTypeVariable(context, valueType);
  if (valueType == Double.class || valueType == double.class) {
    if (value.equals("INF")) {
      return new Double(Double.POSITIVE_INFINITY);
    }
    if (value.equals("-INF")) {
      return new Double(Double.NEGATIVE_INFINITY);
    }
  }
  if (valueType == Float.class || valueType == float.class) {
    if (value.equals("INF")) {
      return Float.POSITIVE_INFINITY;
    }
    if (value.equals("-INF")) {
      return Float.NEGATIVE_INFINITY;
    }
  }
  return Data.parsePrimitiveValue(valueType, value);
}
 
Example #5
Source File: XmlNamespaceDictionary.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
ElementSerializer(Object elementValue, boolean errorOnUnknown) {
  this.errorOnUnknown = errorOnUnknown;
  Class<?> valueClass = elementValue.getClass();
  if (Data.isPrimitive(valueClass) && !Data.isNull(elementValue)) {
    textValue = elementValue;
  } else if (valueClass.isEnum() && !Data.isNull(elementValue)) {
    textValue = elementValue;
  } else {
    for (Map.Entry<String, Object> entry : Data.mapOf(elementValue).entrySet()) {
      Object fieldValue = entry.getValue();
      if (fieldValue != null && !Data.isNull(fieldValue)) {
        String fieldName = entry.getKey();
        if (Xml.TEXT_CONTENT.equals(fieldName)) {
          textValue = fieldValue;
        } else if (fieldName.charAt(0) == '@') {
          attributeNames.add(fieldName.substring(1));
          attributeValues.add(fieldValue);
        } else {
          subElementNames.add(fieldName);
          subElementValues.add(fieldValue);
        }
      }
    }
  }
}
 
Example #6
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParser_nullValue() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(NULL_VALUE);
  parser.nextToken();
  StringNullValue result = parser.parse(StringNullValue.class);
  // serialize
  assertEquals(NULL_VALUE, factory.toString(result));
  // check parsed result
  assertEquals(Data.NULL_STRING, result.value);
  String[] arr = result.arr;
  assertEquals(1, arr.length);
  assertEquals(Data.nullOf(String.class), arr[0]);
  String[][] arr2 = result.arr2;
  assertEquals(2, arr2.length);
  assertEquals(Data.nullOf(String[].class), arr2[0]);
  String[] subArr2 = arr2[1];
  assertEquals(1, subArr2.length);
  assertEquals(Data.NULL_STRING, subArr2[0]);
}
 
Example #7
Source File: Structs.java    From beam with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Map<String, Object> getDictionary(
    Map<String, Object> map, String name, @Nullable Map<String, Object> defaultValue) {
  @Nullable Object value = map.get(name);
  if (value == null) {
    if (map.containsKey(name)) {
      throw new IncorrectTypeException(name, map, "a dictionary");
    }
    return defaultValue;
  }
  if (Data.isNull(value)) {
    // This is a JSON literal null.  When represented as a dictionary, this is
    // an empty map.
    return Collections.emptyMap();
  }
  if (!(value instanceof Map)) {
    throw new IncorrectTypeException(name, map, "a dictionary");
  }
  @SuppressWarnings("unchecked")
  Map<String, Object> result = (Map<String, Object>) value;
  return result;
}
 
Example #8
Source File: Structs.java    From beam with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> getDictionary(Map<String, Object> map, String name) {
  @Nullable Object value = map.get(name);
  if (value == null) {
    throw new ParameterNotFoundException(name, map);
  }
  if (Data.isNull(value)) {
    // This is a JSON literal null.  When represented as a dictionary, this is
    // an empty map.
    return Collections.emptyMap();
  }
  if (!(value instanceof Map)) {
    throw new IncorrectTypeException(name, map, "a dictionary");
  }
  @SuppressWarnings("unchecked")
  Map<String, Object> result = (Map<String, Object>) value;
  return result;
}
 
Example #9
Source File: Structs.java    From beam with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> checkObject(
    Object value, Map<String, Object> map, String name) {
  if (Data.isNull(value)) {
    // This is a JSON literal null.  When represented as an object, this is an
    // empty map.
    return Collections.emptyMap();
  }
  if (!(value instanceof Map)) {
    throw new IncorrectTypeException(name, map, "an object (not a map)");
  }
  @SuppressWarnings("unchecked")
  Map<String, Object> mapValue = (Map<String, Object>) value;
  if (!mapValue.containsKey(PropertyNames.OBJECT_TYPE_NAME)) {
    throw new IncorrectTypeException(
        name, map, "an object (no \"" + PropertyNames.OBJECT_TYPE_NAME + "\" field)");
  }
  return mapValue;
}
 
Example #10
Source File: ReportServiceLogger.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) {
  StringBuilder messageBuilder = new StringBuilder();
  if (headers != null) {
    appendMapAsString(messageBuilder, headers);
  }
  if (content != null) {
    messageBuilder.append(String.format("%nContent:%n"));
    if (content instanceof UrlEncodedContent) {
      UrlEncodedContent encodedContent = (UrlEncodedContent) content;
      appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData()));
    } else if (content != null) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      try {
        content.writeTo(byteStream);
        messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name()));
      } catch (IOException e) {
        messageBuilder.append("Unable to read request content due to exception: " + e);
      }
    }
  }
  return messageBuilder.toString();
}
 
Example #11
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_null() throws Exception {
  JsonFactory factory = newFactory();
  String result = factory.createJsonParser(NULL_TOP_VALUE).parse(String.class);
  assertEquals(NULL_TOP_VALUE, factory.toString(result));
  // check types and values
  assertTrue(Data.isNull(result));
}
 
Example #12
Source File: BigQueryHelpersTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testCoder_nullCell() throws CoderException {
  TableRow row = new TableRow();
  row.set("temperature", Data.nullOf(Object.class));
  row.set("max_temperature", Data.nullOf(Object.class));

  byte[] bytes = CoderUtils.encodeToByteArray(TableRowJsonCoder.of(), row);

  TableRow newRow = CoderUtils.decodeFromByteArray(TableRowJsonCoder.of(), bytes);
  byte[] newBytes = CoderUtils.encodeToByteArray(TableRowJsonCoder.of(), newRow);

  Assert.assertArrayEquals(bytes, newBytes);
}
 
Example #13
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParse_boolean() throws Exception {
  JsonFactory factory = newFactory();
  BooleanTypes parsed;
  // empty
  parsed = factory.fromString(BOOLEAN_TYPE_EMPTY, BooleanTypes.class);
  assertFalse(parsed.bool);
  assertNull(parsed.boolObj);
  assertEquals(BOOLEAN_TYPE_EMPTY_OUTPUT, factory.toString(parsed));
  // true
  parsed = factory.fromString(BOOLEAN_TYPE_TRUE, BooleanTypes.class);
  assertTrue(parsed.bool);
  assertTrue(parsed.boolObj.booleanValue() && !Data.isNull(parsed.boolObj));
  assertEquals(BOOLEAN_TYPE_TRUE, factory.toString(parsed));
  // false
  parsed = factory.fromString(BOOLEAN_TYPE_FALSE, BooleanTypes.class);
  assertFalse(parsed.bool);
  assertTrue(!parsed.boolObj.booleanValue() && !Data.isNull(parsed.boolObj));
  assertEquals(BOOLEAN_TYPE_FALSE, factory.toString(parsed));
  // null
  parsed = factory.fromString(BOOLEAN_TYPE_NULL, BooleanTypes.class);
  assertFalse(parsed.bool);
  assertTrue(Data.isNull(parsed.boolObj));
  assertEquals(BOOLEAN_TYPE_NULL_OUTPUT, factory.toString(parsed));
  // wrong
  try {
    factory.fromString(BOOLEAN_TYPE_WRONG, BooleanTypes.class);
    fail("expected " + IllegalArgumentException.class);
  } catch (IllegalArgumentException e) {
  }
}
 
Example #14
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testParser_treemapForTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  TreeMap<String, Object> result = parser.parse(TreeMap.class);
  // serialize
  assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  ArrayList<Object> arr = (ArrayList<Object>) result.get("arr");
  assertEquals(2, arr.size());
  assertEquals(Data.nullOf(Object.class), arr.get(0));
  ArrayList<BigDecimal> subArr = (ArrayList<BigDecimal>) arr.get(1);
  assertEquals(2, subArr.size());
  assertEquals(Data.nullOf(Object.class), subArr.get(0));
  BigDecimal arrValue = subArr.get(1);
  assertEquals(1, arrValue.intValue());
  // null value
  Object nullValue = result.get("nullValue");
  assertEquals(Data.nullOf(Object.class), nullValue);
  // value
  BigDecimal value = (BigDecimal) result.get("value");
  assertEquals(1, value.intValue());
}
 
Example #15
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_doubleListTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(DOUBLE_LIST_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  DoubleListTypeVariableType result = parser.parse(DoubleListTypeVariableType.class);
  // serialize
  assertEquals(DOUBLE_LIST_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  List<Double>[][] arr = result.arr;
  assertEquals(2, arr.length);
  assertEquals(Data.nullOf(List[].class), arr[0]);
  List<Double>[] subArr = arr[1];
  assertEquals(2, subArr.length);
  assertEquals(Data.nullOf(ArrayList.class), subArr[0]);
  List<Double> arrValue = subArr[1];
  assertEquals(1, arrValue.size());
  Double dValue = arrValue.get(0);
  assertEquals(1.0, dValue);
  // collection
  LinkedList<LinkedList<List<Double>>> list = result.list;
  assertEquals(2, list.size());
  assertEquals(Data.nullOf(LinkedList.class), list.get(0));
  LinkedList<List<Double>> subList = list.get(1);
  assertEquals(2, subList.size());
  assertEquals(Data.nullOf(ArrayList.class), subList.get(0));
  arrValue = subList.get(1);
  assertEquals(ImmutableList.of(Double.valueOf(1)), arrValue);
  // null value
  List<Double> nullValue = result.nullValue;
  assertEquals(Data.nullOf(ArrayList.class), nullValue);
  // value
  List<Double> value = result.value;
  assertEquals(ImmutableList.of(Double.valueOf(1)), value);
}
 
Example #16
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_intArrayTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(INT_ARRAY_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  IntArrayTypeVariableType result = parser.parse(IntArrayTypeVariableType.class);
  // serialize
  assertEquals(INT_ARRAY_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  int[][][] arr = result.arr;
  assertEquals(2, arr.length);
  assertEquals(Data.nullOf(int[][].class), arr[0]);
  int[][] subArr = arr[1];
  assertEquals(2, subArr.length);
  assertEquals(Data.nullOf(int[].class), subArr[0]);
  int[] arrValue = subArr[1];
  assertTrue(Arrays.equals(new int[] {1}, arrValue));
  // collection
  LinkedList<LinkedList<int[]>> list = result.list;
  assertEquals(2, list.size());
  assertEquals(Data.nullOf(LinkedList.class), list.get(0));
  LinkedList<int[]> subList = list.get(1);
  assertEquals(2, subList.size());
  assertEquals(Data.nullOf(int[].class), subList.get(0));
  arrValue = subList.get(1);
  assertTrue(Arrays.equals(new int[] {1}, arrValue));
  // null value
  int[] nullValue = result.nullValue;
  assertEquals(Data.nullOf(int[].class), nullValue);
  // value
  int[] value = result.value;
  assertTrue(Arrays.equals(new int[] {1}, value));
}
 
Example #17
Source File: AbstractJsonFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParser_integerTypeVariableType() throws Exception {
  // parse
  JsonFactory factory = newFactory();
  JsonParser parser;
  parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
  parser.nextToken();
  IntegerTypeVariableType result = parser.parse(IntegerTypeVariableType.class);
  // serialize
  assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
  // check parsed result
  // array
  Integer[][] arr = result.arr;
  assertEquals(2, arr.length);
  assertEquals(Data.nullOf(Integer[].class), arr[0]);
  Integer[] subArr = arr[1];
  assertEquals(2, subArr.length);
  assertEquals(Data.NULL_INTEGER, subArr[0]);
  Integer arrValue = subArr[1];
  assertEquals(1, arrValue.intValue());
  // collection
  LinkedList<LinkedList<Integer>> list = result.list;
  assertEquals(2, list.size());
  assertEquals(Data.nullOf(LinkedList.class), list.get(0));
  LinkedList<Integer> subList = list.get(1);
  assertEquals(2, subList.size());
  assertEquals(Data.NULL_INTEGER, subList.get(0));
  arrValue = subList.get(1);
  assertEquals(1, arrValue.intValue());
  // null value
  Integer nullValue = result.nullValue;
  assertEquals(Data.NULL_INTEGER, nullValue);
  // value
  Integer value = result.value;
  assertEquals(1, value.intValue());
}
 
Example #18
Source File: ClientParametersAuthentication.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void intercept(HttpRequest request) throws IOException {
  Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
  data.put("client_id", clientId);
  if (clientSecret != null) {
    data.put("client_secret", clientSecret);
  }
}
 
Example #19
Source File: BigqueryClient.java    From beam with Apache License 2.0 5 votes vote down vote up
@Nullable
private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) {
  if (Data.isNull(v)) {
    return null;
  }

  if (Objects.equals(fieldSchema.getMode(), "REPEATED")) {
    TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED");
    @SuppressWarnings("unchecked")
    List<Map<String, Object>> rawCells = (List<Map<String, Object>>) v;
    ImmutableList.Builder<Object> values = ImmutableList.builder();
    for (Map<String, Object> element : rawCells) {
      values.add(getTypedCellValue(elementSchema, element.get("v")));
    }
    return values.build();
  }

  if ("RECORD".equals(fieldSchema.getType())) {
    @SuppressWarnings("unchecked")
    Map<String, Object> typedV = (Map<String, Object>) v;
    return getTypedTableRow(fieldSchema.getFields(), typedV);
  }

  if ("FLOAT".equals(fieldSchema.getType())) {
    return Double.parseDouble((String) v);
  }

  if ("BOOLEAN".equals(fieldSchema.getType())) {
    return Boolean.parseBoolean((String) v);
  }

  if ("TIMESTAMP".equals(fieldSchema.getType())) {
    return (String) v;
  }

  // Returns the original value for:
  // 1. String, 2. base64 encoded BYTES, 3. DATE, DATETIME, TIME strings.
  return v;
}
 
Example #20
Source File: Structs.java    From beam with Apache License 2.0 5 votes vote down vote up
@Nullable
public static List<String> getStrings(
    Map<String, Object> map, String name, @Nullable List<String> defaultValue) {
  @Nullable Object value = map.get(name);
  if (value == null) {
    if (map.containsKey(name)) {
      throw new IncorrectTypeException(name, map, "a string or a list");
    }
    return defaultValue;
  }
  if (Data.isNull(value)) {
    // This is a JSON literal null.  When represented as a list of strings,
    // this is an empty list.
    return Collections.emptyList();
  }
  @Nullable String singletonString = decodeValue(value, String.class);
  if (singletonString != null) {
    return Collections.singletonList(singletonString);
  }
  if (!(value instanceof List)) {
    throw new IncorrectTypeException(name, map, "a string or a list");
  }
  @SuppressWarnings("unchecked")
  List<Object> elements = (List<Object>) value;
  List<String> result = new ArrayList<>(elements.size());
  for (Object o : elements) {
    @Nullable String s = decodeValue(o, String.class);
    if (s == null) {
      throw new IncorrectTypeException(name, map, "a list of strings");
    }
    result.add(s);
  }
  return result;
}
 
Example #21
Source File: JsonParser.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * {@link Beta} <br>
 * Parse a JSON Array from the given JSON parser into the given destination collection, optionally
 * using the given parser customizer.
 *
 * @param destinationCollectionClass class of destination collection (must have a public default
 *     constructor)
 * @param destinationItemClass class of destination collection item (must have a public default
 *     constructor)
 * @param customizeParser optional parser customizer or {@code null} for none
 */
@Beta
public final <T> Collection<T> parseArray(
    Class<?> destinationCollectionClass,
    Class<T> destinationItemClass,
    CustomizeJsonParser customizeParser)
    throws IOException {
  @SuppressWarnings("unchecked")
  Collection<T> destinationCollection =
      (Collection<T>) Data.newCollectionInstance(destinationCollectionClass);
  parseArray(destinationCollection, destinationItemClass, customizeParser);
  return destinationCollection;
}
 
Example #22
Source File: Structs.java    From beam with Apache License 2.0 5 votes vote down vote up
@Nullable
public static List<Map<String, Object>> getListOfMaps(
    Map<String, Object> map, String name, @Nullable List<Map<String, Object>> defaultValue) {
  @Nullable Object value = map.get(name);
  if (value == null) {
    if (map.containsKey(name)) {
      throw new IncorrectTypeException(name, map, "a list");
    }
    return defaultValue;
  }
  if (Data.isNull(value)) {
    // This is a JSON literal null.  When represented as a list,
    // this is an empty list.
    return Collections.emptyList();
  }

  if (!(value instanceof List)) {
    throw new IncorrectTypeException(name, map, "a list");
  }

  List<?> elements = (List<?>) value;
  for (Object elem : elements) {
    if (!(elem instanceof Map)) {
      throw new IncorrectTypeException(name, map, "a list of Map objects");
    }
  }

  @SuppressWarnings("unchecked")
  List<Map<String, Object>> result = (List<Map<String, Object>>) elements;
  return result;
}
 
Example #23
Source File: UriTemplate.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new {@code Map<String, Object>} from an {@code Object}.
 *
 * <p>There are no null values in the returned map.
 */
private static Map<String, Object> getMap(Object obj) {
  // Using a LinkedHashMap to maintain the original order of insertions. This is done to help
  // with handling unused parameters and makes testing easier as well.
  Map<String, Object> map = new LinkedHashMap<String, Object>();
  for (Map.Entry<String, Object> entry : Data.mapOf(obj).entrySet()) {
    Object value = entry.getValue();
    if (value != null && !Data.isNull(value)) {
      map.put(entry.getKey(), value);
    }
  }
  return map;
}
 
Example #24
Source File: MicrosoftParametersAuthentication.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void intercept(HttpRequest request) throws IOException {
  Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
  if (clientSecret != null) {
    data.put("client_assertion", clientSecret);
  }
  data.put("client_assertion_type", CLIENT_ASSERTION_TYPE);
  data.put("grant_type", GRANT_TYPE);
}
 
Example #25
Source File: XmlNamespaceDictionary.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
void serialize(XmlSerializer serializer, String elementNamespaceUri, String elementLocalName)
    throws IOException {
  boolean errorOnUnknown = this.errorOnUnknown;
  if (elementLocalName == null) {
    if (errorOnUnknown) {
      throw new IllegalArgumentException("XML name not specified");
    }
    elementLocalName = "unknownName";
  }
  serializer.startTag(elementNamespaceUri, elementLocalName);
  // attributes
  int num = attributeNames.size();
  for (int i = 0; i < num; i++) {
    String attributeName = attributeNames.get(i);
    int colon = attributeName.indexOf(':');
    String attributeLocalName = attributeName.substring(colon + 1);
    String attributeNamespaceUri =
        colon == -1
            ? null
            : getNamespaceUriForAliasHandlingUnknown(
                errorOnUnknown, attributeName.substring(0, colon));
    serializer.attribute(
        attributeNamespaceUri, attributeLocalName, toSerializedValue(attributeValues.get(i)));
  }
  // text
  if (textValue != null) {
    serializer.text(toSerializedValue(textValue));
  }
  // elements
  num = subElementNames.size();
  for (int i = 0; i < num; i++) {
    Object subElementValue = subElementValues.get(i);
    String subElementName = subElementNames.get(i);
    Class<? extends Object> valueClass = subElementValue.getClass();
    if (subElementValue instanceof Iterable<?> || valueClass.isArray()) {
      for (Object subElement : Types.iterableOf(subElementValue)) {
        if (subElement != null && !Data.isNull(subElement)) {
          new ElementSerializer(subElement, errorOnUnknown)
              .serialize(serializer, subElementName);
        }
      }
    } else {
      new ElementSerializer(subElementValue, errorOnUnknown)
          .serialize(serializer, subElementName);
    }
  }
  serializer.endTag(elementNamespaceUri, elementLocalName);
}
 
Example #26
Source File: LinkHeaderParser.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
private static Object parseValue(Type valueType, List<Type> context, String value) {
    Type resolved = Data.resolveWildcardTypeOrTypeVariable(context, valueType);
    return Data.parsePrimitiveValue(resolved, value);
}
 
Example #27
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new instance of an authorization code token request based on the given authorization
 * code.
 *
 * <p>
 * This is used to make a request for an access token using the authorization code. It uses
 * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()},
 * {@link #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}.
 * </p>
 *
 * <pre>
static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code)
    throws IOException, TokenResponseException {
  return flow.newTokenRequest(code).setRedirectUri("https://client.example.com/rd").execute();
}
 * </pre>
 *
 * @param authorizationCode authorization code.
 */
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
  HttpExecuteInterceptor pkceClientAuthenticationWrapper = new HttpExecuteInterceptor() {
    @Override
    public void intercept(HttpRequest request) throws IOException {
      clientAuthentication.intercept(request);
      if (pkce != null) {
        Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
        data.put("code_verifier", pkce.getVerifier());
      }
    }
  };

  return new AuthorizationCodeTokenRequest(transport, jsonFactory,
      new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
      pkceClientAuthenticationWrapper).setRequestInitializer(requestInitializer).setScopes(scopes);
}
 
Example #28
Source File: BearerToken.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
private static Map<String, Object> getData(HttpRequest request) {
  return Data.mapOf(UrlEncodedContent.getContent(request).getData());
}
 
Example #29
Source File: GoogleCloudStorageImpl.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
private static String encodeMetadataValues(byte[] bytes) {
  return bytes == null ? Data.NULL_STRING : BaseEncoding.base64().encode(bytes);
}
 
Example #30
Source File: Structs.java    From beam with Apache License 2.0 4 votes vote down vote up
public static void addNull(Map<String, Object> map, String name) {
  map.put(name, Data.nullOf(Object.class));
}