Search in sources :

Example 6 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project fdroidclient by f-droid.

the class App method setLocalized.

/**
 * Parses the {@code localized} block in the incoming index metadata,
 * choosing the best match in terms of locale/language while filling as
 * many fields as possible.  It first sets up a locale list based on user
 * preference and the locales available for this app, then picks the texts
 * based on that list.  One thing that makes this tricky is that any given
 * locale block in the index might not have all the fields.  So when filling
 * out each value, it needs to go through the whole preference list each time,
 * rather than just taking the whole block for a specific locale.  This is to
 * ensure that there is something to show, as often as possible.
 * <p>
 * It is still possible that the fields will be loaded directly by Jackson
 * without any locale info.  This comes from the old-style, inline app metadata
 * fields that do not have locale info.  They should not be used if the
 * {@code localized} block is included in the index.  Also, null strings in
 * the {@code localized} block should not overwrite Name/Summary/Description
 * strings with empty/null if they were set directly by Jackson.
 * <p>
 * Choosing the locale to use follows two sets of rules, one for Android versions
 * older than {@code android-24} and the other for {@code android-24} or newer.
 * The system-wide language preference list was added in {@code android-24}.
 * <ul>
 * <li>{@code >= android-24}<ol>
 * <li>the country variant {@code de-AT} from the user locale list
 * <li>only the language {@code de} from the above locale
 * <li>{@code en-US} since its the most common English for software
 * <li>the first available {@code en} locale
 * </ol></li>
 * <li>{@code < android-24}<ol>
 * <li>the country variant from the user locale: {@code de-AT}
 * <li>only the language from the above locale:  {@code de}
 * <li>all available locales with the same language:  {@code de-BE}
 * <li>{@code en-US} since its the most common English for software
 * <li>all available {@code en} locales
 * </ol></li>
 * </ul>
 * On {@code >= android-24}, it is by design that this does not fallback to other
 * country-specific locales, e.g. {@code fr-CH} does not fall back on {@code fr-FR}.
 * If someone wants to fallback to {@code fr-FR}, they can add it to the system
 * language list.  There are many cases where it is inappropriate to fallback to a
 * different country-specific locale, for example {@code de-DE --> de-CH} or
 * {@code zh-CN --> zh-TW}.
 * <p>
 * On {@code < android-24}, the user can only set a single
 * locale with a country as an option, so here it makes sense to try to fallback
 * on other country-specific locales, rather than English.
 */
@JsonProperty("localized")
private void setLocalized(Map<String, Map<String, Object>> localized) {
    // NOPMD
    Locale defaultLocale = Locale.getDefault();
    String languageTag = defaultLocale.getLanguage();
    String countryTag = defaultLocale.getCountry();
    String localeTag;
    if (TextUtils.isEmpty(countryTag)) {
        localeTag = languageTag;
    } else {
        localeTag = languageTag + "-" + countryTag;
    }
    Set<String> availableLocales = localized.keySet();
    Set<String> localesToUse = new LinkedHashSet<>();
    if (availableLocales.contains(localeTag)) {
        localesToUse.add(localeTag);
    }
    if (availableLocales.contains(languageTag)) {
        localesToUse.add(languageTag);
    }
    if (Build.VERSION.SDK_INT >= 24) {
        LocaleList localeList = Resources.getSystem().getConfiguration().getLocales();
        String[] sortedLocaleList = localeList.toLanguageTags().split(",");
        Arrays.sort(sortedLocaleList, new java.util.Comparator<String>() {

            @Override
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });
        for (String toUse : sortedLocaleList) {
            localesToUse.add(toUse);
            for (String l : availableLocales) {
                if (l.equals(toUse.split("-")[0])) {
                    localesToUse.add(l);
                    break;
                }
            }
        }
    } else {
        for (String l : availableLocales) {
            if (l.startsWith(languageTag)) {
                localesToUse.add(l);
            }
        }
    }
    if (availableLocales.contains("en-US")) {
        localesToUse.add("en-US");
    }
    for (String l : availableLocales) {
        if (l.startsWith("en")) {
            localesToUse.add(l);
            break;
        }
    }
    whatsNew = getLocalizedEntry(localized, localesToUse, "whatsNew");
    String value = getLocalizedEntry(localized, localesToUse, "video");
    if (!TextUtils.isEmpty(value)) {
        video = value.split("\n", 1)[0];
    }
    value = getLocalizedEntry(localized, localesToUse, "name");
    if (!TextUtils.isEmpty(value)) {
        name = value;
    }
    value = getLocalizedEntry(localized, localesToUse, "summary");
    if (!TextUtils.isEmpty(value)) {
        summary = value;
    }
    value = getLocalizedEntry(localized, localesToUse, "description");
    if (!TextUtils.isEmpty(value)) {
        description = formatDescription(value);
    }
    featureGraphic = getLocalizedGraphicsEntry(localized, localesToUse, "featureGraphic");
    promoGraphic = getLocalizedGraphicsEntry(localized, localesToUse, "promoGraphic");
    tvBanner = getLocalizedGraphicsEntry(localized, localesToUse, "tvBanner");
    wearScreenshots = getLocalizedListEntry(localized, localesToUse, "wearScreenshots");
    phoneScreenshots = getLocalizedListEntry(localized, localesToUse, "phoneScreenshots");
    sevenInchScreenshots = getLocalizedListEntry(localized, localesToUse, "sevenInchScreenshots");
    tenInchScreenshots = getLocalizedListEntry(localized, localesToUse, "tenInchScreenshots");
    tvScreenshots = getLocalizedListEntry(localized, localesToUse, "tvScreenshots");
}
Also used : Locale(java.util.Locale) LinkedHashSet(java.util.LinkedHashSet) LocaleList(android.os.LocaleList) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty)

Example 7 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project autorest-clientruntime-for-java by Azure.

the class Validator method validate.

/**
 * Validates a user provided required parameter to be not null.
 * An {@link IllegalArgumentException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid
 */
public static void validate(Object parameter) {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }
    Class parameterType = parameter.getClass();
    TypeToken<?> parameterToken = TypeToken.of(parameterType);
    if (Primitives.isWrapperType(parameterType)) {
        parameterToken = parameterToken.unwrap();
    }
    if (parameterToken.isPrimitive() || parameterType.isEnum() || parameterType == Class.class || parameterToken.isSupertypeOf(LocalDate.class) || parameterToken.isSupertypeOf(DateTime.class) || parameterToken.isSupertypeOf(String.class) || parameterToken.isSupertypeOf(DateTimeRfc1123.class) || parameterToken.isSupertypeOf(Period.class)) {
        return;
    }
    for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
        // Ignore checks for Object type.
        if (c.isAssignableFrom(Object.class)) {
            continue;
        }
        for (Field field : c.getDeclaredFields()) {
            field.setAccessible(true);
            int mod = field.getModifiers();
            // Skip static fields since we don't have any, skip final fields since users can't modify them
            if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) {
                continue;
            }
            JsonProperty annotation = field.getAnnotation(JsonProperty.class);
            // Skip read-only properties (WRITE_ONLY)
            if (annotation != null && annotation.access().equals(JsonProperty.Access.WRITE_ONLY)) {
                continue;
            }
            Object property;
            try {
                property = field.get(parameter);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            }
            if (property == null) {
                if (annotation != null && annotation.required()) {
                    throw new IllegalArgumentException(field.getName() + " is required and cannot be null.");
                }
            } else {
                try {
                    Class<?> propertyType = property.getClass();
                    if (TypeToken.of(List.class).isSupertypeOf(propertyType)) {
                        List<?> items = (List<?>) property;
                        for (Object item : items) {
                            Validator.validate(item);
                        }
                    } else if (TypeToken.of(Map.class).isSupertypeOf(propertyType)) {
                        Map<?, ?> entries = (Map<?, ?>) property;
                        for (Map.Entry<?, ?> entry : entries.entrySet()) {
                            Validator.validate(entry.getKey());
                            Validator.validate(entry.getValue());
                        }
                    } else if (parameterType != propertyType) {
                        Validator.validate(property);
                    }
                } catch (IllegalArgumentException ex) {
                    if (ex.getCause() == null) {
                        // Build property chain
                        throw new IllegalArgumentException(field.getName() + "." + ex.getMessage());
                    } else {
                        throw ex;
                    }
                }
            }
        }
    }
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Period(org.joda.time.Period) LocalDate(org.joda.time.LocalDate) Field(java.lang.reflect.Field) List(java.util.List) Map(java.util.Map)

Example 8 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project autorest-clientruntime-for-java by Azure.

the class FlatteningDeserializer method deserialize.

@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode root = mapper.readTree(jp);
    final Class<?> tClass = this.defaultDeserializer.handledType();
    for (Class<?> c : TypeToken.of(tClass).getTypes().classes().rawTypes()) {
        // Ignore checks for Object type.
        if (c.isAssignableFrom(Object.class)) {
            continue;
        }
        for (Field field : c.getDeclaredFields()) {
            JsonNode node = root;
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            if (property != null) {
                String value = property.value();
                if (value.matches(".+[^\\\\]\\..+")) {
                    String[] values = value.split("((?<!\\\\))\\.");
                    for (String val : values) {
                        val = val.replace("\\.", ".");
                        node = node.get(val);
                        if (node == null) {
                            break;
                        }
                    }
                    ((ObjectNode) root).put(value, node);
                }
            }
        }
    }
    JsonParser parser = new JsonFactory().createParser(root.toString());
    parser.nextToken();
    return defaultDeserializer.deserialize(parser, ctxt);
}
Also used : Field(java.lang.reflect.Field) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 9 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project POL-POM-5 by PhoenicisOrg.

the class LocalisationHelper method fetchParameterName.

private String fetchParameterName(Parameter parameter) {
    final JsonProperty jsonAnnotation = parameter.getAnnotation(JsonProperty.class);
    final ParameterName parameterNameAnnotation = parameter.getAnnotation(ParameterName.class);
    if (parameterNameAnnotation != null) {
        return parameterNameAnnotation.value();
    }
    if (jsonAnnotation != null) {
        return jsonAnnotation.value();
    }
    return parameter.getName();
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty)

Example 10 with JsonProperty

use of com.fasterxml.jackson.annotation.JsonProperty in project crnk-framework by crnk-project.

the class JacksonResourceFieldInformationProvider method getJsonName.

@Override
public Optional<String> getJsonName(BeanAttributeInformation attributeDesc) {
    Optional<JsonProperty> ignoreAnnotation = attributeDesc.getAnnotation(JsonProperty.class);
    if (ignoreAnnotation.isPresent() && !ignoreAnnotation.get().value().isEmpty()) {
        return Optional.of(ignoreAnnotation.get().value());
    }
    Method getter = attributeDesc.getGetter();
    if (getter != null) {
        Optional<String> name = getName(getter);
        if (name.isPresent()) {
            return name;
        }
    }
    Field field = attributeDesc.getField();
    if (field != null) {
        Optional<String> name = getName(field);
        if (name.isPresent()) {
            return name;
        }
    }
    return Optional.empty();
}
Also used : Field(java.lang.reflect.Field) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) Method(java.lang.reflect.Method)

Aggregations

JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)39 ArrayList (java.util.ArrayList)10 Field (java.lang.reflect.Field)9 Annotation (java.lang.annotation.Annotation)8 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)6 Method (java.lang.reflect.Method)6 Type (java.lang.reflect.Type)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)5 HashMap (java.util.HashMap)5 JsonCreator (com.fasterxml.jackson.annotation.JsonCreator)4 JavaType (com.fasterxml.jackson.databind.JavaType)4 AnnotatedClass (com.fasterxml.jackson.databind.introspect.AnnotatedClass)4 JsonIdentityInfo (com.fasterxml.jackson.annotation.JsonIdentityInfo)3 JsonIdentityReference (com.fasterxml.jackson.annotation.JsonIdentityReference)3 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)3 PropertyMetadata (com.fasterxml.jackson.databind.PropertyMetadata)3 AnnotatedMember (com.fasterxml.jackson.databind.introspect.AnnotatedMember)3 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)3