Java Code Examples for com.google.api.client.util.Data#isNull()

The following examples show how to use com.google.api.client.util.Data#isNull() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
Source File: HttpHeaders.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private static void addHeader(
    Logger logger,
    StringBuilder logbuf,
    StringBuilder curlbuf,
    LowLevelHttpRequest lowLevelHttpRequest,
    String name,
    Object value,
    Writer writer)
    throws IOException {
  // ignore nulls
  if (value == null || Data.isNull(value)) {
    return;
  }
  // compute value
  String stringValue = toStringValue(value);
  // log header
  String loggedStringValue = stringValue;
  if (("Authorization".equalsIgnoreCase(name) || "Cookie".equalsIgnoreCase(name))
      && (logger == null || !logger.isLoggable(Level.ALL))) {
    loggedStringValue = "<Not Logged>";
  }
  if (logbuf != null) {
    logbuf.append(name).append(": ");
    logbuf.append(loggedStringValue);
    logbuf.append(StringUtils.LINE_SEPARATOR);
  }
  if (curlbuf != null) {
    curlbuf.append(" -H '").append(name).append(": ").append(loggedStringValue).append("'");
  }
  // add header to lowLevelHttpRequest
  if (lowLevelHttpRequest != null) {
    lowLevelHttpRequest.addHeader(name, stringValue);
  }
  // add header to the writer
  if (writer != null) {
    writer.write(name);
    writer.write(": ");
    writer.write(stringValue);
    writer.write("\r\n");
  }
}