001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.isis.viewer.restfulobjects.applib.util; 020 021import java.io.ByteArrayInputStream; 022import java.io.InputStream; 023import java.util.List; 024 025import org.codehaus.jackson.JsonNode; 026import org.codehaus.jackson.node.JsonNodeFactory; 027import org.codehaus.jackson.node.ObjectNode; 028 029import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation; 030 031import com.google.common.base.Charsets; 032 033public class JsonNodeUtils { 034 035 private JsonNodeUtils() { 036 } 037 038 public static InputStream asInputStream(final JsonNode jsonNode) { 039 final String jsonStr = jsonNode.toString(); 040 final byte[] bytes = jsonStr.getBytes(Charsets.UTF_8); 041 return new ByteArrayInputStream(bytes); 042 } 043 044 public static InputStream asInputStream(final JsonRepresentation jsonRepresentation) { 045 final String jsonStr = jsonRepresentation.toString(); 046 final byte[] bytes = jsonStr.getBytes(Charsets.UTF_8); 047 return new ByteArrayInputStream(bytes); 048 } 049 050 /** 051 * Walks the path, ensuring keys exist and are maps, or creating required 052 * maps as it goes. 053 * 054 * <p> 055 * For example, if given a list ("a", "b", "c") and starting with an empty 056 * map, then will create: 057 * 058 * <pre> 059 * { 060 * "a": { 061 * "b: { 062 * "c": { 063 * } 064 * } 065 * } 066 * } 067 */ 068 public static ObjectNode walkNodeUpTo(ObjectNode node, final List<String> keys) { 069 for (final String key : keys) { 070 JsonNode jsonNode = node.get(key); 071 if (jsonNode == null) { 072 jsonNode = new ObjectNode(JsonNodeFactory.instance); 073 node.put(key, jsonNode); 074 } else { 075 if (!jsonNode.isObject()) { 076 throw new IllegalArgumentException(String.format("walking path: '%s', existing key '%s' is not a map", keys, key)); 077 } 078 } 079 node = (ObjectNode) jsonNode; 080 } 081 return node; 082 } 083 084}