org.codehaus.jackson.map.ObjectReader Java Examples

The following examples show how to use org.codehaus.jackson.map.ObjectReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestJsonUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testHdfsFileStatus() throws IOException {
  final long now = Time.now();
  final String parent = "/dir";
  final HdfsFileStatus status = new HdfsFileStatus(1001L, false, 3, 1L << 26,
      now, now + 10, new FsPermission((short) 0644), "user", "group",
      DFSUtil.string2Bytes("bar"), DFSUtil.string2Bytes("foo"),
      INodeId.GRANDFATHER_INODE_ID, 0, null, (byte) 0);
  final FileStatus fstatus = toFileStatus(status, parent);
  System.out.println("status  = " + status);
  System.out.println("fstatus = " + fstatus);
  final String json = JsonUtil.toJsonString(status, true);
  System.out.println("json    = " + json.replace(",", ",\n  "));
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  final HdfsFileStatus s2 =
      JsonUtil.toFileStatus((Map<?, ?>) reader.readValue(json), true);
  final FileStatus fs2 = toFileStatus(s2, parent);
  System.out.println("s2      = " + s2);
  System.out.println("fs2     = " + fs2);
  Assert.assertEquals(fstatus, fs2);
}
 
Example #2
Source File: TestInputLoader.java    From helix with Apache License 2.0 6 votes vote down vote up
public static Object[][] loadTestInputs(String inputFile, String[] params) {
  List<Object[]> data = new ArrayList<Object[]>();
  InputStream inputStream = TestInputLoader.class.getClassLoader().getResourceAsStream(inputFile);
  try {
    ObjectReader mapReader = new ObjectMapper().reader(Map[].class);
    Map[] inputs = mapReader.readValue(inputStream);

    for (Map input : inputs) {
      Object[] objects = new Object[params.length];
      for (int i = 0; i < params.length; i++) {
        objects[i] = input.get(params[i]);
      }
      data.add(objects);
    }
  } catch (IOException e) {
    e.printStackTrace();
  }

  Object[][] ret = new Object[data.size()][];
  for(int i = 0; i < data.size(); i++) {
    ret[i] = data.get(i);
  }
  return ret;
}
 
Example #3
Source File: TestJsonUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testToXAttrMap() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);
  XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build();
  XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build();
  List<XAttr> xAttrs = Lists.newArrayList();
  xAttrs.add(xAttr1);
  xAttrs.add(xAttr2);
  Map<String, byte[]> xAttrMap = XAttrHelper.buildXAttrMap(xAttrs);
  Map<String, byte[]> parsedXAttrMap = JsonUtil.toXAttrs(json);
  
  Assert.assertEquals(xAttrMap.size(), parsedXAttrMap.size());
  Iterator<Entry<String, byte[]>> iter = xAttrMap.entrySet().iterator();
  while(iter.hasNext()) {
    Entry<String, byte[]> entry = iter.next();
    Assert.assertArrayEquals(entry.getValue(), 
        parsedXAttrMap.get(entry.getKey()));
  }
}
 
Example #4
Source File: TestJsonUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testToAclStatus() throws IOException {
  String jsonString =
      "{\"AclStatus\":{\"entries\":[\"user::rwx\",\"user:user1:rw-\",\"group::rw-\",\"other::r-x\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  List<AclEntry> aclSpec =
      Lists.newArrayList(aclEntry(ACCESS, USER, ALL),
          aclEntry(ACCESS, USER, "user1", READ_WRITE),
          aclEntry(ACCESS, GROUP, READ_WRITE),
          aclEntry(ACCESS, OTHER, READ_EXECUTE));

  AclStatus.Builder aclStatusBuilder = new AclStatus.Builder();
  aclStatusBuilder.owner("testuser");
  aclStatusBuilder.group("supergroup");
  aclStatusBuilder.addEntries(aclSpec);
  aclStatusBuilder.stickyBit(false);

  Assert.assertEquals("Should be equal", aclStatusBuilder.build(),
      JsonUtil.toAclStatus(json));
}
 
Example #5
Source File: JsonUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
Example #6
Source File: TestJsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testToXAttrMap() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);
  XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build();
  XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build();
  List<XAttr> xAttrs = Lists.newArrayList();
  xAttrs.add(xAttr1);
  xAttrs.add(xAttr2);
  Map<String, byte[]> xAttrMap = XAttrHelper.buildXAttrMap(xAttrs);
  Map<String, byte[]> parsedXAttrMap = JsonUtil.toXAttrs(json);
  
  Assert.assertEquals(xAttrMap.size(), parsedXAttrMap.size());
  Iterator<Entry<String, byte[]>> iter = xAttrMap.entrySet().iterator();
  while(iter.hasNext()) {
    Entry<String, byte[]> entry = iter.next();
    Assert.assertArrayEquals(entry.getValue(), 
        parsedXAttrMap.get(entry.getKey()));
  }
}
 
Example #7
Source File: TestJsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testToAclStatus() throws IOException {
  String jsonString =
      "{\"AclStatus\":{\"entries\":[\"user::rwx\",\"user:user1:rw-\",\"group::rw-\",\"other::r-x\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  List<AclEntry> aclSpec =
      Lists.newArrayList(aclEntry(ACCESS, USER, ALL),
          aclEntry(ACCESS, USER, "user1", READ_WRITE),
          aclEntry(ACCESS, GROUP, READ_WRITE),
          aclEntry(ACCESS, OTHER, READ_EXECUTE));

  AclStatus.Builder aclStatusBuilder = new AclStatus.Builder();
  aclStatusBuilder.owner("testuser");
  aclStatusBuilder.group("supergroup");
  aclStatusBuilder.addEntries(aclSpec);
  aclStatusBuilder.stickyBit(false);

  Assert.assertEquals("Should be equal", aclStatusBuilder.build(),
      JsonUtil.toAclStatus(json));
}
 
Example #8
Source File: TestJsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testHdfsFileStatus() throws IOException {
  final long now = Time.now();
  final String parent = "/dir";
  final HdfsFileStatus status = new HdfsFileStatus(1001L, false, 3, 1L << 26,
      now, now + 10, new FsPermission((short) 0644), "user", "group",
      DFSUtil.string2Bytes("bar"), DFSUtil.string2Bytes("foo"),
      INodeId.GRANDFATHER_INODE_ID, 0, null, (byte) 0);
  final FileStatus fstatus = toFileStatus(status, parent);
  System.out.println("status  = " + status);
  System.out.println("fstatus = " + fstatus);
  final String json = JsonUtil.toJsonString(status, true);
  System.out.println("json    = " + json.replace(",", ",\n  "));
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  final HdfsFileStatus s2 =
      JsonUtil.toFileStatus((Map<?, ?>) reader.readValue(json), true);
  final FileStatus fs2 = toFileStatus(s2, parent);
  System.out.println("s2      = " + s2);
  System.out.println("fs2     = " + fs2);
  Assert.assertEquals(fstatus, fs2);
}
 
Example #9
Source File: JsonUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
Example #10
Source File: TestJsonUtil.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetXAttrFromJson() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  // Get xattr: user.a2
  byte[] value = JsonUtil.getXAttr(json, "user.a2");
  Assert.assertArrayEquals(XAttrCodec.decodeValue("0x313131"), value);
}
 
Example #11
Source File: StringCodec.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public T fromString(String string)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectReader reader = mapper.reader(clazz);
    return reader.readValue(string);
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #12
Source File: Directive.java    From dcs-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Directive deserialize(JsonParser jp, DeserializationContext ctx)
        throws IOException {
    ObjectReader reader = ObjectMapperUtil.instance().getObjectReader();
    ObjectNode obj = (ObjectNode) reader.readTree(jp);
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = obj.getFields();

    String rawMessage = obj.toString();
    DialogRequestIdHeader header = null;
    JsonNode payloadNode = null;
    ObjectReader headerReader =
            ObjectMapperUtil.instance().getObjectReader(DialogRequestIdHeader.class);
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        if (element.getKey().equals("header")) {
            header = headerReader.readValue(element.getValue());
        }
        if (element.getKey().equals("payload")) {
            payloadNode = element.getValue();
        }
    }
    if (header == null) {
        throw ctx.mappingException("Missing header");
    }
    if (payloadNode == null) {
        throw ctx.mappingException("Missing payload");
    }

    return createDirective(header, payloadNode, rawMessage);
}
 
Example #13
Source File: TestJsonUtil.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetXAttrFromJson() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  // Get xattr: user.a2
  byte[] value = JsonUtil.getXAttr(json, "user.a2");
  Assert.assertArrayEquals(XAttrCodec.decodeValue("0x313131"), value);
}
 
Example #14
Source File: StringCodec.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public T fromString(String string)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectReader reader = mapper.reader(clazz);
    return reader.readValue(string);
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #15
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
JacksonInstanceSerializer(ObjectReader objectReader, ObjectWriter objectWriter,
    TypeReference<ServiceInstance<T>> typeRef)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
  this.typeRef = typeRef;
}
 
Example #16
Source File: StateTransitionThrottleConfig.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiate a throttle config from a config JSON string.
 * @param configJsonStr
 * @return StateTransitionThrottleConfig or null if the given configs map is not a valid
 *         StateTransitionThrottleConfig.
 */
public static StateTransitionThrottleConfig fromJSON(String configJsonStr) {
  StateTransitionThrottleConfig throttleConfig = null;
  try {
    ObjectReader objectReader = OBJECT_MAPPER.reader(Map.class);
    Map<String, String> configsMap = objectReader.readValue(configJsonStr);
    throttleConfig = fromConfigMap(configsMap);
  } catch (IOException e) {
    logger.error("Failed to convert JSON string to config map! {}", configJsonStr);
  }

  return throttleConfig;
}
 
Example #17
Source File: TestRecoveryLoadBalance.java    From helix with Apache License 2.0 5 votes vote down vote up
public List<Object[]> loadTestInputs(String fileName) {
  List<Object[]> ret = new ArrayList<>();
  InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
  try {
    ObjectReader mapReader = new ObjectMapper().reader(List.class);
    List<Map<String, Object>> inputList = mapReader.readValue(inputStream);
    for (Map<String, Object> inputMap : inputList) {
      String stateModelName = (String) inputMap.get(STATE_MODEL);
      int threshold = (int) inputMap.get(ERROR_OR_RECOVERY_PARTITION_THRESHOLD);
      int minActiveReplicas = -1;
      if (inputMap.get(MIN_ACTIVE_REPLICAS) != null) {
        minActiveReplicas = Integer.parseInt(inputMap.get(MIN_ACTIVE_REPLICAS).toString());
      }
      int loadBalanceThrottle = -1;
      if (inputMap.get(LOAD_BALANCE_THROTTLE) != null) {
        loadBalanceThrottle = Integer.parseInt(inputMap.get(LOAD_BALANCE_THROTTLE).toString());
      }
      Map<String, Map<String, Map<String, String>>> stateMapping =
          (Map<String, Map<String, Map<String, String>>>) inputMap.get(INPUT);
      ret.add(new Object[] {
          stateModelName, threshold, stateMapping, minActiveReplicas, loadBalanceThrottle
      });
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return ret;
}
 
Example #18
Source File: ObjectMapperUtil.java    From dcs-sdk-java with Apache License 2.0 4 votes vote down vote up
public ObjectReader getObjectReader(Class<?> clazz) {
    return objectMapper.reader().withType(clazz);
}
 
Example #19
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
InstanceSerializerFactory(ObjectReader objectReader, ObjectWriter objectWriter)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
}
 
Example #20
Source File: TestZeroReplicaAvoidance.java    From helix with Apache License 2.0 4 votes vote down vote up
public List<Object[]> loadTestInputs(String fileName) {
  List<Object[]> ret = null;
  InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
  try {
    ObjectReader mapReader = new ObjectMapper().reader(Map.class);
    Map<String, Object> inputMaps = mapReader.readValue(inputStream);
    String stateModelName = (String) inputMaps.get(STATE_MODEL);

    StateModelDefinition stateModelDef =
        BuiltInStateModelDefinitions.valueOf(stateModelName).getStateModelDefinition();

    List<Map<String, Object>> inputs = (List<Map<String, Object>>) inputMaps.get(INPUT);
    ret = new ArrayList<>();
    for (Map<String, Object> inMap : inputs) {
      Map<String, String> currentStates = (Map<String, String>) inMap.get(CURRENT_STATE);
      Map<String, String> bestPossibleStates =
          (Map<String, String>) inMap.get(BEST_POSSIBLE_STATE);
      List<String> preferenceList = (List<String>) inMap.get(PREFERENCE_LIST);
      Map<String, String> pendingStates = (Map<String, String>) inMap.get(PENDING_MESSAGES);
      Map<String, List<Message>> pendingMessages = null;
      if (pendingStates != null) {
        Random r = new Random();
        pendingMessages = new HashMap<>();
        for (String instance : pendingStates.keySet()) {
          pendingMessages.put(instance, new ArrayList<>());
          Message m = new Message(new ZNRecord(UUID.randomUUID().toString()));
          m.setFromState(pendingStates.get(instance).split(":")[0]);
          m.setToState(pendingStates.get(instance).split(":")[1]);
          pendingMessages.get(instance).add(m);
        }
      }

      ret.add(new Object[] {
          stateModelDef, preferenceList, currentStates, pendingMessages, bestPossibleStates
      });
    }
  } catch (IOException e) {
    e.printStackTrace();
  }

  return ret;
}
 
Example #21
Source File: ObjectMapperUtil.java    From dcs-sdk-java with Apache License 2.0 4 votes vote down vote up
public ObjectReader getObjectReader() {
    return objectMapper.reader();
}