@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); }
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; }
@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); }
@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)); }
@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())); } }
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; }
@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"), HdfsConstants.GRANDFATHER_INODE_ID, 0, null, (byte) 0, null); 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 = JsonUtilClient.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); }
@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(), JsonUtilClient.toAclStatus(json)); }
@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 = JsonUtilClient.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())); } }
/** * Constructs the object based on the content as a List, the JSON can be an array or just a single value without the [] symbols * @param content Reader * @return A collection of the specified type * @throws IOException */ public <T> List<T> constructList(Reader content, Class<T> requiredType) throws IOException, JsonMappingException, JsonParseException { ObjectReader reader = objectMapper.reader(TypeFactory.defaultInstance().constructParametricType(List.class, requiredType)); try { List<T> toReturn = reader.readValue(content); if (toReturn == null || toReturn.isEmpty()) { throw new InvalidArgumentException("Could not read content from HTTP request body, the list is empty"); } return toReturn; } catch (IOException error) { throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage()); } }
private Object[][] loadInputData(String inputEntry) { Object[][] inputData = null; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(TEST_INPUT_FILE); try { ObjectReader mapReader = new ObjectMapper().reader(Map.class); Map<String, Object> inputMaps = mapReader.readValue(inputStream); List<Map<String, Object>> inputs = (List<Map<String, Object>>) inputMaps.get(inputEntry); inputData = new Object[inputs.size()][]; for (int i = 0; i < inputs.size(); i++) { Map<String, Map<String, String>> intialCurrentStates = (Map<String, Map<String, String>>) inputs.get(i).get(INITIAL_CURRENT_STATES); Map<String, Map<String, String>> handoffCurrentStates = (Map<String, Map<String, String>>) inputs.get(i).get(HANDOFF_CURRENT_STATES); Long expectedDuration = Long.parseLong((String) inputs.get(i).get(EXPECTED_DURATION)); inputData[i] = new Object[] { intialCurrentStates, handoffCurrentStates, expectedDuration }; } } catch (IOException e) { e.printStackTrace(); } return inputData; }
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; }
public static CanvasRequest verifyAndDecode(String input, String secret) throws SecurityException { String[] split = getParts(input); String encodedSig = split[0]; String encodedEnvelope = split[1]; // Deserialize the json body String json_envelope = new String(new Base64(true).decode(encodedEnvelope)); ObjectMapper mapper = new ObjectMapper(); ObjectReader reader = mapper.reader(CanvasRequest.class); CanvasRequest canvasRequest; String algorithm; try { canvasRequest = reader.readValue(json_envelope); algorithm = canvasRequest.getAlgorithm() == null ? "HMACSHA256" : canvasRequest.getAlgorithm(); } catch (IOException e) { throw new SecurityException(String.format("Error [%s] deserializing JSON to Object [%s]", e.getMessage(), CanvasRequest.class.getName()), e); } verify(secret, algorithm, encodedEnvelope, encodedSig); // If we got this far, then the request was not tampered with. // return the request as a Java object return canvasRequest; }
@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); }
@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 = JsonUtilClient.getXAttr(json, "user.a2"); Assert.assertArrayEquals(XAttrCodec.decodeValue("0x313131"), value); }
@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); } }
JacksonInstanceSerializer(ObjectReader objectReader, ObjectWriter objectWriter, TypeReference<ServiceInstance<T>> typeRef) { this.objectReader = objectReader; this.objectWriter = objectWriter; this.typeRef = typeRef; }
/** * Constructs the object based on the content. * @param content Reader * @return T * @throws IOException */ public <T> T construct(Reader content, Class<T> requiredType) throws IOException, JsonMappingException, JsonParseException { ObjectReader reader = objectMapper.reader(requiredType); try { return reader.readValue(content); } catch (IOException error) { throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage()); } }
/** * 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; }
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<Object[]>(); 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); ret.add(new Object[] { stateModelDef, preferenceList, currentStates, bestPossibleStates }); } } catch (IOException e) { e.printStackTrace(); } return ret; }
@Test public void testProxies() throws Throwable { Person person = createTestPerson(); FullTaxonomy_Person fullTaxonomyPerson = Inflection.cast( FullTaxonomy_Person.class, person ); UseCase1_Person useCase1Person = Inflection.cast( UseCase1_Person.class, person ); UseCase2_Person useCase2Person = Inflection.cast( UseCase2_Person.class, person ); UseCase3_Person useCase3Person = Inflection.cast( UseCase3_Person.class, person ); UseCase4_Address useCase4Address = Inflection.cast( UseCase4_Address.class, person.getAddresses().get( 0 ) ); UseCase5_Person useCase5Person = Inflection.cast( UseCase5_Person.class, person ); ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter(); ObjectReader reader = mapper.reader().withType( FullTaxonomy_Person.class ); reader.readValue( writer.writeValueAsString( fullTaxonomyPerson ) ); printStream.println( "FullTaxonomy_Person:" ); printStream.println( writer.writeValueAsString( fullTaxonomyPerson ) ); printStream.println(); printStream.println( "UseCase1_Person:" ); printStream.println( writer.writeValueAsString( useCase1Person ) ); printStream.println(); printStream.println( "UseCase2_Person:" ); printStream.println( writer.writeValueAsString( useCase2Person ) ); printStream.println(); printStream.println( "UseCase3_Person:" ); printStream.println( writer.writeValueAsString( useCase3Person ) ); printStream.println(); printStream.println( "UseCase4_Address:" ); printStream.println( writer.writeValueAsString( useCase4Address ) ); printStream.println(); printStream.println( "UseCase5_Person:" ); printStream.println( writer.writeValueAsString( useCase5Person ) ); printStream.println(); }
public ObjectReader getObjectReader() { return objectMapper.reader(); }
public ObjectReader getObjectReader(Class<?> clazz) { return objectMapper.reader().withType(clazz); }
InstanceSerializerFactory(ObjectReader objectReader, ObjectWriter objectWriter) { this.objectReader = objectReader; this.objectWriter = objectWriter; }