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:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

private List<Point> getServerData() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();

    HttpURLConnection urlConnection = (HttpURLConnection) new URL(findNumericMetricsUrl).openConnection();
    urlConnection.connect();/* w  ww  .j a  v  a  2s .  c  o  m*/
    int responseCode = urlConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        String msg = "Could not get metrics list from server: %s, %d";
        fail(String.format(Locale.ROOT, msg, findNumericMetricsUrl, responseCode));
    }
    List<String> metricNames;
    try (InputStream inputStream = urlConnection.getInputStream()) {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricName.class);
        List<MetricName> value = objectMapper.readValue(inputStream, valueType);
        metricNames = value.stream().map(MetricName::getId).collect(toList());
    }

    Stream<Point> points = Stream.empty();

    for (String metricName : metricNames) {
        String[] split = metricName.split("\\.");
        String type = split[split.length - 1];

        urlConnection = (HttpURLConnection) new URL(findNumericDataUrl(metricName)).openConnection();
        urlConnection.connect();
        responseCode = urlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            fail("Could not load metric data from server: " + responseCode);
        }

        try (InputStream inputStream = urlConnection.getInputStream()) {
            TypeFactory typeFactory = objectMapper.getTypeFactory();
            CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricData.class);
            List<MetricData> data = objectMapper.readValue(inputStream, valueType);
            Stream<Point> metricPoints = data.stream()
                    .map(metricData -> new Point(type, metricData.timestamp, metricData.value));
            points = Stream.concat(points, metricPoints);
        }
    }

    return points.sorted(Comparator.comparing(Point::getType).thenComparing(Point::getTimestamp))
            .collect(toList());
}

From source file:org.flockdata.integration.FileProcessor.java

private int processJsonTags(String fileName) throws FlockException {
    Collection<TagInputBean> tags;
    ObjectMapper mapper = FdJsonObjectMapper.getObjectMapper();
    int processed = 0;
    try {//from  w  w  w  .  j  a  v a 2s . c o m
        File file = new File(fileName);
        InputStream stream = null;
        if (!file.exists()) {
            // Try as a resource
            stream = ClassLoader.class.getResourceAsStream(fileName);
            if (stream == null) {
                logger.error("{} does not exist", fileName);
                throw new FlockException(fileName + " Does not exist");
            }
        }
        TypeFactory typeFactory = mapper.getTypeFactory();
        CollectionType collType = typeFactory.constructCollectionType(ArrayList.class, TagInputBean.class);

        if (file.exists())
            tags = mapper.readValue(file, collType);
        else
            tags = mapper.readValue(stream, collType);
        for (TagInputBean tag : tags) {
            getPayloadWriter().writeTag(tag, "JSON Tag Importer");
            processed++;
        }

    } catch (IOException e) {
        logger.error("Error writing exceptions with {} [{}]", fileName, e.getMessage());
        throw new RuntimeException("IO Exception ", e);
    } finally {
        if (processed > 0L)
            getPayloadWriter().flush();

    }
    return tags.size();
}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

protected List<Resource> getResources(String path, int minCount, int attemptCount, long attemptDelay)
        throws Throwable {
    String url = baseInvUri + path;
    Throwable e = null;/*from w w w. j  ava 2 s .c  o  m*/
    for (int i = 0; i < attemptCount; i++) {
        try {
            String body = getWithRetries(url, attemptCount, attemptDelay);
            TypeFactory tf = mapper.getTypeFactory();
            JavaType listType = tf.constructCollectionType(ArrayList.class, Resource.class);
            JsonNode node = mapper.readTree(body);
            List<Resource> result = mapper.readValue(node.traverse(), listType);
            if (result.size() >= minCount) {
                return result;
            }
            System.out.println("Got only " + result.size() + " resources while expected " + minCount + " on "
                    + (i + 1) + " of " + attemptCount + " attempts for URL [" + url + "]");
            // System.out.println(body);
        } catch (Throwable t) {
            /* some initial attempts may fail */
            e = t;
            System.out.println("URL [" + url + "] not ready yet on " + (i + 1) + " of " + attemptCount
                    + " attempts, about to retry after " + attemptDelay + " ms");
        }
        Thread.sleep(attemptDelay);
    }
    if (e != null) {
        throw e;
    } else {
        throw new AssertionError("Could not get [" + url + "]");
    }
}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

protected OperationType getOperationType(String path, int attemptCount, long attemptDelay) throws Throwable {
    String url = baseInvUri + path;
    Throwable e = null;//from ww  w  .j  a v a 2  s.c  om
    int minCount = 1; // for now, we expect to retrieve only 1 type
    for (int i = 0; i < attemptCount; i++) {
        try {
            String body = getWithRetries(url, attemptCount, attemptDelay);
            TypeFactory tf = mapper.getTypeFactory();
            JavaType listType = tf.constructCollectionType(ArrayList.class, OperationType.class);
            JsonNode node = mapper.readTree(body);
            List<OperationType> result = mapper.readValue(node.traverse(), listType);
            if (result.size() >= minCount) {
                return result.get(0); // we assume we are just getting 1
            }
            System.out.println("Got only " + result.size() + " operation types while expected " + minCount
                    + " on " + (i + 1) + " of " + attemptCount + " attempts for URL [" + url + "]");
            // System.out.println(body);
        } catch (Throwable t) {
            /* some initial attempts may fail */
            e = t;
            System.out.println("URL [" + url + "] not ready yet on " + (i + 1) + " of " + attemptCount
                    + " attempts, about to retry after " + attemptDelay + " ms");
        }
        Thread.sleep(attemptDelay);
    }
    if (e != null) {
        throw e;
    } else {
        throw new AssertionError("Could not get [" + url + "]");
    }
}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

protected Resource getResource(String listPath, Predicate<Resource> predicate, int attemptCount,
        long attemptDelay) throws Throwable {
    String url = baseInvUri + listPath;
    Throwable e = null;//ww  w .j av  a2  s . c om
    for (int i = 0; i < attemptCount; i++) {
        try {
            String body = getWithRetries(url, attemptCount, attemptDelay);
            TypeFactory tf = mapper.getTypeFactory();
            JavaType listType = tf.constructCollectionType(ArrayList.class, Resource.class);
            JsonNode node = mapper.readTree(body);
            List<Resource> result = mapper.readValue(node.traverse(), listType);
            Optional<Resource> found = result.stream().filter(predicate).findFirst();
            if (found.isPresent()) {
                return found.get();
            }
            System.out.println("Could not find the right resource among " + result.size() + " resources on "
                    + (i + 1) + " of " + attemptCount + " attempts for URL [" + url + "]");
            // System.out.println(body);
        } catch (Throwable t) {
            /* some initial attempts may fail */
            e = t;
            System.out.println("URL [" + url + "] not ready yet on " + (i + 1) + " of " + attemptCount
                    + " attempts, about to retry after " + attemptDelay + " ms: " + t.getMessage());
        }
        Thread.sleep(attemptDelay);
    }
    if (e != null) {
        throw e;
    } else {
        throw new AssertionError("Could not get [" + url + "]");
    }
}

From source file:com.kaaprotech.satu.jackson.SatuTypeModifier.java

@SuppressWarnings("unused")
@Override/*from   www.  j a v a 2 s.  c o  m*/
public JavaType modifyType(JavaType type, Type jdkType, TypeBindings context, TypeFactory typeFactory) {
    final Class<?> raw = type.getRawClass();

    if (ImmutableMap.class.isAssignableFrom(raw)) {
        JavaType keyType = type.containedType(0);
        JavaType contentType = type.containedType(1);

        if (keyType == null) {
            keyType = TypeFactory.unknownType();
        }
        if (contentType == null) {
            contentType = TypeFactory.unknownType();
        }
        return typeFactory.constructMapType(AbstractImmutableMap.class, keyType, contentType);
    }

    if (ImmutableSet.class.isAssignableFrom(raw)) {
        JavaType contentType = type.containedType(0);

        if (contentType == null) {
            contentType = TypeFactory.unknownType();
        }
        return typeFactory.constructCollectionType(AbstractImmutableSet.class, contentType);
    }
    return type;
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

@Override
public <V, T> List<V> doGetToList(Class<T> clazz, String url, Map<String, String> parameters,
        Map<String, String> headers) throws JSONWebServiceInvocationException, JSONWebServiceSerializeException,
        JSONWebServiceTransportException {

    String json = doGet(url, parameters, headers);

    if (json == null) {
        return Collections.emptyList();
    }//w ww .  jav  a2  s  .co  m

    try {
        TypeFactory typeFactory = _objectMapper.getTypeFactory();

        List<V> list = new ArrayList<V>();

        JavaType javaType = typeFactory.constructCollectionType(list.getClass(), clazz);

        return _objectMapper.readValue(json, javaType);
    } catch (IOException ioe) {
        throw _getJSONWebServiceSerializeException(json, clazz);
    }
}

From source file:com.almende.eve.test.agents.Test2Agent.java

/**
 * Test tf complex result.//ww  w .  jav  a2s  .  c o  m
 * 
 * @param url
 *            the url
 * @return the double
 * @throws Exception
 *             the exception
 */
public Double testTFComplexResult(@Name("url") final String url) throws Exception {
    final TypeFactory tf = JOM.getTypeFactory();
    final Map<String, List<Double>> res = send(URI.create(url), "complexResult", JOM.createObjectNode(),
            tf.constructMapType(HashMap.class, JOM.getTypeFactory().constructType(String.class),
                    tf.constructCollectionType(List.class, Double.class)));
    return res.get("result").get(0);
}