Example usage for com.fasterxml.jackson.databind.type TypeFactory constructCollectionType

List of usage examples for com.fasterxml.jackson.databind.type TypeFactory constructCollectionType

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.type TypeFactory constructCollectionType.

Prototype

public CollectionType constructCollectionType(Class<? extends Collection> paramClass, Class<?> paramClass1) 

Source Link

Usage

From source file:com.bna.ezrxlookup.util.JsonMapperUtil.java

/**
 * Parse JSON string and return a list of object type.
 * @param jsonString - input JSON string
 * @param rootName - root node name//from w  ww .  ja  va 2s  .  c  o  m
 * @param type - object class type
 * @return list of object class
 */
public static <T> List<T> readJsonToList(String jsonString, String rootName, Class<T> clazz) throws Exception {
    List<T> objList = null;
    ObjectMapper objectMapper = new ObjectMapper();

    try {
        // get json content with root name
        JsonNode root = objectMapper.readTree(jsonString).get(rootName);
        TypeFactory tf = objectMapper.getTypeFactory();
        JavaType listOfObjs = tf.constructCollectionType(ArrayList.class, clazz);
        objList = objectMapper.readValue(root.traverse(), listOfObjs);
    } catch (Exception e) {
        throw e;
    }

    return objList;
}

From source file:com.xvdiff.infinity.utils.Mapper.java

public static <T> List<T> mapCollection(String data, Class<T> type)
        throws JsonParseException, JsonMappingException, IOException {
    TypeFactory typeFactory = getInstance().getTypeFactory();
    return getInstance().readValue(data, typeFactory.constructCollectionType(List.class, type));
}

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

@SuppressWarnings("unchecked") // for Collections.EMPTY_LIST
@NonNull// ww w  . j  ava 2s .c o  m
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:org.roda.core.data.utils.JsonUtils.java

public static <T> List<T> getListFromJson(String json, Class<T> objectClass) throws GenericException {
    try {/*from w w  w .j  a  v  a2  s.  co  m*/
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        TypeFactory t = TypeFactory.defaultInstance();
        return mapper.readValue(json, t.constructCollectionType(ArrayList.class, objectClass));
    } catch (IOException e) {
        throw new GenericException(JSON_ERROR_MESSAGE, e);
    }
}

From source file:com.auditbucket.client.Importer.java

private static long processJsonTags(String fileName, AbRestClient abExporter, int skipCount,
        boolean simulateOnly) {
    Collection<TagInputBean> tags;
    ObjectMapper mapper = new ObjectMapper();
    try {/*w w w . j  a  va 2  s.co m*/
        File file = new File(fileName);
        if (!file.exists()) {
            logger.error("{} does not exist", fileName);
            return 0;
        }
        TypeFactory typeFactory = mapper.getTypeFactory();
        CollectionType collType = typeFactory.constructCollectionType(ArrayList.class, TagInputBean.class);

        tags = mapper.readValue(file, collType);
        for (TagInputBean tag : tags) {
            abExporter.writeTag(tag, "JSON Tag Importer");
        }
    } catch (IOException e) {
        logger.error("Error writing exceptions with {} [{}]", fileName, e);
        throw new RuntimeException("IO Exception ", e);
    } finally {
        abExporter.flush("Finishing processing of TagInputBeans " + fileName);

    }
    return tags.size(); //To change body of created methods use File | Settings | File Templates.
}

From source file:org.mstc.zmq.json.Decoder.java

@SuppressWarnings("unchecked")
public static void decode(String input, Field[] fields, Object b) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    if (logger.isDebugEnabled())
        logger.debug(input);//from ww  w.j ava  2  s  . co m
    JsonFactory factory = mapper.getFactory();
    try (JsonParser jp = factory.createParser(input)) {
        /* Sanity check: verify that we got "Json Object" */
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }

        /* Iterate over object fields */
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            jp.nextToken();
            Field field = getField(fieldName, fields);
            if (field == null) {
                throw new IOException(
                        "Could not find field [" + fieldName + "] on class " + b.getClass().getName());
            }
            try {
                if (field.getType().isAssignableFrom(List.class)) {
                    String adder = getAdder(fieldName);
                    TypeFactory t = TypeFactory.defaultInstance();
                    ParameterizedType listType = (ParameterizedType) field.getGenericType();
                    Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
                    List list = mapper.readValue(jp.getValueAsString(),
                            t.constructCollectionType(List.class, listClass));
                    Method m = b.getClass().getDeclaredMethod(adder, Collection.class);
                    m.invoke(b, list);
                } else if (field.getType().isArray()) {
                    Class<?> type = field.getType();
                    String setter = getSetter(fieldName);
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());
                    logger.info("Field {} is array of {}[], {}, using method {}", field.getName(),
                            field.getType().getComponentType(), jp.getCurrentToken().name(), m);
                    if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) {
                        List list = new ArrayList();
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            String value = jp.getText();
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                list.add(value);
                                break;
                            case VALUE_NUMBER_INT:
                                if (type.getComponentType().isAssignableFrom(double.class)) {
                                    list.add(Double.parseDouble(value));
                                } else if (type.getComponentType().isAssignableFrom(float.class)) {
                                    list.add(Float.parseFloat(value));
                                } else {
                                    list.add(Integer.parseInt(value));
                                }
                                break;
                            case VALUE_NUMBER_FLOAT:
                                logger.info("Add float");
                                list.add(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                break;
                            default:
                                logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        Object array = Array.newInstance(field.getType().getComponentType(), list.size());
                        for (int i = 0; i < list.size(); i++) {
                            Object val = list.get(i);
                            Array.set(array, i, val);
                        }
                        m.invoke(b, array);
                    } else {
                        if (type.getComponentType().isAssignableFrom(byte.class)) {
                            m.invoke(b, jp.getBinaryValue());
                        }
                    }
                } else {
                    String setter = getSetter(fieldName);
                    logger.debug("{}: {}", setter, field.getType().getName());
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());

                    switch (jp.getCurrentToken()) {
                    case VALUE_STRING:
                        m.invoke(b, jp.getText());
                        break;
                    case VALUE_NUMBER_INT:
                        m.invoke(b, jp.getIntValue());
                        break;
                    case VALUE_NUMBER_FLOAT:
                        m.invoke(b, jp.getFloatValue());
                        break;
                    case VALUE_NULL:
                        logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(),
                                m.getName());
                        break;
                    case START_OBJECT:
                        StringBuilder sb = new StringBuilder();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                sb.append("\"").append(jp.getText()).append("\"");
                                break;
                            case FIELD_NAME:
                                if (sb.length() > 0)
                                    sb.append(",");
                                sb.append("\"").append(jp.getText()).append("\"").append(":");
                                break;
                            case VALUE_NUMBER_INT:
                                sb.append(jp.getIntValue());
                                break;
                            case VALUE_NUMBER_FLOAT:
                                sb.append(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                sb.append("null");
                                break;
                            default:
                                logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(),
                                JsonToken.END_OBJECT.asString());
                        Object parsed = getNested(field.getType(), s.getBytes());
                        m.invoke(b, parsed);
                        break;
                    default:
                        logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name());
                    }
                }
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException
                    | IllegalArgumentException e) {
                logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e);
            }
        }
    }
}

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  . ja  v  a  2 s  .  c om
 *            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;
}

From source file:org.mythtv.services.api.converters.ArrayOfStringConverter.java

@Override
public JavaType getInputType(TypeFactory typeFactory) {
    return typeFactory.constructCollectionType(List.class, String.class);
}

From source file:com.aba.market.fetch.impl.CrestMarketOrderFetcherUnitTests.java

@Before
public void setupData() throws IOException {
    InputStream sleipnirDataIS = CrestMarketOrderFetcherUnitTests.class
            .getResourceAsStream("/CrestMarketWithDataForSleipnirs.json");

    TypeFactory typeFactory = mapper.getTypeFactory();
    CollectionType type = typeFactory.constructCollectionType(List.class, CrestMarketOrder.class);
    sleipnirData = mapper.readValue(sleipnirDataIS, type);
}

From source file:io.fabric8.example.variance.http.VarianceProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    String message = exchange.getIn().getBody(String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    List<Double> values = objectMapper.readValue(message,
            typeFactory.constructCollectionType(List.class, Double.class));
    SummaryStatistics summaryStatistics = new SummaryStatistics();
    List<Double> list = new ObjectMapper().readValue(message, List.class);
    for (Double value : list) {
        summaryStatistics.addValue(value);
    }//www  . j  av a  2  s . c  om
    String variance = Double.toString(summaryStatistics.getVariance());
    exchange.getOut().setBody(variance);
}