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

The following examples show how to use com.google.api.client.util.Types. 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: GoogleHttpClientEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Request map(HttpRequest request) {
    Request.RequestBuilder builder = Request.builder()
            .method(request.getRequestMethod())
            .uri(request.getUrl().toURI())
            .body(serializeContent(request));
    for (Map.Entry<String, Object> entry : request.getHeaders().entrySet()) {
        Object value = entry.getValue();
        if (value instanceof Iterable<?> || value.getClass().isArray()) {
            for (Object repeatedValue : Types.iterableOf(value)) {
                // NOTE: Request is about to throw an exception!
                builder.header(entry.getKey(), toStringValue(repeatedValue));
            }
        } else {
            builder.header(entry.getKey(), toStringValue(value));
        }
    }
    return builder.build();
}
 
Example #2
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 #3
Source File: MultiKindFeedParser.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/** Sets the entry classes to use when parsing. */
public void setEntryClasses(Class<?>... entryClasses) {
  int numEntries = entryClasses.length;
  HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap;
  for (int i = 0; i < numEntries; i++) {
    Class<?> entryClass = entryClasses[i];
    ClassInfo typeInfo = ClassInfo.of(entryClass);
    Field field = typeInfo.getField("@gd:kind");
    if (field == null) {
      throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName());
    }
    Object entry = Types.newInstance(entryClass);
    String kind = (String) FieldInfo.getFieldValue(field, entry);
    if (kind == null) {
      throw new IllegalArgumentException(
          "missing value for @gd:kind field in " + entryClass.getName());
    }
    kindToEntryClassMap.put(kind, entryClass);
  }
}
 
Example #4
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 #5
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an unmodifiable list of the header string values for the given header name.
 *
 * @param name header name (may be any case)
 * @return header string values or empty if not found
 * @since 1.13
 */
public List<String> getHeaderStringValues(String name) {
  Object value = get(name.toLowerCase(Locale.US));
  if (value == null) {
    return Collections.emptyList();
  }
  Class<? extends Object> valueClass = value.getClass();
  if (value instanceof Iterable<?> || valueClass.isArray()) {
    List<String> values = new ArrayList<String>();
    for (Object repeatedValue : Types.iterableOf(value)) {
      values.add(toStringValue(repeatedValue));
    }
    return Collections.unmodifiableList(values);
  }
  return Collections.singletonList(toStringValue(value));
}
 
Example #6
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first header string value for the given header name.
 *
 * @param name header name (may be any case)
 * @return first header string value or {@code null} if not found
 * @since 1.13
 */
public String getFirstHeaderStringValue(String name) {
  Object value = get(name.toLowerCase(Locale.US));
  if (value == null) {
    return null;
  }
  Class<? extends Object> valueClass = value.getClass();
  if (value instanceof Iterable<?> || valueClass.isArray()) {
    for (Object repeatedValue : Types.iterableOf(value)) {
      return toStringValue(repeatedValue);
    }
  }
  return toStringValue(value);
}
 
Example #7
Source File: LinkHeaderParser.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public Object parseAndClose(Reader reader, Type dataType) throws IOException {
    Preconditions.checkArgument(
            dataType instanceof Class<?>, "dataType has to be of type Class<?>");

    Object newInstance = Types.newInstance((Class<?>) dataType);
    parse(new BufferedReader(reader), newInstance);
    return newInstance;
}
 
Example #8
Source File: MultiKindFeedParser.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected Object parseEntryInternal() throws IOException, XmlPullParserException {
  XmlPullParser parser = getParser();
  String kind = parser.getAttributeValue(GoogleAtom.GD_NAMESPACE, "kind");
  Class<?> entryClass = this.kindToEntryClassMap.get(kind);
  if (entryClass == null) {
    throw new IllegalArgumentException("unrecognized kind: " + kind);
  }
  Object result = Types.newInstance(entryClass);
  Xml.parseElement(parser, result, getNamespaceDictionary(), null);
  return result;
}
 
Example #9
Source File: UrlEncodedParser.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public Object parseAndClose(Reader reader, Type dataType) throws IOException {
  Preconditions.checkArgument(
      dataType instanceof Class<?>, "dataType has to be of type Class<?>");

  Object newInstance = Types.newInstance((Class<?>) dataType);
  parse(new BufferedReader(reader), newInstance);
  return newInstance;
}
 
Example #10
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
static void serializeHeaders(
    HttpHeaders headers,
    StringBuilder logbuf,
    StringBuilder curlbuf,
    Logger logger,
    LowLevelHttpRequest lowLevelHttpRequest,
    Writer writer)
    throws IOException {
  HashSet<String> headerNames = new HashSet<String>();
  for (Map.Entry<String, Object> headerEntry : headers.entrySet()) {
    String name = headerEntry.getKey();
    Preconditions.checkArgument(
        headerNames.add(name),
        "multiple headers of the same name (headers are case insensitive): %s",
        name);
    Object value = headerEntry.getValue();
    if (value != null) {
      // compute the display name from the declared field name to fix capitalization
      String displayName = name;
      FieldInfo fieldInfo = headers.getClassInfo().getFieldInfo(name);
      if (fieldInfo != null) {
        displayName = fieldInfo.getName();
      }
      Class<? extends Object> valueClass = value.getClass();
      if (value instanceof Iterable<?> || valueClass.isArray()) {
        for (Object repeatedValue : Types.iterableOf(value)) {
          addHeader(
              logger, logbuf, curlbuf, lowLevelHttpRequest, displayName, repeatedValue, writer);
        }
      } else {
        addHeader(logger, logbuf, curlbuf, lowLevelHttpRequest, displayName, value, writer);
      }
    }
  }
  if (writer != null) {
    writer.flush();
  }
}
 
Example #11
Source File: AbstractAtomFeedParser.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the feed and return a new parsed instance of the feed type. This method can be skipped if
 * all you want are the items.
 *
 * @throws IOException I/O exception
 * @throws XmlPullParserException XML pull parser exception
 */
public T parseFeed() throws IOException, XmlPullParserException {
  boolean close = true;
  try {
    this.feedParsed = true;
    T result = Types.newInstance(feedClass);
    Xml.parseElement(parser, result, namespaceDictionary, Atom.StopAtAtomEntry.INSTANCE);
    close = false;
    return result;
  } finally {
    if (close) {
      close();
    }
  }
}
 
Example #12
Source File: XmlObjectParser.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private Object readObject(XmlPullParser parser, Type dataType)
    throws XmlPullParserException, IOException {
  Preconditions.checkArgument(dataType instanceof Class<?>, "dataType has to be of Class<?>");
  Object result = Types.newInstance((Class<?>) dataType);
  Xml.parseElement(parser, result, namespaceDictionary, null);
  return result;
}
 
Example #13
Source File: AtomFeedParser.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected Object parseEntryInternal() throws IOException, XmlPullParserException {
  E result = Types.newInstance(entryClass);
  Xml.parseElement(getParser(), result, getNamespaceDictionary(), null);
  return result;
}
 
Example #14
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/** Parses the specified case-insensitive header pair into this HttpHeaders instance. */
void parseHeader(String headerName, String headerValue, ParseHeaderState state) {
  List<Type> context = state.context;
  ClassInfo classInfo = state.classInfo;
  ArrayValueMap arrayValueMap = state.arrayValueMap;
  StringBuilder logger = state.logger;

  if (logger != null) {
    logger.append(headerName + ": " + headerValue).append(StringUtils.LINE_SEPARATOR);
  }
  // use field information if available
  FieldInfo fieldInfo = classInfo.getFieldInfo(headerName);
  if (fieldInfo != null) {
    Type type = Data.resolveWildcardTypeOrTypeVariable(context, fieldInfo.getGenericType());
    // type is now class, parameterized type, or generic array type
    if (Types.isArray(type)) {
      // array that can handle repeating values
      Class<?> rawArrayComponentType =
          Types.getRawArrayComponentType(context, Types.getArrayComponentType(type));
      arrayValueMap.put(
          fieldInfo.getField(),
          rawArrayComponentType,
          parseValue(rawArrayComponentType, context, headerValue));
    } else if (Types.isAssignableToOrFrom(
        Types.getRawArrayComponentType(context, type), Iterable.class)) {
      // iterable that can handle repeating values
      @SuppressWarnings("unchecked")
      Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(this);
      if (collection == null) {
        collection = Data.newCollectionInstance(type);
        fieldInfo.setValue(this, collection);
      }
      Type subFieldType = type == Object.class ? null : Types.getIterableParameter(type);
      collection.add(parseValue(subFieldType, context, headerValue));
    } else {
      // parse value based on field type
      fieldInfo.setValue(this, parseValue(type, context, headerValue));
    }
  } else {
    // store header values in an array list
    @SuppressWarnings("unchecked")
    ArrayList<String> listValue = (ArrayList<String>) this.get(headerName);
    if (listValue == null) {
      listValue = new ArrayList<String>();
      this.set(headerName, listValue);
    }
    listValue.add(headerValue);
  }
}
 
Example #15
Source File: JsonGenerator.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private void serialize(boolean isJsonString, Object value) throws IOException {
  if (value == null) {
    return;
  }
  Class<?> valueClass = value.getClass();
  if (Data.isNull(value)) {
    writeNull();
  } else if (value instanceof String) {
    writeString((String) value);
  } else if (value instanceof Number) {
    if (isJsonString) {
      writeString(value.toString());
    } else if (value instanceof BigDecimal) {
      writeNumber((BigDecimal) value);
    } else if (value instanceof BigInteger) {
      writeNumber((BigInteger) value);
    } else if (value instanceof Long) {
      writeNumber((Long) value);
    } else if (value instanceof Float) {
      float floatValue = ((Number) value).floatValue();
      Preconditions.checkArgument(!Float.isInfinite(floatValue) && !Float.isNaN(floatValue));
      writeNumber(floatValue);
    } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
      writeNumber(((Number) value).intValue());
    } else {
      double doubleValue = ((Number) value).doubleValue();
      Preconditions.checkArgument(!Double.isInfinite(doubleValue) && !Double.isNaN(doubleValue));
      writeNumber(doubleValue);
    }
  } else if (value instanceof Boolean) {
    writeBoolean((Boolean) value);
  } else if (value instanceof DateTime) {
    writeString(((DateTime) value).toStringRfc3339());
  } else if ((value instanceof Iterable<?> || valueClass.isArray())
      && !(value instanceof Map<?, ?>)
      && !(value instanceof GenericData)) {
    writeStartArray();
    for (Object o : Types.iterableOf(value)) {
      serialize(isJsonString, o);
    }
    writeEndArray();
  } else if (valueClass.isEnum()) {
    String name = FieldInfo.of((Enum<?>) value).getName();
    if (name == null) {
      writeNull();
    } else {
      writeString(name);
    }
  } else {
    writeStartObject();
    // only inspect fields of POJO (possibly extends GenericData) but not generic Map
    boolean isMapNotGenericData = value instanceof Map<?, ?> && !(value instanceof GenericData);
    ClassInfo classInfo = isMapNotGenericData ? null : ClassInfo.of(valueClass);
    for (Map.Entry<String, Object> entry : Data.mapOf(value).entrySet()) {
      Object fieldValue = entry.getValue();
      if (fieldValue != null) {
        String fieldName = entry.getKey();
        boolean isJsonStringForField;
        if (isMapNotGenericData) {
          isJsonStringForField = isJsonString;
        } else {
          Field field = classInfo.getField(fieldName);
          isJsonStringForField = field != null && field.getAnnotation(JsonString.class) != null;
        }
        writeFieldName(fieldName);
        serialize(isJsonStringForField, fieldValue);
      }
    }
    writeEndObject();
  }
}
 
Example #16
Source File: GoogleAtom.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
private static void appendFieldsFor(
    StringBuilder fieldsBuf, Class<?> dataClass, int[] numFields) {
  if (Map.class.isAssignableFrom(dataClass) || Collection.class.isAssignableFrom(dataClass)) {
    throw new IllegalArgumentException(
        "cannot specify field mask for a Map or Collection class: " + dataClass);
  }
  ClassInfo classInfo = ClassInfo.of(dataClass);
  for (String name : new TreeSet<String>(classInfo.getNames())) {
    FieldInfo fieldInfo = classInfo.getFieldInfo(name);
    if (fieldInfo.isFinal()) {
      continue;
    }
    if (++numFields[0] != 1) {
      fieldsBuf.append(',');
    }
    fieldsBuf.append(name);
    // TODO(yanivi): handle Java arrays?
    Class<?> fieldClass = fieldInfo.getType();
    if (Collection.class.isAssignableFrom(fieldClass)) {
      // TODO(yanivi): handle Java collection of Java collection or Java map?
      fieldClass = (Class<?>) Types.getIterableParameter(fieldInfo.getField().getGenericType());
    }
    // TODO(yanivi): implement support for map when server implements support for *:*
    if (fieldClass != null) {
      if (fieldInfo.isPrimitive()) {
        if (name.charAt(0) != '@' && !name.equals("text()")) {
          // TODO(yanivi): wait for bug fix from server to support text() -- already fixed???
          // buf.append("/text()");
        }
      } else if (!Collection.class.isAssignableFrom(fieldClass)
          && !Map.class.isAssignableFrom(fieldClass)) {
        int[] subNumFields = new int[1];
        int openParenIndex = fieldsBuf.length();
        fieldsBuf.append('(');
        // TODO(yanivi): abort if found cycle to avoid infinite loop
        appendFieldsFor(fieldsBuf, fieldClass, subNumFields);
        updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, subNumFields[0]);
      }
    }
  }
}
 
Example #17
Source File: JsonParser.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the next field from the given JSON parser into the given destination object.
 *
 * @param context destination context stack (possibly empty)
 * @param destination destination object instance or {@code null} for none (for example empty
 *     context stack)
 * @param customizeParser optional parser customizer or {@code null} for none
 */
private void parse(
    ArrayList<Type> context, Object destination, CustomizeJsonParser customizeParser)
    throws IOException {
  if (destination instanceof GenericJson) {
    ((GenericJson) destination).setFactory(getFactory());
  }
  JsonToken curToken = startParsingObjectOrArray();
  Class<?> destinationClass = destination.getClass();
  ClassInfo classInfo = ClassInfo.of(destinationClass);
  boolean isGenericData = GenericData.class.isAssignableFrom(destinationClass);
  if (!isGenericData && Map.class.isAssignableFrom(destinationClass)) {
    // The destination class is not a sub-class of GenericData but is of Map, so parse data
    // using parseMap.
    @SuppressWarnings("unchecked")
    Map<String, Object> destinationMap = (Map<String, Object>) destination;
    parseMap(
        null,
        destinationMap,
        Types.getMapValueParameter(destinationClass),
        context,
        customizeParser);
    return;
  }
  while (curToken == JsonToken.FIELD_NAME) {
    String key = getText();
    nextToken();
    // stop at items for feeds
    if (customizeParser != null && customizeParser.stopAt(destination, key)) {
      return;
    }
    // get the field from the type information
    FieldInfo fieldInfo = classInfo.getFieldInfo(key);
    if (fieldInfo != null) {
      // skip final fields
      if (fieldInfo.isFinal() && !fieldInfo.isPrimitive()) {
        throw new IllegalArgumentException("final array/object fields are not supported");
      }
      Field field = fieldInfo.getField();
      int contextSize = context.size();
      context.add(field.getGenericType());
      Object fieldValue =
          parseValue(
              field, fieldInfo.getGenericType(), context, destination, customizeParser, true);
      context.remove(contextSize);
      fieldInfo.setValue(destination, fieldValue);
    } else if (isGenericData) {
      // store unknown field in generic JSON
      GenericData object = (GenericData) destination;
      object.set(key, parseValue(null, null, context, destination, customizeParser, true));
    } else {
      // unrecognized field, skip value.
      if (customizeParser != null) {
        customizeParser.handleUnrecognizedKey(destination, key);
      }
      skipChildren();
    }
    curToken = nextToken();
  }
}
 
Example #18
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);
}