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:com.tectonica.thirdparty.Jackson2.java

public static <T, P> T fromJson(InputStream is, Class<T> clz, Class<P> paramClz, ObjectMapper mapper) {
    try {/*from w  ww .jav a2  s  . c o m*/
        JavaType jt = mapper.getTypeFactory().constructParametrizedType(clz, clz, paramClz);
        return mapper.readValue(is, jt);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tectonica.thirdparty.Jackson2.java

public static <T, P> T fromJson(Reader r, Class<T> clz, Class<P> paramClz, ObjectMapper mapper) {
    try {//from  w w  w  . ja v a 2 s  . c o m
        JavaType jt = mapper.getTypeFactory().constructParametrizedType(clz, clz, paramClz);
        return mapper.readValue(r, jt);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:id.zelory.tanipedia.util.Utils.java

public static ArrayList<Berita> getRandomBerita(Context context, String alamat) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayList<Berita> beritaArrayList = null;
    try {/*from   www .  j av  a  2  s .com*/
        beritaArrayList = mapper.readValue(PrefUtils.ambilString(context, "berita"),
                mapper.getTypeFactory().constructCollectionType(ArrayList.class, Berita.class));
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < 5; i++) {
        int x = randInt(0, beritaArrayList.size() - 1);
        if (beritaArrayList.get(x).getAlamat().equals(alamat)) {
            beritaArrayList.remove(x);
            i--;
        } else {
            beritaArrayList.set(i, beritaArrayList.get(x));
            beritaArrayList.remove(x);
        }
    }

    for (int i = 5; i < beritaArrayList.size(); i++)
        beritaArrayList.remove(i);

    return beritaArrayList;
}

From source file:de.alpharogroup.xml.json.JsonTransformer.java

/**
 * Transforms the given json string into a java object list.
 *
 * @param <T>/*from  w  w w . j a v  a  2 s .  c o m*/
 *            the generic type of the return type
 * @param jsonString
 *            the json string
 * @param clazz
 *            the clazz of the generic type
 * @return the list with the java objects.
 * @throws JsonParseException
 *             If an error occurs when parsing the string into Object
 * @throws JsonMappingException
 *             the If an error occurs when mapping the string into Object
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static <T> List<T> toObjectList(final String jsonString, final Class<T> clazz)
        throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = getObjectMapper(true);
    final List<T> objectList = mapper.readValue(jsonString,
            mapper.getTypeFactory().constructCollectionType(List.class, clazz));
    return objectList;
}

From source file:org.openengsb.core.util.JsonUtils.java

public static ObjectMapper createObjectMapperWithIntroSpectors() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector primaryIntrospector = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondaryIntrospector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    AnnotationIntrospector introspector = new AnnotationIntrospectorPair(primaryIntrospector,
            secondaryIntrospector);// w  ww.  j a  v  a  2s.  c o m
    mapper.getDeserializationConfig().withAppendedAnnotationIntrospector(introspector);
    mapper.getSerializationConfig().withAppendedAnnotationIntrospector(introspector);
    return mapper;
}

From source file:de.avpptr.umweltzone.utils.ContentProvider.java

@SuppressWarnings("unchecked") // for Collections.EMPTY_LIST
@NonNull/* ww  w.  j a va2 s.  c  om*/
private static <T> List<T> getContent(final Context context, final String fileName, final String folderName,
        Class<T> contentType) {
    int rawResourceId = getResourceId(context, fileName, folderName);

    InputStream inputStream = context.getResources().openRawResource(rawResourceId);
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Circuit.class, new CircuitDeserializer());
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(module);
    String datePattern = context.getString(R.string.config_zone_number_since_date_format);
    objectMapper.setDateFormat(new SimpleDateFormat(datePattern, Locale.getDefault()));
    try {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(List.class, contentType);
        return objectMapper.readValue(inputStream, collectionType);
    } catch (IOException e) {
        // TODO Aware that app will crash when JSON is mis-structured.
        e.printStackTrace();
    }
    Log.e(ContentProvider.class.getName(), "Failure parsing zone data for: " + fileName);
    return Collections.EMPTY_LIST;
}

From source file:loadTest.loadTestLib.LUtil.java

public static List<LoadTestConfigModel> readJSONConfig() throws IOException {
    InputStream in = LUtil.class.getClassLoader().getResourceAsStream("loadTestConfig.json");
    ObjectMapper mapper = new ObjectMapper();
    List<LoadTestConfigModel> myObjects = mapper.readValue(in,
            mapper.getTypeFactory().constructCollectionType(List.class, LoadTestConfigModel.class));
    return myObjects;
}

From source file:org.apache.nifi.toolkit.cli.impl.client.nifi.impl.JerseyNiFiClient.java

private static JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
    JacksonJaxbJsonProvider jacksonJaxbJsonProvider = new JacksonJaxbJsonProvider();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDefaultPropertyInclusion(//from  w  w w .j av  a  2s.  c o m
            JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
    mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(mapper.getTypeFactory()));
    // Ignore unknown properties so that deployed client remain compatible with future versions of NiFi that add new fields
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    jacksonJaxbJsonProvider.setMapper(mapper);
    return jacksonJaxbJsonProvider;
}

From source file:org.apache.nifi.registry.client.impl.JerseyNiFiRegistryClient.java

private static JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
    JacksonJaxbJsonProvider jacksonJaxbJsonProvider = new JacksonJaxbJsonProvider();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyInclusion(/*from ww w  .jav a 2  s. com*/
            JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
    mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(mapper.getTypeFactory()));
    // Ignore unknown properties so that deployed client remain compatible with future versions of NiFi Registry that add new fields
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(BucketItem[].class, new BucketItemDeserializer());
    mapper.registerModule(module);

    jacksonJaxbJsonProvider.setMapper(mapper);
    return jacksonJaxbJsonProvider;
}

From source file:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * This method adds a selection of {@link TNodeTemplate}- and {@link TRelationshipTemplate}-XML-Strings to a {@link TTopologyTemplate}-XML-String using JAXB.
 * After the templates have been added, the {@link TTopologyTemplate} object is re-marshalled to an XML-String.
 *
 * This method is called by the selectionHandler.jsp after several Node or RelationshipTemplates have been chosen in a dialog.
 *
 * @param topology/*from ww  w  .  jav a  2  s. co m*/
 *            the topology as XML string
 * @param allTemplateChoicesAsXML
 *            all possible template choices as TOSCA-XML strings containing the complete templates
 * @param selectedNodeTemplatesAsJSON
 *            the names of the selected NodeTemplates as JSONArray
 * @param selectedRelationshipTemplatesAsJSON
 *            the names of the selected RelationshipTemplates as JSONArray
 *
 * @return the complete topology XML string
 */
public static String addTemplatesToTopology(String topology, String allTemplateChoicesAsXML,
        String selectedNodeTemplatesAsJSON, String selectedRelationshipTemplatesAsJSON) {
    try {

        // initialization code for the jackson types used to convert JSON string arrays to a java.util.List
        ObjectMapper mapper = new ObjectMapper();
        TypeFactory factory = mapper.getTypeFactory();

        // convert the JSON array containing the names of the selected RelationshipTemplates to a java.util.List
        List<String> selectedRelationshipTemplates = mapper.readValue(selectedRelationshipTemplatesAsJSON,
                factory.constructCollectionType(List.class, String.class));

        // convert the topology and the choices to objects using JAXB
        TTopologyTemplate topologyTemplate = getTopologyAsJaxBObject(topology);
        List<TEntityTemplate> allTemplateChoices = getEntityTemplatesAsJaxBObject(allTemplateChoicesAsXML);

        // this distinction of cases is necessary because it is possible that only RelationshipTemplates have been selected
        if (selectedNodeTemplatesAsJSON != null) {

            // convert the JSON string array containing the names of the selected NodeTemplates to a java.util.List
            List<String> selectedNodeTemplates = mapper.readValue(selectedNodeTemplatesAsJSON,
                    factory.constructCollectionType(List.class, String.class));

            // search the selected NodeTemplate in the List of all choices by its name to receive its object which will ne added to the topology
            for (String nodeTemplateName : selectedNodeTemplates) {
                for (TEntityTemplate choice : allTemplateChoices) {
                    if (choice instanceof TNodeTemplate) {
                        TNodeTemplate nodeTemplate = (TNodeTemplate) choice;
                        // matching a name is usually unsafe because the uniqueness cannot be assured,
                        // however similar names are not possible at this location due to the implementation of the selection dialogs
                        if (nodeTemplateName.equals(nodeTemplate.getName())) {
                            // add the selected NodeTemplate to the topology
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate);

                            // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                            // Re-add it to avoid errors.
                            for (TEntityTemplate entity : topologyTemplate
                                    .getNodeTemplateOrRelationshipTemplate()) {
                                if (entity instanceof TRelationshipTemplate) {
                                    TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) entity;
                                    if (relationshipTemplate.getSourceElement().getRef() == null) {
                                        // connect to the added NodeTemplate
                                        SourceElement sourceElement = new SourceElement();
                                        sourceElement.setRef(nodeTemplate);
                                        relationshipTemplate.setSourceElement(sourceElement);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // now search and add the selected RelationshipTemplate object connecting to the inserted NodeTemplate
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TEntityTemplate toBeAdded : allTemplateChoices) {
                    if (toBeAdded instanceof TRelationshipTemplate) {
                        TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) toBeAdded;
                        if (relationshipTemplateName.equals(relationshipTemplate.getName())) {
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relationshipTemplate);
                        }
                    }
                }
            }

        } else {
            // in this case only Relationship Templates have been selected
            List<TRelationshipTemplate> allRelationshipTemplateChoices = JAXBHelper
                    .getRelationshipTemplatesAsJaxBObject(allTemplateChoicesAsXML);

            // add the target Node Template to the topology which is unique due to the implementation of the selection dialog
            topologyTemplate.getNodeTemplateOrRelationshipTemplate()
                    .add((TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                            .getTargetElement().getRef());

            // search the JAXB object of the selected RelationshipTemplate and add it to the topology
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TRelationshipTemplate choice : allRelationshipTemplateChoices) {
                    if (relationshipTemplateName.equals(choice.getName())) {
                        topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(choice);
                    }
                }
            }

            for (TEntityTemplate entityTemplate : topologyTemplate.getNodeTemplateOrRelationshipTemplate()) {
                if (entityTemplate instanceof TRelationshipTemplate) {
                    TRelationshipTemplate relationship = (TRelationshipTemplate) entityTemplate;

                    // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                    // Re-add it to avoid errors.
                    if (relationship.getSourceElement().getRef() == null) {
                        relationship.getSourceElement().setRef(
                                (TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                                        .getTargetElement().getRef());
                    }
                }
            }
        }

        // re-convert the topology from a JAXB object to an XML string and return it
        Definitions definitions = new Definitions();
        TServiceTemplate st = new TServiceTemplate();
        st.setTopologyTemplate(topologyTemplate);
        definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(st);
        JAXBContext context = JAXBContext.newInstance(Definitions.class);
        Marshaller m = context.createMarshaller();
        StringWriter stringWriter = new StringWriter();

        m.marshal(definitions, stringWriter);

        return stringWriter.toString();

    } catch (JAXBException | IOException e) {
        logger.error(e.getLocalizedMessage());
    }

    return null;
}