@Override public List<JsonNode> getSourceDocuments() { LOGGER.debug("Retrieving source docs"); try { DataFindRequest sourceRequest = new DataFindRequest(getMigrationConfiguration().getSourceEntityName(), getMigrationConfiguration().getSourceEntityVersion()); sourceRequest.where(Query.query((ContainerNode) JSON.toJsonNode(getMigrationJob().getQuery()))); sourceRequest.select(Projection.includeFieldRecursively("*"), Projection.excludeField("objectType")); LOGGER.debug("Source docs retrieval req: {}", sourceRequest.getBody()); JsonNode[] results = getSourceCli().data(sourceRequest, JsonNode[].class); LOGGER.debug("There are {} source docs", results.length); return Arrays.asList(results); } catch (Exception e) { LOGGER.error("Error while retrieving source documents:{}", e); throw new RuntimeException("Cannot retrieve source documents:" + e); } }
@Override protected void appendToJsonNode(Object value, ContainerNode<?> targetNode, FieldCursor cursor) { FieldTreeNode field = cursor.getCurrentNode(); if(PredefinedFields.isFieldAnArrayCount(field.getName(), currentFields)){ /* * This case will be handled by the array itself, allowing this to * process runs the risk of nulling out the correct value. */ return; } Path fieldPath = cursor.getCurrentPath(); if (targetNode instanceof ObjectNode) { currentTargetObjectNode = (ObjectNode) targetNode; } if(PredefinedFields.isFieldObjectType(fieldPath.toString())){ ((ObjectNode) targetNode).set(fieldPath.toString(), toJson(StringType.TYPE, entityMetadata.getEntityInfo().getName())); } else{ super.appendToJsonNode(value, targetNode, cursor); } }
/** * This method here expands our horizons in writing code that sucks. * JsonNodes have no parent pointer, so finding a parent involves iterating * all nodes with the hope of finding the node, and returning the container * that contains it. * * The whole JsonNode thing should be reengineered at some point. */ public static JsonNode findParent(final JsonNode root, final JsonNode node) { if (root instanceof ContainerNode) { for (Iterator<JsonNode> itr = root.elements(); itr.hasNext();) { JsonNode child = itr.next(); if (child == node) { return root; } else { JsonNode found = findParent(child, node); if (found != null) { return found; } } } } return null; }
private TestRackInterface withDataRequest(String resource, ContainerNode<ObjectNode> body, MockHttpServletRequestBuilder requestBuilder) throws Exception { MvcResult result = getMockMvc().perform(requestBuilder .content(body.toString()) .contentType(contentType)) .andReturn(); return toSimpleResponse(result); }
public static void stripEmptyContainerNodes(ObjectNode objectNode) { Iterator<Entry<String, JsonNode>> i = objectNode.fields(); while (i.hasNext()) { Entry<String, JsonNode> entry = i.next(); JsonNode value = entry.getValue(); if (value instanceof ContainerNode && ((ContainerNode<?>) value).size() == 0) { // remove empty nodes, e.g. unused "smtp" and "alerts" nodes i.remove(); } } }
@Override protected void appendToJsonNode(Object value, ContainerNode<?> targetNode, FieldCursor cursor) { Path fieldPath = cursor.getCurrentPath(); if(dnPath.equals(fieldPath)){ //DN is not technically an attribute and can be skipped. return; } super.appendToJsonNode(value, targetNode, cursor); }
protected void appendToJsonNode(Object value, ContainerNode<?> targetNode, FieldCursor cursor) { FieldTreeNode field = cursor.getCurrentNode(); Error.push(field.getName()); try{ JsonNode newJsonNode = null; Object newValue = null; if (field instanceof ObjectField || field instanceof ObjectArrayElement) { newJsonNode = translateToObjectNode(value, cursor); } else if((newValue = getValueFor(value, cursor.getCurrentPath())) != null){ if (field instanceof SimpleField) { newJsonNode = translate((SimpleField)field, newValue); } else if (field instanceof ArrayField){ newJsonNode = translateToArrayNode((ArrayField) field, newValue, cursor); } else{ throw new UnsupportedOperationException("Unknown Field type: " + field.getClass().getName()); } } if (targetNode instanceof ObjectNode) { ((ObjectNode) targetNode).set(cursor.getCurrentNode().getName(), newJsonNode); } else { ((ArrayNode) targetNode).add(newJsonNode); } } finally{ Error.pop(); } }
@SuppressWarnings("rawtypes") private static JsonNode createIntermediate(JsonNode node, StringBuffer pathSofar, String index, String nextIndex) { if (node instanceof ContainerNode) { ContainerNode temp = (ContainerNode) node; JsonNode value = PATTERN_INDEX.matcher(nextIndex).matches() ? temp.arrayNode() : temp.objectNode(); return createIntermediate(temp, pathSofar, index, value); } return null; }
public TestRackInterface POST(String resource, ContainerNode<ObjectNode> body) throws Exception { return withDataRequest(resource, body, post(resource)); }
public TestRackInterface PUT(String resource, ContainerNode<ObjectNode> body) throws Exception { return withDataRequest(resource, body, put(resource)); }
/** * Constructs a projection node from an array or object node */ public Projection(ContainerNode node) { super(node); }
/** * Returns a projection based on an array or object node */ public static Projection project(ContainerNode node) { return new Projection(node); }
/** * Creates an update node with the given array or object node */ public Update(ContainerNode node) { super(node); }
public static Update update(ContainerNode node) { return new Update(node); }
/** * Constructs a query object from a json array or object */ public Query(ContainerNode node) { super(node); }
/** * Creates a sort node using the array or object node */ public Sort(ContainerNode node) { super(node); }
public static Sort sort(ContainerNode node) { return new Sort(node); }
/** * Construct expression with the given object or array node */ protected Expression(ContainerNode node) { super(node); }
/** * Performs single JSON-RPC request and return JSON-RPC response * * @param request JSON-RPC request as a Java object * @param service service object * @return JSON-RPC response as a Java object * @throws Exception in case of a runtime error (reflections, business logic...) */ @NotNull private Response handleSingle(@NotNull Request request, @NotNull Object service) throws Exception { // Check mandatory fields and correct protocol version String requestMethod = request.getMethod(); String jsonrpc = request.getJsonrpc(); ValueNode id = request.getId(); if (jsonrpc == null || requestMethod == null) { log.error("Not a JSON-RPC request: " + request); return new ErrorResponse(id, INVALID_REQUEST); } if (!jsonrpc.equals(VERSION)) { log.error("Not a JSON_RPC 2.0 request: " + request); return new ErrorResponse(id, INVALID_REQUEST); } JsonNode params = request.getParams(); if (!params.isObject() && !params.isArray() && !params.isNull()) { log.error("Params of request: '" + request + "' should be an object, an array or null"); return new ErrorResponse(id, INVALID_REQUEST); } ClassMetadata classMetadata = classesMetadata.get(service.getClass()); if (!classMetadata.isService()) { log.warn(service.getClass() + " is not available as a JSON-RPC 2.0 service"); return new ErrorResponse(id, METHOD_NOT_FOUND); } MethodMetadata method = classMetadata.getMethods().get(requestMethod); if (method == null) { log.error("Unable find a method: '" + requestMethod + "' in a " + service.getClass()); return new ErrorResponse(id, METHOD_NOT_FOUND); } ContainerNode<?> notNullParams = !params.isNull() ? (ContainerNode<?>) params : mapper.createObjectNode(); Object[] methodParams; try { methodParams = convertToMethodParams(notNullParams, method); } catch (IllegalArgumentException e) { log.error("Bad params: " + notNullParams + " of a method '" + method.getName() + "'", e); return new ErrorResponse(id, INVALID_PARAMS); } Object result = method.getMethod().invoke(service, methodParams); return new SuccessResponse(id, result); }
/** * Converts JSON params to java params in the appropriate order of the invoked method * * @param params json params (map or array) * @param method invoked method metadata * @return array of java objects for passing to the method */ @NotNull private Object[] convertToMethodParams(@NotNull ContainerNode<?> params, @NotNull MethodMetadata method) { int methodParamsSize = method.getParams().size(); int jsonParamsSize = params.size(); // Check amount arguments if (jsonParamsSize > methodParamsSize) { throw new IllegalArgumentException("Wrong amount arguments: " + jsonParamsSize + " for a method '" + method.getName() + "'. Actual amount: " + methodParamsSize); } Object[] methodParams = new Object[methodParamsSize]; int processed = 0; for (ParameterMetadata param : method.getParams().values()) { Class<?> parameterType = param.getType(); int index = param.getIndex(); String name = param.getName(); JsonNode jsonNode = params.isObject() ? params.get(name) : params.get(index); // Handle omitted value if (jsonNode == null || jsonNode.isNull()) { if (param.isOptional()) { methodParams[index] = getDefaultValue(parameterType); if (jsonNode != null) { processed++; } continue; } else { throw new IllegalArgumentException("Mandatory parameter '" + name + "' of a method '" + method.getName() + "' is not set"); } } // Convert JSON object to an actual Java object try { JsonParser jsonParser = mapper.treeAsTokens(jsonNode); JavaType javaType = mapper.getTypeFactory().constructType(param.getGenericType()); methodParams[index] = mapper.readValue(jsonParser, javaType); processed++; } catch (IOException e) { throw new IllegalArgumentException("Wrong param: " + jsonNode + ". Expected type: '" + param, e); } } // Check that some unprocessed parameters were not passed if (processed < jsonParamsSize) { throw new IllegalArgumentException("Some unspecified parameters in " + params + " are passed to a method '" + method.getName() + "'"); } return methodParams; }
private void iterateOverNodes(Object value, ContainerNode<?> targetNode, FieldCursor cursor) { do { appendToJsonNode(value, targetNode, cursor); } while(cursor.nextSibling()); }