Example usage for com.fasterxml.jackson.core JsonFactory JsonFactory

List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory JsonFactory.

Prototype

public JsonFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.LocationsTest.java

@Test
public void itGetsCachesForALocation() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/locations");

    CloseableHttpResponse response = null;
    try {//w w w . j  av a 2s  .co  m
        response = closeableHttpClient.execute(httpGet);

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        String location = jsonNode.get("locations").get(0).asText();

        httpGet = new HttpGet("http://localhost:3333/crs/locations/" + location + "/caches");

        response = closeableHttpClient.execute(httpGet);

        jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));

        assertThat(jsonNode.get("caches").isArray(), equalTo(true));
        JsonNode cacheNode = jsonNode.get("caches").get(0);

        assertThat(cacheNode.get("cacheId").asText(), not(equalTo("")));
        assertThat(cacheNode.get("fqdn").asText(), not(equalTo("")));

        assertThat(cacheNode.get("ipAddresses").isArray(), equalTo(true));
        assertThat(cacheNode.has("adminStatus"), equalTo(true));

        assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("lastUpdateTime").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("connections").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("currentBW").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("availBW").asInt(-123456), not(equalTo(-123456)));

        assertThat(cacheNode.get("cacheOnline").asText(), anyOf(equalTo("true"), equalTo("false")));
        assertThat(cacheNode.get("lastUpdateHealthy").asText(), anyOf(equalTo("true"), equalTo("false")));

    } finally {
        if (response != null)
            response.close();
    }
}

From source file:org.apache.olingo.commons.core.serialization.JsonSerializer.java

@SuppressWarnings("unchecked")
@Override//from   w  w  w  .  j a  va2  s. co m
public <T> void write(final Writer writer, final ResWrap<T> container) throws ODataSerializerException {
    final T obj = container == null ? null : container.getPayload();
    try {
        final JsonGenerator json = new JsonFactory().createGenerator(writer);
        if (obj instanceof EntitySet) {
            new JsonEntitySetSerializer(version, serverMode)
                    .doContainerSerialize((ResWrap<EntitySet>) container, json);
        } else if (obj instanceof Entity) {
            new JsonEntitySerializer(version, serverMode).doContainerSerialize((ResWrap<Entity>) container,
                    json);
        } else if (obj instanceof Property) {
            new JsonPropertySerializer(version, serverMode).doContainerSerialize((ResWrap<Property>) container,
                    json);
        } else if (obj instanceof Link) {
            link((Link) obj, json);
        }
        json.flush();
    } catch (final IOException e) {
        throw new ODataSerializerException(e);
    } catch (final EdmPrimitiveTypeException e) {
        throw new ODataSerializerException(e);
    }
}

From source file:com.googlecode.jmxtrans.model.output.kafka.KafkaWriter.java

@JsonCreator
public KafkaWriter(@JsonProperty("typeNames") ImmutableList<String> typeNames,
        @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("rootPrefix") String rootPrefix,
        @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("topics") String topics,
        @JsonProperty("tags") Map<String, String> tags,
        @JsonProperty("settings") Map<String, Object> settings) {
    super(typeNames, booleanAsNumber, debugEnabled, settings);
    this.rootPrefix = firstNonNull(rootPrefix, (String) getSettings().get("rootPrefix"), DEFAULT_ROOT_PREFIX);
    // Setting all the required Kafka Properties
    Properties kafkaProperties = new Properties();
    kafkaProperties.setProperty("metadata.broker.list",
            Settings.getStringSetting(settings, "metadata.broker.list", null));
    kafkaProperties.setProperty("zk.connect", Settings.getStringSetting(settings, "zk.connect", null));
    kafkaProperties.setProperty("serializer.class",
            Settings.getStringSetting(settings, "serializer.class", null));
    this.producer = new Producer<>(new ProducerConfig(kafkaProperties));
    this.topics = asList(Settings.getStringSetting(settings, "topics", "").split(","));
    this.tags = ImmutableMap.copyOf(firstNonNull(tags, (Map<String, String>) getSettings().get("tags"),
            ImmutableMap.<String, String>of()));
    jsonFactory = new JsonFactory();
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.RouterTest.java

@Before
public void before() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }//www. j a v a2  s.c  om

    Set<String> steeringDeliveryServices = new HashSet<String>();
    JsonNode steeringData = objectMapper.readTree(inputStream).get("response");
    Iterator<JsonNode> elements = steeringData.elements();

    while (elements.hasNext()) {
        JsonNode ds = elements.next();
        String dsId = ds.get("deliveryService").asText();
        steeringDeliveryServices.add(dsId);
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext()) {
        String dsId = deliveryServices.next();

        if (steeringDeliveryServices.contains(dsId)) {
            continue;
        }

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);
        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();

        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                final boolean sslEnabled = JsonUtils.optBoolean(deliveryServiceNode, "sslEnabled");
                if (!sslEnabled) {
                    deliveryServiceId = dsId;
                    deliveryServiceDomain = deliveryServiceNode.get("domains").get(0).asText();
                }
            }
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(deliveryServiceDomain, not(nullValue()));
    assertThat(httpsOnlyId, not(nullValue()));
    assertThat(httpsOnlyDomain, not(nullValue()));

    Iterator<String> cacheIds = jsonNode.get("contentServers").fieldNames();
    while (cacheIds.hasNext()) {
        String cacheId = cacheIds.next();
        JsonNode cacheNode = jsonNode.get("contentServers").get(cacheId);

        if (!cacheNode.has("deliveryServices")) {
            continue;
        }

        if (cacheNode.get("deliveryServices").has(deliveryServiceId)) {
            int port = cacheNode.get("port").asInt();
            String portText = (port == 80) ? "" : ":" + port;
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78&format=json");
        }

        if (cacheNode.get("deliveryServices").has(httpsOnlyId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsOnlyLocations.add("https://" + cacheId + "." + httpsOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpsNoCertsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsNoCertsLocations.add("https://" + cacheId + "." + httpsNoCertsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpAndHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpAndHttpsLocations.add("https://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");

            port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;
            portText = (port == 80) ? "" : ":" + port;
            httpAndHttpsLocations.add("http://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpToHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpToHttpsLocations.add("https://" + cacheId + "." + httpToHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpOnlyId)) {
            int port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;

            String portText = (port == 80) ? "" : ":" + port;
            httpOnlyLocations.add("http://" + cacheId + "." + httpOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }
    }

    assertThat(validLocations.isEmpty(), equalTo(false));
    assertThat(httpsOnlyLocations.isEmpty(), equalTo(false));

    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream("keystore.jks");
    trustStore.load(keystoreStream, "changeit".toCharArray());
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).init(trustStore);

    httpClient = HttpClientBuilder.create()
            .setSSLSocketFactory(new ClientSslSocketFactory("tr.https-only-test.thecdn.example.com"))
            .setSSLHostnameVerifier(new TestHostnameVerifier()).disableRedirectHandling().build();

}

From source file:nl.esciencecenter.xnatclient.data.XnatParser.java

/**
 * Xnat Rest Query has a diferrent Json Tree. Parse structure
 * /*from  ww w . ja v  a  2s.  c o m*/
 * @throws XnatParseException
 */
public static int parseJsonQueryResult(XnatObjectType type, String jsonStr, List list)
        throws XnatParseException {
    if (StringUtil.isEmpty(jsonStr))
        return 0;

    try {
        JsonFactory jsonFac = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper();

        // use dom like parsing:
        JsonNode tree = mapper.readTree(jsonStr);

        JsonNode items = tree.get("items");

        if (items == null) {
            logger.warnPrintf("Couldn't find 'items' in jsonTree\n");
            return 0;
        }

        // parse objects:
        JsonNode node = null;
        Iterator<JsonNode> els = items.elements();
        int index = 0;
        while (els.hasNext()) {
            logger.debugPrintf(" - item[%d]\n", index++);
            JsonNode el = els.next();
            node = el.get("data_fields");
            if (node != null)
                list.add(parseXnatObject(type, node));
            else
                logger.warnPrintf("jsonNode doesn't have 'data_fields' element:%s", el);
        }
    }
    // wrap exception:
    catch (JsonParseException e) {
        throw new XnatParseException("JsonParseException:" + e.getMessage(), e);
    } catch (IOException e) {
        throw new XnatParseException("IOException:" + e.getMessage(), e);
    }

    return list.size();
}

From source file:de.qaware.cloud.deployer.kubernetes.resource.replication.controller.ReplicationControllerResourceTest.java

@Test
public void testDelete()
        throws ResourceException, InterruptedException, TimeoutException, JsonProcessingException {
    String scenarioName = "testDelete";

    // Scale pods down
    instanceRule.stubFor(put(SCALE_PATTERN).inScenario(scenarioName).whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withStatus(200)).willSetStateTo("scaledDown"));

    // Delete replication controller
    instanceRule.stubFor(delete(REPLICATION_CONTROLLER_PATTERN).inScenario(scenarioName)
            .whenScenarioStateIs("scaledDown").willReturn(aResponse().withStatus(200))
            .willSetStateTo("replicationControllerHalfDeleted"));

    // Simulate deleting
    instanceRule.stubFor(get(REPLICATION_CONTROLLER_PATTERN).inScenario(scenarioName)
            .whenScenarioStateIs("replicationControllerHalfDeleted").willReturn(aResponse().withStatus(200))
            .willSetStateTo("replicationControllerDeleted"));

    // Deleted replicationController
    instanceRule.stubFor(get(REPLICATION_CONTROLLER_PATTERN).inScenario(scenarioName)
            .whenScenarioStateIs("replicationControllerDeleted").willReturn(aResponse().withStatus(404)));

    // Test/*w w w  . ja  v  a2s . com*/
    resource.delete();

    // Verify calls
    instanceRule.verify(1, putRequestedFor(SCALE_PATTERN));
    instanceRule.verify(1, deleteRequestedFor(REPLICATION_CONTROLLER_PATTERN));
    instanceRule.verify(2, getRequestedFor(REPLICATION_CONTROLLER_PATTERN));

    // Check if delete options are specified
    String jsonDeleteOptions = new ObjectMapper(new JsonFactory()).writeValueAsString(new DeleteOptions(0));
    instanceRule.verify(
            deleteRequestedFor(REPLICATION_CONTROLLER_PATTERN).withRequestBody(equalTo(jsonDeleteOptions)));
}

From source file:me.tfeng.toolbox.dust.NodeEngine.java

private boolean isRegistered(Process process, String template) throws IOException {
    PrintWriter writer = new PrintWriter(process.getOutputStream());
    writer.println("[");
    printIsRegisteredExpression(writer, template);
    writer.println("]");
    writer.println("1");
    writer.flush();//from   w  w w  .j av a 2  s  . c o  m

    String result = readInput(process, "1");
    JsonParser parser = new JsonFactory().createParser(result).configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,
            true);
    ArrayNode arrayNode = OBJECT_MAPPER.readValue(parser, ArrayNode.class);
    return arrayNode.get(0).booleanValue();
}

From source file:msearch.filmlisten.MSFilmlisteLesen.java

public void readFilmListe(String source, final ListeFilme listeFilme, int days) {
    JsonToken jsonToken;/*from  ww w .j a  v a2s  . c  om*/
    String sender = "", thema = "";
    listeFilme.clear();
    this.notifyStart(source, PROGRESS_MAX); // fr die Progressanzeige

    if (days > 0) {
        final long maxDays = 1000L * 60L * 60L * 24L * days;
        seconds = new Date().getTime() - maxDays;
    } else {
        seconds = 0;
    }

    try {
        InputStream in = selectDecompressor(source, getInputStreamForLocation(source));
        JsonParser jp = new JsonFactory().createParser(in);
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IllegalStateException("Expected data to start with an Object");
        }

        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                for (int k = 0; k < ListeFilme.MAX_ELEM; ++k) {
                    listeFilme.metaDaten[k] = jp.nextTextValue();
                }
                break;
            }
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                // sind nur die Feldbeschreibungen, brauch mer nicht
                jp.nextToken();
                break;
            }
        }
        while (!MSConfig.getStop() && (jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                DatenFilm datenFilm = new DatenFilm();
                for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                    //if we are in FASTAUTO mode, we dont need film descriptions.
                    //this should speed up loading on low end devices...
                    if (workMode == WorkMode.FASTAUTO) {
                        if (DatenFilm.COLUMN_NAMES_JSON[i] == DatenFilm.FILM_BESCHREIBUNG_NR
                                || DatenFilm.COLUMN_NAMES_JSON[i] == DatenFilm.FILM_WEBSEITE_NR
                                || DatenFilm.COLUMN_NAMES_JSON[i] == DatenFilm.FILM_GEO_NR) {
                            jp.nextToken();
                            continue;
                        }
                    }

                    datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = jp.nextTextValue();
                    /// fr die Entwicklungszeit
                    if (datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] == null) {
                        datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = "";
                    }
                }
                if (datenFilm.arr[DatenFilm.FILM_SENDER_NR].isEmpty()) {
                    datenFilm.arr[DatenFilm.FILM_SENDER_NR] = sender;
                } else {
                    sender = datenFilm.arr[DatenFilm.FILM_SENDER_NR];
                }
                if (datenFilm.arr[DatenFilm.FILM_THEMA_NR].isEmpty()) {
                    datenFilm.arr[DatenFilm.FILM_THEMA_NR] = thema;
                } else {
                    thema = datenFilm.arr[DatenFilm.FILM_THEMA_NR];
                }

                listeFilme.importFilmliste(datenFilm);
                if (seconds > 0) {
                    // muss "rckwrts" laufen, da das Datum sonst 2x gebaut werden muss
                    // wenns drin bleibt, kann mans noch ndern
                    if (!checkDate(datenFilm)) {
                        listeFilme.remove(datenFilm);
                    }
                }
            }
        }
    } catch (FileNotFoundException ex) {
        listeFilme.clear();
    } catch (Exception ex) {
        MSLog.fehlerMeldung(945123641, MSLog.FEHLER_ART_PROG,
                "MSearchIoXmlFilmlisteLesen.readFilmListe: " + source, ex);
        listeFilme.clear();
    }
    if (MSConfig.getStop()) {
        listeFilme.clear();
    }
    notifyFertig(source, listeFilme);
}

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

@Test
public void testJsonFactory() {
    assertThat(OpenRtbJsonFactory.create().getJsonFactory()).isNotNull();
    JsonFactory jf = new JsonFactory();
    assertThat(OpenRtbJsonFactory.create().setJsonFactory(jf).getJsonFactory()).isSameAs(jf);
    TestUtil.testCommonMethods(new Test2Reader<BidRequest.Builder>(TestExt.testRequest2, "x"));
    TestUtil.testCommonMethods(new Test4Writer());
}

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

/**
 * Begins parsing a JSON stream into a tree structure. The JsonValue object
 * created contains the value at the root of the tree.
 * //w ww . j av  a 2s. c om
 * This constructor will block until the first JSON token is received. To
 * continue building the tree, the "build" method (inherited from
 * JsonBuffered) must be called in another thread.
 * 
 * @param source
 *         The source of incoming JSON data.
 * @throws java.io.IOException
 */
public JsonValue(final String source) throws IOException {
    this(new JsonFactory().createParser(source));
}