static String toJsonPath(JsonStreamContext context) { StringBuilder builder = new StringBuilder(); for (JsonStreamContext c = context; c != null; c = c.getParent()) { if (c.inArray()) { builder.insert(0, "[" + c.getCurrentIndex() + "]"); } else if (c.inObject()) { @Nullable String name = c.getCurrentName(); if (name == null || name.isEmpty()) { builder.insert(0, "[]"); } else if (isAsciiIdentifierPath(name)) { builder.insert(0, "." + name); } else { builder.insert(0, "['" + name + "']"); } } else if (c.inRoot()) { builder.insert(0, "$"); } } return builder.toString(); }
/** Get type for "on" values that are plain URIs by deducing the type from their parent. */ private String getOnType(DeserializationContext ctxt) { // Easiest way: The parser has already constructed an annotation object with a motivation. // This is highly dependendant on the order of keys in the JSON, i.e. if "on" is the first key in the annotation // object, this won't work. Object curVal = ctxt.getParser().getCurrentValue(); boolean isPaintingAnno = (curVal != null && curVal instanceof Annotation && ((Annotation) curVal).getMotivation() != null && ((Annotation) curVal).getMotivation().equals(Motivation.PAINTING)); if (isPaintingAnno) { return "sc:Canvas"; } // More reliable way: Walk up the parsing context until we hit a IIIF resource that we can deduce the type from // Usually this shouldn't be more than two levels up JsonStreamContext parent = ctxt.getParser().getParsingContext().getParent(); while (parent != null && (parent.getCurrentValue() == null || !(parent.getCurrentValue() instanceof Resource))) { parent = parent.getParent(); } if (parent != null) { Resource parentObj = (Resource) parent.getCurrentValue(); return parentObj.getType(); } return null; }
@Override public void close() throws IOException { if (generator.isClosed()) { return; } JsonStreamContext context = generator.getOutputContext(); if ((context != null) && (context.inRoot() == false)) { throw new IOException("Unclosed object or array found"); } if (writeLineFeedAtEnd) { flush(); // Bypass generator to always write the line feed getLowLevelGenerator().writeRaw(LF); } generator.close(); }
private Path getPath(PropertyWriter writer, JsonStreamContext sc) { LinkedList<PathElement> elements = new LinkedList<>(); if (sc != null) { elements.add(new PathElement(writer.getName(), sc.getCurrentValue())); sc = sc.getParent(); } while (sc != null) { if (sc.getCurrentName() != null && sc.getCurrentValue() != null) { elements.addFirst(new PathElement(sc.getCurrentName(), sc.getCurrentValue())); } sc = sc.getParent(); } return new Path(elements); }
private void close() throws IOException { if ( !shallowObjects.isEmpty() ) { for (String o : shallowObjects) { jg.writeFieldName(o); jg.writeBoolean(true); } } while (jg.getOutputContext().getParent() != null) { JsonStreamContext oc = jg.getOutputContext(); if (oc.inObject()) { jg.writeEndObject(); } else if (oc.inArray()) { jg.writeEndArray(); } } jg.flush(); if( options.callback()!=null ) { output.write(")".getBytes(StandardCharsets.UTF_8)); } jg.close(); }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { if (context.inArray()) { mismatch.appendText("was of type ARRAY"); return false; } if (context.inRoot()) { mismatch.appendText("was of type ROOT"); return false; } if (!context.inObject()) { mismatch.appendText("was not of type OBJECT"); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { if (context.inRoot()) { mismatch.appendText("was of type ROOT"); return false; } if (context.inObject()) { mismatch.appendText("was of type OBJECT"); return false; } if (!context.inArray()) { mismatch.appendText("was not of type ARRAY"); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { if (context.inObject()) { mismatch.appendText("was of type OBJECT"); return false; } if (context.inArray()) { mismatch.appendText("was of type ARRAY"); return false; } if (!context.inRoot()) { mismatch.appendText("was not of type ROOT"); return false; } return true; }
@Override public void writeFieldsEnd(FSTClazzInfo serializationInfo) { try { JsonStreamContext outputContext = gen.getOutputContext(); if ( outputContext.inObject() ) { gen.writeEndObject(); } else { gen.writeEndArray(); } if ( outputContext.inObject() ) gen.writeEndObject(); } catch (IOException e) { FSTUtil.<RuntimeException>rethrow(e); try { gen.flush(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println( new String(out.buf,0,out.pos) ); } }
private static String getContainingField(JsonGenerator gen) { JsonStreamContext ctx = gen.getOutputContext(); if (ctx.inArray()) { return ctx.getParent().getCurrentName(); } else { return ctx.getCurrentName(); } }
private static String getContainingField(JsonParser parser) { final JsonStreamContext ctx = parser.getParsingContext(); if (ctx.inArray()) { return ctx.getParent().getCurrentName(); } else { return ctx.getCurrentName(); } }
protected boolean inRoot() { if (isFiltered()) { JsonStreamContext context = filter.getFilterContext(); return ((context != null) && (context.inRoot() && context.getCurrentName() == null)); } return false; }
@Override public void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException { JsonStreamContext context = gen.getOutputContext(); gen.setCurrentValue(value); // must set manually, or else the result of context.getCurrentValue() will be null。this method will call context.setCurrentValue(value); gen.writeStartObject(); // writeStartObject(value) will call setCurrentValue(value) well Class<?> entityClass = value.getClass(); Method[] methods = entityClass.getMethods(); // include method inherited from super classes for(Method method : methods) { // check whether serialization will be recursive if (willRecursive(gen, context, method)) { gen.writeEndObject(); return; } // method annotated with @Field Field fieldAnnotation = method.getAnnotation(Field.class); if(fieldAnnotation != null) { serializeField(value, gen, entityClass, method, fieldAnnotation); }else { MultiFields multiFields = method.getAnnotation(MultiFields.class); if(multiFields != null) { Field mainFieldAnnotation = multiFields.mainField(); serializeField(value, gen, entityClass, method, mainFieldAnnotation); } } } // gen.writeObjectField("extra_field", "whatever_value"); gen.writeEndObject(); }
private boolean willRecursive(JsonGenerator gen, JsonStreamContext ctxt, Method method) throws IOException { if (ctxt != null) { JsonStreamContext ptxt = ctxt.getParent(); while(ptxt != null) { // if(ctxt.getCurrentValue() != ptxt.getCurrentValue()) { // ptxt = ptxt.getParent(); // }else { // gen.writeEndObject(); // return; // } // if(ptxt.getCurrentValue() == null || !ctxt.getCurrentValue().getClass().equals(ptxt.getCurrentValue().getClass())) { // ptxt = ptxt.getParent(); // }else { // gen.writeEndObject(); // return; // } // String typeName = method.getGenericReturnType().getTypeName(); if(ptxt.getCurrentValue() == null || !ReflectionUtils.getInnermostType(method).equals(ptxt.getCurrentValue().getClass().getCanonicalName())) { ptxt = ptxt.getParent(); }else { return true; } } } return false; }
private boolean willRecursive(JsonStreamContext ctxt, Method method) throws IOException { if (ctxt != null) { JsonStreamContext ptxt; ptxt = ctxt.getParent(); while(ptxt != null) { if(ptxt.getCurrentValue() == null || !ReflectionUtils.getInnermostType(method).equals(ptxt.getCurrentValue().getClass().getCanonicalName())) { ptxt = ptxt.getParent(); }else { return true; } } } return false; }
protected boolean include(final PropertyWriter writer, final JsonGenerator jgen) { if (!contextProvider.isFilteringEnabled()) { return true; } JsonStreamContext streamContext = getStreamContext(jgen); if (streamContext == null) { return true; } Path path = getPath(writer, streamContext); SquigglyContext context = contextProvider.getContext(path.getFirst().getBeanClass()); String filter = context.getFilter(); if (AnyDeepName.ID.equals(filter)) { return true; } if (path.isCachable()) { // cache the match result using the path and filter expression Pair<Path, String> pair = Pair.of(path, filter); Boolean match = MATCH_CACHE.getIfPresent(pair); if (match == null) { match = pathMatches(path, context); } MATCH_CACHE.put(pair, match); return match; } return pathMatches(path, context); }
@SuppressWarnings("unused") private static String printOutputContext(JsonStreamContext ctx) { return new StringBuilder("JSONContext [") .append("\n\tCurrent Index:").append(ctx.getCurrentIndex()) .append("\n\tCurrent Name:").append(ctx.getCurrentName()) .append("\n\tEntry Count:").append(ctx.getEntryCount()) .append("\n\tType Desc:").append(ctx.getTypeDesc()) .append("\n\tIn Array:").append(ctx.inArray()) .append("\n\tIn Object:").append(ctx.inObject()) .append("\n\tIn Root:").append(ctx.inRoot()) .append("\n]").toString(); }
private static String printOutputContext(JsonStreamContext ctx) { return new StringBuilder("JSONContext [") .append("\n\tCurrent Index:").append(ctx.getCurrentIndex()) .append("\n\tCurrent Name:").append(ctx.getCurrentName()) .append("\n\tEntry Count:").append(ctx.getEntryCount()) .append("\n\tType Desc:").append(ctx.getTypeDesc()) .append("\n\tIn Array:").append(ctx.inArray()) .append("\n\tIn Object:").append(ctx.inObject()) .append("\n\tIn Root:").append(ctx.inRoot()) .append("\n]").toString(); }
@Override public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException { if(jobsManager == null) { throw new IllegalStateException("This deserializer need a jobsManager instance, see 'JobParametersDeserializer.setJobsManager'"); } final JsonStreamContext jsc = p.getParsingContext(); String paramName = null; JsonStreamContext parent = jsc; while(parent != null) { paramName = parent.getCurrentName(); if(paramName != null) { break; } parent = parent.getParent(); } if(parent == null) { throw new NullPointerException("Something wrong: we can not find our parent object, " + "may be you use this deserializer on custom object?"); } JobParameters.Builder r = (JobParameters.Builder) parent.getParent().getCurrentValue(); String jobType = r.getType(); JobDescription desc = jobsManager.getDescription(jobType); JobParameterDescription param = desc.getParameters().get(paramName); TypeFactory typeFactory = ctx.getTypeFactory(); JavaType type; if(param == null) { type = typeFactory.constructType(Object.class); } else { type = typeFactory.constructType(param.getType()); } JsonDeserializer<Object> deser = ctx.findNonContextualValueDeserializer(type); try { return deser.deserialize(p, ctx); } catch (Exception e) { throw new RuntimeException("Can not deserialize '" + jobType + "." + paramName + "' job parameter ", e ); } }
/** * JSON tree walk to find the druid query context of the current context and apply handler to the DruidQuery, * finds the current context if current context is a druid query. * * @param gen the Json Generator to retrieve the tree to walk on. * @param mapper a function that takes an DruidQuery as an argument and return the final desired returned result. * @param <T> Type of result from the mapper * * @return an Optional of the desired result T if DruidQuery is found, Optional.empty otherwise */ public static <T> Optional<T> mapNearestDruidQuery(JsonGenerator gen, Function<DruidQuery, T> mapper) { JsonStreamContext context = gen.getOutputContext(); while (context != null) { Object parent = context.getCurrentValue(); if (parent instanceof DruidQuery) { return Optional.of(mapper.apply((DruidQuery) parent)); } context = context.getParent(); } return Optional.empty(); }
/** * Default constructor * @param message The error message * @param jsonStreamContext The JSON stream context * @param throwable An optional throwable associated with the error */ JsonError(String message, JsonStreamContext jsonStreamContext, Throwable throwable) { this.message = message; this.jsonPath = Collections.unmodifiableList( createJsonPath(jsonStreamContext)); this.throwable = throwable; }
/** * Create a list of strings describing the JSON path for the given * stream context * * @param streamContext The stream context * @return The string list */ private static List<String> createJsonPath(JsonStreamContext streamContext) { Collection<JsonStreamContext> list = expand(streamContext); return list.stream() .map(c -> c.getCurrentName() == null ? "" : c.getCurrentName()) .collect(Collectors.toList()); }
/** * Create a collection consisting of stream contexts, starting at the root * node and ending at the given stream context * * @param streamContext The stream context * @return The collection */ private static Collection<JsonStreamContext> expand( JsonStreamContext streamContext) { Deque<JsonStreamContext> collection = new LinkedList<JsonStreamContext>(); JsonStreamContext current = streamContext; while (current != null) { collection.addFirst(current); current = current.getParent(); } return collection; }
@Override protected Object deserializeFromObjectUsingNonDefault(JsonParser p, DeserializationContext ctxt) throws IOException { JsonStreamContext parent = p.getParsingContext().getParent(); // handle embedded types if (parent != null && parent.getCurrentValue() != null) { Object value = parent.getCurrentValue(); Class<?> parentClass = value.getClass(); Method method = embeddedGetters.get(parentClass); if (method == null) { Class<?> target = getValueType().getRawClass(); for (Method m : parentClass.getDeclaredMethods()) { if (target.isAssignableFrom(m.getReturnType()) && m.getParameterTypes().length == 0) { embeddedGetters.put(parentClass, m); method = m; break; } } } if (method != null) { try { return method.invoke(value); } catch (Exception e) { throw new RuntimeException(e); } } } return super.deserializeFromObjectUsingNonDefault(p, ctxt); }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { final int value = context.getEntryCount(); if (!matcher.matches(value)) { mismatch.appendText("entry count was "); matcher.describeMismatch(value, mismatch); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { final String value = context.getTypeDesc(); if (!matcher.matches(value)) { mismatch.appendText("type desc was "); matcher.describeMismatch(value, mismatch); return false; } return true; }
@Override protected boolean safeMatchesSafely(JsonParser parser, Description mismatch) throws IOException { final JsonStreamContext context = parser.getParsingContext(); if (!matcher.matches(context)) { mismatch.appendText("context "); matcher.describeMismatch(context, mismatch); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { final JsonStreamContext value = context.getParent(); if (!matcher.matches(value)) { mismatch.appendText("parent "); matcher.describeMismatch(value, mismatch); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { final String value = context.getCurrentName(); if (!matcher.matches(value)) { mismatch.appendText("current name was "); matcher.describeMismatch(value, mismatch); return false; } return true; }
@Override protected boolean matchesSafely(JsonStreamContext context, Description mismatch) { final int value = context.getCurrentIndex(); if (!matcher.matches(value)) { mismatch.appendText("current index was "); matcher.describeMismatch(value, mismatch); return false; } return true; }
protected static boolean isInICalProperty(JsonStreamContext context) { if (context == null) { return false; } Object currentValue = context.getCurrentValue(); if (currentValue == PROPERTY_VALUE) { return true; } return isInICalProperty(context.getParent()); }
/** * only first call return FetchPath * <p> * and then call is bean sub-path (property) * * @return fetch path or null */ private FetchPath getPathProperties(JsonGenerator jsonGenerator) { FetchPath fetchPath = EbeanUtils.getRequestFetchPath(); if (fetchPath != null) { JsonStreamContext context = jsonGenerator.getOutputContext(); JsonStreamContext parent = context.getParent(); if (parent == null) { return fetchPath; } StringBuilder path = new StringBuilder(); while (parent != null && !parent.inRoot()) { if (parent != context.getParent()) { path.insert(0, '.'); } path.insert(0, parent.getCurrentName()); parent = parent.getParent(); } String fp = path.toString(); PathProperties fetch = new PathProperties(); EbeanPathProps src = (EbeanPathProps) fetchPath; String cp = fp + "."; for (BeanPathProperties.Props prop : src.getPathProps()) { String pp = prop.getPath(); if (pp.equals(fp)) { addToFetchPath(fetch, null, prop); } else if (pp.startsWith(cp)) { addToFetchPath(fetch, pp.substring(cp.length()), prop); } } return fetch; } return null; }
public NumericallyIndexedObjectBackedArray(ConfigValue n, HoconNodeCursor p) { super(JsonStreamContext.TYPE_ARRAY, p); TreeMap<Integer, ConfigValue> sortedContents = new TreeMap<Integer, ConfigValue>(); for (Map.Entry<String, ConfigValue> entry: ((ConfigObject) n).entrySet()) { try { Integer key = Integer.parseInt(entry.getKey()); sortedContents.put(key, entry.getValue()); } catch (NumberFormatException e) { throw new IllegalStateException("Key: '" + entry.getKey() + "' in object could not be parsed to an Integer, therefor we cannot be using a " + getClass().getSimpleName()); } } _contents = sortedContents.values().iterator(); }
private boolean inRoot() { JsonStreamContext context = generator.getOutputContext(); return ((context != null) && (context.inRoot() && context.getCurrentName() == null)); }
@Override public JsonStreamContext getParsingContext() { return null; }
@Override public JsonStreamContext getParsingContext() { throw new UnsupportedOperationException(); }
private JsonStreamContext getStreamContext(JsonGenerator jgen) { return jgen.getOutputContext(); }