Search in sources :

Example 26 with TypeReference

use of org.codehaus.jackson.type.TypeReference in project crate by crate.

the class PingTaskTest method testUnsuccessfulPingTaskRun.

@Test
public void testUnsuccessfulPingTaskRun() throws Exception {
    testServer = new HttpTestServer(18081, true);
    testServer.run();
    PingTask task = new PingTask(clusterService, clusterIdService, extendedNodeInfo, "http://localhost:18081/", Settings.EMPTY);
    task.run();
    assertThat(testServer.responses.size(), is(1));
    task.run();
    assertThat(testServer.responses.size(), is(2));
    for (long i = 0; i < testServer.responses.size(); i++) {
        String json = testServer.responses.get((int) i);
        Map<String, String> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            //convert JSON string to Map
            map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        assertThat(map, hasKey("kernel"));
        assertThat(map.get("kernel"), is(notNullValue()));
        assertThat(map, hasKey("cluster_id"));
        assertThat(map.get("cluster_id"), is(notNullValue()));
        assertThat(map, hasKey("master"));
        assertThat(map.get("master"), is(notNullValue()));
        assertThat(map, hasKey("ping_count"));
        assertThat(map.get("ping_count"), is(notNullValue()));
        Map<String, Long> pingCountMap;
        pingCountMap = mapper.readValue(map.get("ping_count"), new TypeReference<Map<String, Long>>() {
        });
        assertThat(pingCountMap.get("success"), is(0L));
        assertThat(pingCountMap.get("failure"), is(i));
        if (task.getHardwareAddress() != null) {
            assertThat(map, hasKey("hardware_address"));
            assertThat(map.get("hardware_address"), is(notNullValue()));
        }
        assertThat(map, hasKey("crate_version"));
        assertThat(map.get("crate_version"), is(notNullValue()));
        assertThat(map, hasKey("java_version"));
        assertThat(map.get("java_version"), is(notNullValue()));
    }
}
Also used : HashMap(java.util.HashMap) HttpTestServer(io.crate.http.HttpTestServer) TypeReference(org.codehaus.jackson.type.TypeReference) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Example 27 with TypeReference

use of org.codehaus.jackson.type.TypeReference in project voldemort by voldemort.

the class RestUtils method deserializeVectorClocks.

public static List<Version> deserializeVectorClocks(String serializedVC) {
    Set<VectorClockWrapper> vectorClockWrappers = null;
    List<Version> vectorClocks = null;
    if (serializedVC == null) {
        return null;
    }
    try {
        vectorClockWrappers = mapper.readValue(serializedVC, new TypeReference<Set<VectorClockWrapper>>() {
        });
        if (vectorClockWrappers.size() > 0) {
            vectorClocks = new ArrayList<Version>();
        }
        for (VectorClockWrapper vectorClockWrapper : vectorClockWrappers) {
            vectorClocks.add(new VectorClock(vectorClockWrapper.getVersions(), vectorClockWrapper.getTimestamp()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return vectorClocks;
}
Also used : Version(voldemort.versioning.Version) VectorClock(voldemort.versioning.VectorClock) TypeReference(org.codehaus.jackson.type.TypeReference) IOException(java.io.IOException) MappingException(voldemort.xml.MappingException) JDOMException(org.jdom.JDOMException)

Example 28 with TypeReference

use of org.codehaus.jackson.type.TypeReference in project samza by apache.

the class TestCoordinatorStreamWriter method testSendMessage.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void testSendMessage() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    //check a correct message
    assertEquals(0, systemProducer.getEnvelopes().size());
    coordinatorStreamWriter.sendMessage("set-config", "key0", "value0");
    assertEquals(1, systemProducer.getEnvelopes().size());
    //check invalid input is handled
    boolean exceptionHappened = false;
    try {
        coordinatorStreamWriter.sendMessage("invalid-type", "key-invalid", "value-invalid");
    } catch (IllegalArgumentException e) {
        exceptionHappened = true;
    }
    assertTrue(exceptionHappened);
    assertEquals(1, systemProducer.getEnvelopes().size());
    //check sendSetConfigMessage method works correctly
    Class[] sendArgs = { String.class, String.class };
    Method sendSetConfigMethod = coordinatorStreamWriter.getClass().getDeclaredMethod("sendSetConfigMessage", sendArgs);
    sendSetConfigMethod.setAccessible(true);
    sendSetConfigMethod.invoke(coordinatorStreamWriter, "key1", "value1");
    assertEquals(2, systemProducer.getEnvelopes().size());
    //check the messages are correct
    List<OutgoingMessageEnvelope> envelopes = systemProducer.getEnvelopes();
    OutgoingMessageEnvelope envelope0 = envelopes.get(0);
    OutgoingMessageEnvelope envelope1 = envelopes.get(1);
    TypeReference<Object[]> keyRef = new TypeReference<Object[]>() {
    };
    TypeReference<Map<String, Object>> msgRef = new TypeReference<Map<String, Object>>() {
    };
    assertEquals(2, envelopes.size());
    assertEquals("key0", deserialize((byte[]) envelope0.getKey(), keyRef)[CoordinatorStreamMessage.KEY_INDEX]);
    Map<String, String> values = (Map<String, String>) deserialize((byte[]) envelope0.getMessage(), msgRef).get("values");
    assertEquals("value0", values.get("value"));
    assertEquals("key1", deserialize((byte[]) envelope1.getKey(), keyRef)[CoordinatorStreamMessage.KEY_INDEX]);
    values = (Map<String, String>) deserialize((byte[]) envelope1.getMessage(), msgRef).get("values");
    assertEquals("value1", values.get("value"));
}
Also used : Method(java.lang.reflect.Method) TypeReference(org.codehaus.jackson.type.TypeReference) OutgoingMessageEnvelope(org.apache.samza.system.OutgoingMessageEnvelope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 29 with TypeReference

use of org.codehaus.jackson.type.TypeReference in project samza by apache.

the class SamzaObjectMapper method getObjectMapper.

/**
   * @return Returns a new ObjectMapper that's been configured to (de)serialize
   *         Samza's job data model, and simple data types such as TaskName,
   *         Partition, Config, and SystemStreamPartition.
   */
public static ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("SamzaModule", new Version(1, 0, 0, ""));
    // Setup custom serdes for simple data types.
    module.addSerializer(Partition.class, new PartitionSerializer());
    module.addSerializer(SystemStreamPartition.class, new SystemStreamPartitionSerializer());
    module.addKeySerializer(SystemStreamPartition.class, new SystemStreamPartitionKeySerializer());
    module.addSerializer(TaskName.class, new TaskNameSerializer());
    module.addDeserializer(Partition.class, new PartitionDeserializer());
    module.addDeserializer(SystemStreamPartition.class, new SystemStreamPartitionDeserializer());
    module.addKeyDeserializer(SystemStreamPartition.class, new SystemStreamPartitionKeyDeserializer());
    module.addDeserializer(Config.class, new ConfigDeserializer());
    // Setup mixins for data models.
    mapper.getSerializationConfig().addMixInAnnotations(TaskModel.class, JsonTaskModelMixIn.class);
    mapper.getDeserializationConfig().addMixInAnnotations(TaskModel.class, JsonTaskModelMixIn.class);
    mapper.getSerializationConfig().addMixInAnnotations(ContainerModel.class, JsonContainerModelMixIn.class);
    mapper.getSerializationConfig().addMixInAnnotations(JobModel.class, JsonJobModelMixIn.class);
    mapper.getDeserializationConfig().addMixInAnnotations(JobModel.class, JsonJobModelMixIn.class);
    module.addDeserializer(ContainerModel.class, new JsonDeserializer<ContainerModel>() {

        @Override
        public ContainerModel deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            ObjectCodec oc = jp.getCodec();
            JsonNode node = oc.readTree(jp);
            int containerId = node.get("container-id").getIntValue();
            if (node.get("container-id") == null) {
                throw new SamzaException("JobModel did not contain a container-id. This can never happen. JobModel corrupt!");
            }
            String processorId;
            if (node.get("processor-id") == null) {
                processorId = String.valueOf(containerId);
            } else {
                processorId = node.get("processor-id").getTextValue();
            }
            Map<TaskName, TaskModel> tasksMapping = OBJECT_MAPPER.readValue(node.get("tasks"), new TypeReference<Map<TaskName, TaskModel>>() {
            });
            return new ContainerModel(processorId, containerId, tasksMapping);
        }
    });
    // Convert camel case to hyphenated field names, and register the module.
    mapper.setPropertyNamingStrategy(new CamelCaseToDashesStrategy());
    mapper.registerModule(module);
    return mapper;
}
Also used : JsonNode(org.codehaus.jackson.JsonNode) ObjectCodec(org.codehaus.jackson.ObjectCodec) SamzaException(org.apache.samza.SamzaException) ContainerModel(org.apache.samza.job.model.ContainerModel) Version(org.codehaus.jackson.Version) DeserializationContext(org.codehaus.jackson.map.DeserializationContext) TypeReference(org.codehaus.jackson.type.TypeReference) JsonProcessingException(org.codehaus.jackson.JsonProcessingException) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) JsonParser(org.codehaus.jackson.JsonParser) IOException(java.io.IOException) TaskName(org.apache.samza.container.TaskName) HashMap(java.util.HashMap) Map(java.util.Map) SimpleModule(org.codehaus.jackson.map.module.SimpleModule) TaskModel(org.apache.samza.job.model.TaskModel)

Aggregations

TypeReference (org.codehaus.jackson.type.TypeReference)29 IOException (java.io.IOException)16 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)11 JsonMappingException (org.codehaus.jackson.map.JsonMappingException)10 JsonParseException (org.codehaus.jackson.JsonParseException)9 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 InputStreamReader (java.io.InputStreamReader)4 HashMap (java.util.HashMap)4 HttpResponse (org.apache.http.HttpResponse)4 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 HttpClient (org.apache.http.client.HttpClient)4 HttpGet (org.apache.http.client.methods.HttpGet)3 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)3 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)3 File (java.io.File)2 List (java.util.List)2 Test (org.junit.Test)2 Activate (aQute.bnd.annotation.component.Activate)1 BlogSearchJson (cn.eoe.app.entity.BlogSearchJson)1