com.google.api.client.util.FieldInfo Java Examples
The following examples show how to use
com.google.api.client.util.FieldInfo.
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: BaseApiService.java From connector-sdk with Apache License 2.0 | 6 votes |
private static Object setDefaultValuesForPrimitiveTypes(Object object) { if (!(object instanceof GenericJson)) { return object; } GenericJson genericJson = (GenericJson) object; for (FieldInfo f : genericJson.getClassInfo().getFieldInfos()) { if (Boolean.class.equals(f.getType())) { f.setValue(genericJson, Optional.ofNullable(f.getValue(genericJson)).orElse(false)); } else if (Integer.class.equals(f.getType())) { f.setValue(genericJson, Optional.ofNullable(f.getValue(genericJson)).orElse(0)); } else if (GenericJson.class.isAssignableFrom(f.getType())) { setDefaultValuesForPrimitiveTypes(f.getValue(genericJson)); } else if (Collection.class.isAssignableFrom(f.getType())) { Object collection = f.getValue(genericJson); if (collection == null) { f.setValue(genericJson, Collections.emptyList()); } else { Collection<?> values = (Collection<?>) collection; for (Object v : values) { setDefaultValuesForPrimitiveTypes(v); } } } } return object; }
Example #2
Source File: Xml.java From google-http-java-client with Apache License 2.0 | 6 votes |
/** * Sets the value of a given field or map entry. * * @param value value * @param field field to set or {@code null} if not applicable * @param destination destination object or {@code null} for none * @param genericXml generic XML or {@code null} if not applicable * @param destinationMap destination map or {@code null} if not applicable * @param name key name */ private static void setValue( Object value, Field field, Object destination, GenericXml genericXml, Map<String, Object> destinationMap, String name) { if (field != null) { FieldInfo.setFieldValue(field, destination, value); } else if (genericXml != null) { genericXml.set(name, value); } else { destinationMap.put(name, value); } }
Example #3
Source File: UrlEncodedContent.java From google-http-java-client with Apache License 2.0 | 6 votes |
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: MultiKindFeedParser.java From google-api-java-client with Apache License 2.0 | 6 votes |
/** 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 #5
Source File: XmlNamespaceDictionary.java From google-http-java-client with Apache License 2.0 | 5 votes |
static String toSerializedValue(Object value) { if (value instanceof Float) { Float f = (Float) value; if (f.floatValue() == Float.POSITIVE_INFINITY) { return "INF"; } if (f.floatValue() == Float.NEGATIVE_INFINITY) { return "-INF"; } } if (value instanceof Double) { Double d = (Double) value; if (d.doubleValue() == Double.POSITIVE_INFINITY) { return "INF"; } if (d.doubleValue() == Double.NEGATIVE_INFINITY) { return "-INF"; } } if (value instanceof String || value instanceof Number || value instanceof Boolean) { return value.toString(); } if (value instanceof DateTime) { return ((DateTime) value).toStringRfc3339(); } if (value instanceof Enum<?>) { return FieldInfo.of((Enum<?>) value).getName(); } throw new IllegalArgumentException("unrecognized value type: " + value.getClass()); }
Example #6
Source File: HttpHeaders.java From google-http-java-client with Apache License 2.0 | 5 votes |
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 #7
Source File: JsonParser.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** * 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 #8
Source File: JsonParser.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** * Finds the {@link Field} on the given {@link Class} that has the {@link JsonPolymorphicTypeMap} * annotation, or {@code null} if there is none. * * <p>The class must contain exactly zero or one {@link JsonPolymorphicTypeMap} annotation. * * @param key The {@link Class} to search in, or {@code null} * @return The {@link Field} with the {@link JsonPolymorphicTypeMap} annotation, or {@code null} * either if there is none or if the key is {@code null} */ private static Field getCachedTypemapFieldFor(Class<?> key) { if (key == null) { return null; } lock.lock(); try { // Must use containsKey because we do store null values for when the class has no // JsonPolymorphicTypeMap field. if (cachedTypemapFields.containsKey(key)) { return cachedTypemapFields.get(key); } // Find the field that determines the type and cache it. Field value = null; Collection<FieldInfo> fieldInfos = ClassInfo.of(key).getFieldInfos(); for (FieldInfo fieldInfo : fieldInfos) { Field field = fieldInfo.getField(); JsonPolymorphicTypeMap typemapAnnotation = field.getAnnotation(JsonPolymorphicTypeMap.class); if (typemapAnnotation != null) { Preconditions.checkArgument( value == null, "Class contains more than one field with @JsonPolymorphicTypeMap annotation: %s", key); Preconditions.checkArgument( Data.isPrimitive(field.getType()), "Field which has the @JsonPolymorphicTypeMap, %s, is not a supported type: %s", key, field.getType()); value = field; // Check for duplicate typeDef keys TypeDef[] typeDefs = typemapAnnotation.typeDefinitions(); HashSet<String> typeDefKeys = Sets.newHashSet(); Preconditions.checkArgument( typeDefs.length > 0, "@JsonPolymorphicTypeMap must have at least one @TypeDef"); for (TypeDef typeDef : typeDefs) { Preconditions.checkArgument( typeDefKeys.add(typeDef.key()), "Class contains two @TypeDef annotations with identical key: %s", typeDef.key()); } } } cachedTypemapFields.put(key, value); return value; } finally { lock.unlock(); } }
Example #9
Source File: JsonGenerator.java From google-http-java-client with Apache License 2.0 | 4 votes |
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 #10
Source File: HttpHeaders.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** Returns the string header value for the given header value as an object. */ private static String toStringValue(Object headerValue) { return headerValue instanceof Enum<?> ? FieldInfo.of((Enum<?>) headerValue).getName() : headerValue.toString(); }
Example #11
Source File: HttpHeaders.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** 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 #12
Source File: GoogleAtom.java From google-api-java-client with Apache License 2.0 | 4 votes |
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 #13
Source File: GoogleHttpClientEdgeGridRequestSigner.java From AkamaiOPEN-edgegrid-java with Apache License 2.0 | 4 votes |
private static String toStringValue(Object headerValue) { return headerValue instanceof Enum<?> ? FieldInfo.of((Enum<?>) headerValue).getName() : headerValue.toString(); }