Example usage for com.fasterxml.jackson.databind ObjectMapper getTypeFactory

List of usage examples for com.fasterxml.jackson.databind ObjectMapper getTypeFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper getTypeFactory.

Prototype

public TypeFactory getTypeFactory() 

Source Link

Document

Accessor for getting currently configured TypeFactory instance.

Usage

From source file:gaffer.rest.service.SimpleGraphConfigurationService.java

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override/*from ww  w . j a  va 2 s.c  o m*/
public Set<String> getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(className);
    } catch (Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();

    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }

    return fields;
}

From source file:ijfx.service.overlay.io.OverlayLoader.java

public List<Overlay> load(File f) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Overlay.class, new OverlayDeserializer(context));
    mapper.registerModule(module);/*from   w w w .  ja  v  a 2 s .  c  o  m*/
    try {
        return mapper.readValue(f, mapper.getTypeFactory().constructCollectionType(List.class, Overlay.class));
    } catch (Exception e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
}

From source file:com.google.api.server.spi.config.jsonwriter.JacksonResourceSchemaProvider.java

@Override
public ResourceSchema getResourceSchema(TypeToken<?> type, ApiConfig config) {
    ResourceSchema schema = super.getResourceSchema(type, config);
    if (schema != null) {
        return schema;
    }/*from   w  w w.  ja va  2  s . c o m*/
    ObjectMapper objectMapper = ObjectMapperUtil.createStandardObjectMapper(config.getSerializationConfig());
    JavaType javaType = objectMapper.getTypeFactory().constructType(type.getRawType());
    BeanDescription beanDescription = objectMapper.getSerializationConfig().introspect(javaType);
    ResourceSchema.Builder schemaBuilder = ResourceSchema.builderForType(type.getRawType());
    Set<String> genericDataFieldNames = getGenericDataFieldNames(type);
    for (BeanPropertyDefinition definition : beanDescription.findProperties()) {
        TypeToken<?> propertyType = getPropertyType(type, toMethod(definition.getGetter()),
                toMethod(definition.getSetter()), definition.getField(), config);
        String name = definition.getName();
        if (genericDataFieldNames == null || genericDataFieldNames.contains(name)) {
            if (hasUnresolvedType(propertyType)) {
                logger.warning("skipping field '" + name + "' of type '" + propertyType
                        + "' because it is unresolved.");
                continue;
            }
            if (propertyType != null) {
                schemaBuilder.addProperty(name, ResourcePropertySchema.of(propertyType));
            } else {
                logger.warning("No type found for property '" + name + "' on class '" + type + "'.");
            }
        } else {
            logger.fine("skipping field '" + name + "' because it's not a Java client model field.");
        }
    }
    return schemaBuilder.build();
}

From source file:com.proofpoint.json.JsonCodec.java

JsonCodec(ObjectMapper mapper, Type type) {
    this.mapper = mapper;
    this.type = type;
    this.javaType = mapper.getTypeFactory().constructType(type);
}

From source file:com.happydroids.droidtowers.gui.AboutWindow.java

public AboutWindow(Stage stage) {
    super("Droid Towers by happydroids.com", stage);

    defaults().left().space(Display.devicePixel(8));

    row().padTop(Display.devicePixel(20));
    add(FontManager.RobotoBold18.makeLabel("Credits"));
    addHorizontalRule(Colors.DARK_GRAY, 1, 1);

    addLabel("Philip Plante", FontManager.Roboto24);
    addLabel("Programming and Game Design", FontManager.Roboto18).spaceBottom(Display.devicePixel(16));

    addLabel("Will Phillips", FontManager.Roboto24);
    addLabel("Music Composer", FontManager.Roboto18);
    row();//from   w  w  w  . j  a  v a2  s  . c o  m
    TextButton willPhillipsButton = FontManager.Roboto18.makeTextButton("facebook.com/willphillipsmusic");
    willPhillipsButton.addListener(new VibrateClickListener() {
        @Override
        public void onClick(InputEvent event, float x, float y) {
            Platform.getBrowserUtil().launchWebBrowser("http://www.facebook.com/willphillipsmusic");
        }
    });
    add(willPhillipsButton).spaceBottom(Display.devicePixel(16));

    addLabel("Alex Miller", FontManager.Roboto24);
    addLabel("Lead Artist", FontManager.Roboto18).spaceBottom(Display.devicePixel(32));

    addLabel("Thank you to the following Friends who helped test:", FontManager.RobotoBold18);
    addHorizontalRule(Colors.DARK_GRAY, 1, 1);
    addLabel(StringUtils.wrap(Gdx.files.internal("testers.txt").readString(), 60), FontManager.Roboto18);

    addHorizontalRule(Colors.DARK_GRAY, 1, 1).padTop(Display.devicePixel(50));
    addLabel("Device ID: " + TowerGameService.instance().getDeviceId(), FontManager.Roboto18);
    addLabel("Game Version: " + TowerConsts.VERSION + " (" + TowerConsts.GIT_SHA.substring(0, 8) + ")",
            FontManager.Roboto18);

    row().spaceTop(Display.devicePixel(40));
    add(FontManager.RobotoBold18.makeLabel("Software Licenses"));
    addHorizontalRule(Colors.DARK_GRAY, 1, 1);

    try {
        ObjectMapper mapper = new ObjectMapper();
        List<String> licenseFiles = mapper.readValue(Gdx.files.internal("licenses/index.json").readBytes(),
                mapper.getTypeFactory().constructCollectionType(ArrayList.class, String.class));
        for (String licenseFile : licenseFiles) {
            FileHandle licenseFileHandle = Gdx.files.internal(licenseFile);
            if (licenseFileHandle.exists()) {
                addLabel(licenseFileHandle.readString(), FontManager.Roboto18)
                        .spaceBottom(Display.devicePixel(32));
            }
        }
    } catch (IOException ignored) {
    }
}

From source file:capital.scalable.restdocs.payload.AbstractJacksonFieldSnippet.java

protected Collection<FieldDescriptor> createFieldDescriptors(Operation operation, HandlerMethod handlerMethod) {
    ObjectMapper objectMapper = getObjectMapper(operation);
    ObjectWriter writer = objectMapper.writer();
    TypeFactory typeFactory = objectMapper.getTypeFactory();

    JavadocReader javadocReader = getJavadocReader(operation);
    ConstraintReader constraintReader = getConstraintReader(operation);

    Map<String, FieldDescriptor> fieldDescriptors = new LinkedHashMap<>();

    Type signatureType = getType(handlerMethod);
    if (signatureType != null) {
        try {//from w  ww .  j a v a  2  s  . c om
            for (Type type : resolveActualTypes(signatureType)) {
                resolveFieldDescriptors(fieldDescriptors, type, writer, typeFactory, javadocReader,
                        constraintReader);
            }
        } catch (JsonMappingException e) {
            throw new JacksonFieldProcessingException("Error while parsing fields", e);
        }
    }

    return fieldDescriptors.values();
}

From source file:com.dynatrace.cf.servicebroker.catalog.CatalogFactory.java

@Bean
Catalog catalog(@Value("${DYNATRACE_SERVICE_PLANS}") String dynatracePlans) throws Exception {
    System.out.println("DYNATRACE_SERVICE_PLANS set to: " + dynatracePlans);
    String serviceId = UUID.nameUUIDFromBytes("Dynatrace_ServiceId_v12".getBytes()).toString();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    plans = (Map) objectMapper.readValue(dynatracePlans, objectMapper.getTypeFactory()
            .constructMapLikeType(HashMap.class, String.class, DynatracePlan.class));

    for (DynatracePlan p : plans.values()) {
        p.setPlanId();/*from  ww  w.  ja va 2 s  . com*/
        System.out.println("\t\tDynatracePlan: " + p);
    }

    return new Catalog().service().id(UUID.fromString(serviceId)).name("dynatrace").description(
            "Dynatrace is all-in-one full stack performance monitoring and management powered by artificial intelligence")
            .bindable(Boolean.valueOf(true))
            .tags(new String[] { "dynatrace", "performance", "monitoring", "apm", "analytics" }).metadata()
            .displayName("Dynatrace")
            .imageUrl(
                    URI.create("https://assets.dynatrace.com/global/resources/Signet_Logo_RGB_CP_48x48px.png"))
            .longDescription("Dynatrace is all-in-one full stack performance "
                    + "monitoring and management powered by artificial "
                    + "intelligence that provides you with automated application-health "
                    + "and root-cause analysis information to quickly identify "
                    + "performance bottlenecks in browsers, databases and code.")
            .providerDisplayName("Dynatrace LLC").documentationUrl(URI.create("https://help.dynatrace.com"))
            .supportUrl(URI.create("https://support.ruxit.com")).and().addAllPlans(plans).and();
}

From source file:ijfx.service.ui.DefaultHintService.java

private List<DefaultHint> jsonToHintList(String json) {
    try {/*from  w w w  .  j a  v  a2s.co  m*/
        ObjectMapper mapper = new ObjectMapper();
        List<DefaultHint> hints = mapper.readValue(json,
                mapper.getTypeFactory().constructCollectionType(List.class, DefaultHint.class));
        return hints;
    } catch (IOException ex) {
        Logger.getLogger(DefaultHintService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.proofpoint.http.client.SmileBodyGenerator.java

public static <T> SmileBodyGenerator<T> smileBodyGenerator(JsonCodec<T> jsonCodec, T instance) {
    ObjectMapper objectMapper = OBJECT_MAPPER_SUPPLIER.get();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JsonGenerator jsonGenerator;//  w  w w  . jav  a  2s . c  om
    try {
        jsonGenerator = new SmileFactory().createGenerator(out);
    } catch (IOException e) {
        throw propagate(e);
    }

    Type genericType = jsonCodec.getType();
    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;
    if (genericType != null && instance != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        // type since it prevents polymorphic type serialization. Since we really
        // just need this for generics, let's only use generic type if it's truly
        // generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            // type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            // for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    try {
        if (rootType != null) {
            objectMapper.writerWithType(rootType).writeValue(jsonGenerator, instance);
        } else {
            objectMapper.writeValue(jsonGenerator, instance);
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(
                String.format("%s could not be converted to SMILE", instance.getClass().getName()), e);
    }

    return new SmileBodyGenerator<>(out.toByteArray());
}

From source file:org.comicwiki.Repository.java

public void load(InputStream is, DataFormat format) throws IOException, JsonLdError {
    Collection<T> results = new TreeSet<T>();
    if (DataFormat.JSON.equals(format)) {
        @SuppressWarnings("unchecked")
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        ObjectMapper mapper = new ObjectMapper();

        results = mapper.readValue(is,//  www  . j av a2 s . c om
                mapper.getTypeFactory().constructCollectionType(Collection.class, clazz));
    } else if (DataFormat.TURTLE.equals(format)) {
        String data = FileUtils.readStream(is);
        results = TurtleImporter.importTurtle(data, new TreeSet<T>());

    } else if (DataFormat.N_TRIPLES.equals(format)) {
        String data = FileUtils.readStream(is);
        results = TurtleImporter.importNTriples(data, new TreeSet<T>());
    }

    for (T t : results) {
        cache.put(t.instanceId, t);
    }
}