com.fasterxml.jackson.databind.JsonNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.JsonNode. 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: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 7 votes vote down vote up
private static List<Commit> getHistory(AggregatedHttpResponse res) {
    switch (res.status().code()) {
        case 200:
            final JsonNode node = toJson(res, null);
            if (node.isObject()) {
                return ImmutableList.of(toCommit(node));
            } else if (node.isArray()) {
                return Streams.stream(node)
                              .map(ArmeriaCentralDogma::toCommit)
                              .collect(toImmutableList());
            } else {
                return rejectNeitherArrayNorObject(res);
            }
        case 204:
            return ImmutableList.of();
    }

    return handleErrorResponse(res);
}
 
Example #2
Source File: DecryptAetIdentifiers.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Decrypt a payload encoded in a compact serialization of JSON Web Encryption (JWE).
 *
 * <p>The payload may be either a single JWE string or an array of values.
 *
 * <p>Assumes that the payload contains a "kid" parameter that can be used to look up a matching
 * private key.
 */
public static JsonNode decrypt(KeyStore keyStore, JsonNode anonIdNode)
    throws JoseException, KeyNotFoundException {
  if (anonIdNode.isTextual()) {
    String anonId = anonIdNode.textValue();
    JsonWebStructure fromCompact = JsonWebEncryption.fromCompactSerialization(anonId);
    String keyId = fromCompact.getKeyIdHeaderValue();
    PrivateKey key = keyStore.getKeyOrThrow(keyId);
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(key);
    jwe.setContentEncryptionKey(key.getEncoded());
    jwe.setCompactSerialization(anonId);
    return TextNode.valueOf(jwe.getPlaintextString());
  } else if (anonIdNode.isArray()) {
    ArrayNode userIds = Json.createArrayNode();
    for (JsonNode node : anonIdNode) {
      userIds.add(decrypt(keyStore, node));
    }
    return userIds;
  } else {
    throw new IllegalArgumentException(
        "Argument to decrypt must be a TextNode or ArrayNode, but got " + anonIdNode);
  }
}
 
Example #3
Source File: SentryConverterTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void validate(JsonNode model) {
    ArrayNode node = (ArrayNode) model.path("childShapes").get(0).path("childShapes");
    JsonNode sentryNode = null;

    for (JsonNode shape : node) {
        String resourceId = shape.path("resourceId").asText();
        if (SENTRY_NODE_ID.equals(resourceId)) {
            sentryNode = shape;
        }
    }

    //validate docker nodes
    Double x = sentryNode.path("dockers").get(0).path("x").asDouble();
    Double y = sentryNode.path("dockers").get(0).path("y").asDouble();

    //the modeler does not store a mathematical correct docker point.
    assertThat(x).isEqualTo(-1.0);
    assertThat(y).isEqualTo(34.0);
}
 
Example #4
Source File: EventValidatorTest.java    From tasmo with Apache License 2.0 6 votes vote down vote up
private Validated validateUnknownEvent(boolean subsequent) {
    ObjectNode instance = mapper.createObjectNode();
    instance.put("value", "value");
    instance.put("ref_field", mapper.convertValue(new ObjectId("Bar", new Id(2)).toStringForm(), JsonNode.class));
    instance.put("refs_field", mapper.convertValue(Arrays.asList(new ObjectId("Baz", new Id(3)).toStringForm()), JsonNode.class));
    instance.put("all_field", mapper.convertValue(Arrays.asList(new ObjectId("Goo", new Id(4)).toStringForm()), JsonNode.class));

    ObjectNode event2 = mapper.createObjectNode();
    jec.setEventId(event2, 1);
    jec.setInstanceNode(event2, "Bar", instance);

    ChainedVersion version2 = new ChainedVersion("1", "2");
    Mockito.when(eventsProvider.getCurrentEventsVersion(tenantId))
            .thenReturn(version, version2);
    Mockito.when(eventsProvider.getEvents(Mockito.any(EventsProcessorId.class)))
            .thenReturn(Arrays.asList(event), Arrays.asList(event2));

    VersionedEventsModel versionedEventsModel = tenantEventsProvider.getVersionedEventsModel(tenantId);
    if (subsequent) {
        tenantEventsProvider.loadModel(tenantId);
        versionedEventsModel = tenantEventsProvider.getVersionedEventsModel(tenantId);
    }
    return eventValidator.validateEvent(versionedEventsModel, event2);
}
 
Example #5
Source File: ClusterRestController.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Patch a cluster using JSON Patch.
 *
 * @param id    The id of the cluster to patch
 * @param patch The JSON Patch instructions
 * @throws NotFoundException           If no cluster with {@literal id} exists
 * @throws PreconditionFailedException If the ids don't match
 * @throws GenieServerException        If the patch can't be applied
 */
@PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void patchCluster(
    @PathVariable("id") final String id,
    @RequestBody final JsonPatch patch
) throws NotFoundException, PreconditionFailedException, GenieServerException {
    log.info("[patchCluster] Called with id {} with patch {}", id, patch);

    final Cluster currentCluster = DtoConverters.toV3Cluster(this.persistenceService.getCluster(id));

    try {
        log.debug("Will patch cluster {}. Original state: {}", id, currentCluster);
        final JsonNode clusterNode = GenieObjectMapper.getMapper().valueToTree(currentCluster);
        final JsonNode postPatchNode = patch.apply(clusterNode);
        final Cluster patchedCluster = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Cluster.class);
        log.debug("Finished patching cluster {}. New state: {}", id, patchedCluster);
        this.persistenceService.updateCluster(id, DtoConverters.toV4Cluster(patchedCluster));
    } catch (final JsonPatchException | IOException e) {
        log.error("Unable to patch cluster {} with patch {} due to exception.", id, patch, e);
        throw new GenieServerException(e.getLocalizedMessage(), e);
    }
}
 
Example #6
Source File: XGBoostModel.java    From samantha with MIT License 6 votes vote down vote up
public List<ObjectNode> classify(List<ObjectNode> entities) {
    List<LearningInstance> instances = new ArrayList<>();
    for (JsonNode entity : entities) {
        instances.add(featurize(entity, true));
    }
    double[][] preds = predict(instances);
    List<ObjectNode> rankings = new ArrayList<>();
    for (int i=0; i<instances.size(); i++) {
        int k = preds[i].length;
        for (int j = 0; j < k; j++) {
            if (indexSpace.getKeyMapSize(ConfigKey.LABEL_INDEX_NAME.get()) > j) {
                ObjectNode rec = Json.newObject();
                rec.put("dataId", i);
                String fea = (String) indexSpace.getKeyForIndex(
                        ConfigKey.LABEL_INDEX_NAME.get(), j);
                IOUtilities.parseEntityFromStringMap(rec, FeatureExtractorUtilities.decomposeKey(fea));
                rec.put("classProb", preds[i][j]);
                rankings.add(rec);
            }
        }
    }
    return rankings;
}
 
Example #7
Source File: TestJson.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testJsonArraysForArrayNode() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsJsonArrayValues());
    ObjectMapper objectMapper =  new ObjectMapper();
    ArrayNode jsonArray1 = new ArrayNode(objectMapper.getNodeFactory());
    ObjectNode john = new ObjectNode(objectMapper.getNodeFactory());
    john.put("username", "john");
    ObjectNode pete = new ObjectNode(objectMapper.getNodeFactory());
    pete.put("username", "pete");
    jsonArray1.add(john);
    jsonArray1.add(pete);

    ArrayNode jsonArray2 = new ArrayNode(objectMapper.getNodeFactory());
    ObjectNode john2 = new ObjectNode(objectMapper.getNodeFactory());
    john2.put("username", "john2");
    ObjectNode pete2 = new ObjectNode(objectMapper.getNodeFactory());
    pete2.put("username", "pete2");
    jsonArray2.add(john2);
    jsonArray2.add(pete2);

    ArrayNode[] arrayNodes = new ArrayNode[]{jsonArray1, jsonArray2};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "docs", arrayNodes);
    this.sqlgGraph.tx().commit();
    JsonNode[] value = this.sqlgGraph.traversal().V(v1.id()).next().value("docs");
    Assert.assertArrayEquals(arrayNodes, value);
}
 
Example #8
Source File: JsonSplitReplaceOpTest.java    From zjsonpatch with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonDiffDoesNotSplitsWhenThereIsNoReplaceOperationButOnlyAdd() throws JsonProcessingException {
    String source = "{ \"ids\": [ \"F1\" ] }";
    String target = "{ \"ids\": [ \"F1\", \"F6\"] }";

    JsonNode sourceNode = OBJECT_MAPPER.reader().readTree(source);
    JsonNode targetNode = OBJECT_MAPPER.reader().readTree(target);

    JsonNode diff = JsonDiff.asJson(sourceNode, targetNode, EnumSet.of(
            DiffFlags.ADD_EXPLICIT_REMOVE_ADD_ON_REPLACE
    ));
    assertEquals(1, diff.size());
    assertEquals(Operation.ADD.rfcName(), diff.get(0).get("op").textValue());
    assertEquals("/ids/1", diff.get(0).get("path").textValue());
    assertEquals("F6", diff.get(0).get("value").textValue());
}
 
Example #9
Source File: JsonNodeELResolver.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected JsonNode getResultNode(JsonNode base, Object property, ELContext context) {
    if (property instanceof String) {
        JsonNode propertyNode = base.get((String) property);
        if (propertyNode != null) {
            return propertyNode;
        }

        if (!readOnly && base instanceof ObjectNode && context.getContext(EvaluationState.class) == EvaluationState.WRITE) {
            // The base does not have the requested property, so add it and return it, only if we are in write evaluation state
            return ((ObjectNode) base).putObject((String) property);
        }
        return null;
    } else if (property instanceof Number) {
        return base.get(((Number) property).intValue());
    } else {
        return base.get(property.toString());
    }
}
 
Example #10
Source File: OAAnnotationCollectionServiceImpl.java    From elucidate-server with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected OAAnnotationCollection convertToAnnotationCollection(W3CAnnotationCollection w3cAnnotationCollection) {

    Map<String, Object> w3cAnnotationCollectionMap = w3cAnnotationCollection.getJsonMap();
    JsonNode w3cAnnotationCollectionNode = new ObjectMapper().convertValue(w3cAnnotationCollectionMap, JsonNode.class);

    JsonNode oaAnnotationCollectionNode = new W3CToOAAnnotationCollectionConverter().convert(w3cAnnotationCollectionNode);
    Map<String, Object> oaAnnotationCollectionMap = new ObjectMapper().convertValue(oaAnnotationCollectionNode, Map.class);

    OAAnnotationCollection oaAnnotationCollection = new OAAnnotationCollection();
    oaAnnotationCollection.setPk(w3cAnnotationCollection.getPk());
    oaAnnotationCollection.setCacheKey(w3cAnnotationCollection.getCacheKey());
    oaAnnotationCollection.setCreatedDateTime(w3cAnnotationCollection.getCreatedDateTime());
    oaAnnotationCollection.setDeleted(w3cAnnotationCollection.isDeleted());
    oaAnnotationCollection.setCollectionId(w3cAnnotationCollection.getCollectionId());
    oaAnnotationCollection.setJsonMap(oaAnnotationCollectionMap);
    oaAnnotationCollection.setModifiedDateTime(oaAnnotationCollection.getModifiedDateTime());
    return oaAnnotationCollection;
}
 
Example #11
Source File: FakeApiController.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@ApiAction
public Result testInlineAdditionalProperties() throws Exception {
    JsonNode nodeparam = request().body().asJson();
    Map<String, String> param;
    if (nodeparam != null) {
        param = mapper.readValue(nodeparam.toString(), new TypeReference<Map<String, String>>(){});
        if (configuration.getBoolean("useInputBeanValidation")) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                OpenAPIUtils.validate(entry.getValue());
            }
        }
    } else {
        throw new IllegalArgumentException("'param' parameter is required");
    }
    imp.testInlineAdditionalProperties(param);
    return ok();
}
 
Example #12
Source File: PropertyDeserializer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private static List<String> getRequired(JsonNode node, PropertyBuilder.PropertyId type) {
    List<String> result = new ArrayList<String>();

    final JsonNode detailNode = getDetailNode(node, type);

    if (detailNode == null) {
        return result;
    }

    if (detailNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) detailNode;
        Iterator<JsonNode> fieldNameIter = arrayNode.iterator();

        while (fieldNameIter.hasNext()) {
            JsonNode item = fieldNameIter.next();
            result.add(item.asText());
        }
        return result;
    } else {
        throw new RuntimeException("Required property should be a list");
    }

}
 
Example #13
Source File: MappingInstructionJsonMatcher.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Matches the contents of an unicast weight mapping instruction.
 *
 * @param node        JSON instruction to match
 * @param description object used for recording errors
 * @return true if contents match, false otherwise
 */
private boolean matchUnicastWeightInstruction(JsonNode node,
                                              Description description) {
    UnicastMappingInstruction.WeightMappingInstruction instructionToMatch =
            (UnicastMappingInstruction.WeightMappingInstruction) instruction;
    final String jsonSubtype = node.get(MappingInstructionCodec.SUBTYPE).textValue();
    if (!instructionToMatch.subtype().name().equals(jsonSubtype)) {
        description.appendText("subtype was " + jsonSubtype);
        return false;
    }

    final String jsonType = node.get(MappingInstructionCodec.TYPE).textValue();
    if (!instructionToMatch.type().name().equals(jsonType)) {
        description.appendText("type was " + jsonType);
        return false;
    }

    final int jsonWeight = node.get(MappingInstructionCodec.UNICAST_WEIGHT).intValue();
    final int weight = instructionToMatch.weight();
    if (jsonWeight != weight) {
        description.appendText("Unicast weight was " + jsonWeight);
        return false;
    }

    return true;
}
 
Example #14
Source File: JsonPathSelector.java    From camunda-bpm-reactor with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(Object key) {
  if (null == key) {
    return false;
  }

  Object result = read(key);
  if (null == result) {
    return false;
  }
  Class<?> type = result.getClass();
  if (Collection.class.isAssignableFrom(type)) {
    return ((Collection) result).size() > 0;
  } else if (Map.class.isAssignableFrom(type)) {
    return ((Map) result).size() > 0;
  } else if (JsonNode.class.isAssignableFrom(type)) {
    return ((JsonNode) result).size() > 0;
  } else {
    return true;
  }
}
 
Example #15
Source File: ModelsResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
  JsonNode childShapesNode = editorJsonNode.get("childShapes");
  if (childShapesNode != null && childShapesNode.isArray()) {
    ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
    for (JsonNode childShapeNode : childShapesArrayNode) {
      // Properties
      ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
      if (properties != null && properties.has(propertyName)) {
        JsonNode propertyNode = properties.get(propertyName);
        if (propertyNode != null) {
          properties.remove(propertyName);
        }
      }

      // Potential nested child shapes
      if (childShapeNode.has("childShapes")) {
        internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
      }

    }
  }
}
 
Example #16
Source File: DruidSinkIT.java    From ingestion with Apache License 2.0 6 votes vote down vote up
private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "[email protected]", "[email protected]", "[email protected]",
            "[email protected]" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp", String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random
            .nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}
 
Example #17
Source File: Request.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public Request(
        @JsonProperty("headers")Map<String, Object> headers,
        @JsonProperty("queryParams")Map<String, Object> queryParams,
        @JsonProperty("body")JsonNode body) {
    this.headers = headers;
    this.queryParams = queryParams;
    this.body = body;
}
 
Example #18
Source File: SPARQLServiceConverter.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private String limitOffsetSTR(JsonNode jsonQuery) {
    JsonNode args = jsonQuery.get("args");
    String limitSTR = "";
    String offsetSTR = "";
    if (args != null) {
        if (args.has("limit")) {
            limitSTR = limitSTR(args.get("limit").asInt());
        }
        if (args.has("offset")) {
            offsetSTR = offsetSTR(args.get("offset").asInt());
        }
    }
    return limitSTR + offsetSTR;
}
 
Example #19
Source File: PrimitiveObjectToJsonNode.java    From yosegi with Apache License 2.0 5 votes vote down vote up
/**
 * Convert PrimitiveObject to JsonNode.
 */
public static JsonNode get( final PrimitiveObject obj ) throws IOException {
  if ( obj == null ) {
    return NullNode.getInstance();
  }
  switch ( obj.getPrimitiveType() ) {
    case BOOLEAN:
      return BooleanNode.valueOf( obj.getBoolean() );
    case BYTE:
      return IntNode.valueOf( obj.getInt() );
    case SHORT:
      return IntNode.valueOf( obj.getInt() );
    case INTEGER:
      return IntNode.valueOf( obj.getInt() );
    case LONG:
      return new LongNode( obj.getLong() );
    case FLOAT:
      return new DoubleNode( obj.getDouble() );
    case DOUBLE:
      return new DoubleNode( obj.getDouble() );
    case STRING:
      return new TextNode( obj.getString() );
    case BYTES:
      return new BinaryNode( obj.getBytes() );
    default:
      return NullNode.getInstance();
  }
}
 
Example #20
Source File: HttpApiTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testGzipAsync() throws Exception {
    HttpResponse<JsonNode> jsonResponse =
            new GetRequest("http://httpbin.org/gzip").asJsonAsync().get();
    assertThat(jsonResponse.headers().size() > 0);
    assertThat(jsonResponse.body().toString().length() > 0);

    assertThat(jsonResponse.code()).isEqualTo(OK);
    JsonNode json = jsonResponse.body();
    assertThat(json.get("gzipped").asBoolean());
}
 
Example #21
Source File: JsonPatchApplierTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void addDescription() throws Exception {
  JsonNode road = mapper.readTree("{}");

  List<PatchOperation> operations = singletonList(PatchOperation.add("/description", "description1"));

  JsonNode result = underTest.apply(road, operations);

  assertThat(result.isMissingNode(), is(false));
  assertThat(result.get("description").textValue(), is("description1"));
}
 
Example #22
Source File: VplsAppConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Activate, deactivates, sets the encapsulation type for a given VPLS.
 *
 * @param vplsName the vplsName of the VPLS
 * @param encap the encapsulation type, if set
 */
public void setEncap(String vplsName, EncapsulationType encap) {
    JsonNode vplsNodes = object.get(VPLS);
    vplsNodes.forEach(vplsNode -> {
        if (hasNamedNode(vplsNode, vplsName)) {
            ((ObjectNode) vplsNode).put(ENCAPSULATION, encap.toString());
        }
    });
}
 
Example #23
Source File: GenericDiscoveryContext.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public T unMarshallJson(JsonNode node) throws Exception
{
    T payload;
    ObjectMapper mapper = new ObjectMapper();
    //noinspection unchecked
    payload = (T)mapper.readValue(node.toString(), payloadType.getRawType());
    return payload;
}
 
Example #24
Source File: DefaultWorkplaceDescription.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode toJson() {
    ObjectNode root = JsonNodeFactory.instance.objectNode();
    root.put(WP_NAME, name());
    if (data().isPresent()) {
        root.put(WP_DATA, data().get());
    }
    return root;
}
 
Example #25
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@ApiAction
public Result getPetById(Long petId) throws Exception {
    Pet obj = imp.getPetById(petId);
    if (configuration.getBoolean("useOutputBeanValidation")) {
        OpenAPIUtils.validate(obj);
    }
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
Example #26
Source File: GetInstanceResponseUnmarshaller.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public GetInstanceResponse unmarshall(InputStream inputStream)
        throws Exception {
    String streamContents = Unmarshallers.readStreamContents(inputStream);

    JsonNode root = JsonUtils.jsonNodeOf(streamContents);
    if (!root.isObject()) {
        throw new BceClientException("input json object:"
                                           + root.toString()
                                           + " is not an object");
    }

    JsonNode tableObj = root.get(MolaDbConstants.JSON_TABLENAMES);
    String desc = root.get(MolaDbConstants.JSON_DESCRIPTION).asText();
    String name = root.get(MolaDbConstants.JSON_NAME).asText();
    result.setDescription(desc);
    result.setInstanceName(name);

    List<String> tableNames = new ArrayList<String>();
    Iterator<JsonNode> tableList = tableObj.elements();
    while (tableList.hasNext()) {
        JsonNode table = tableList.next();
        tableNames.add(table.asText());
    }
    result.setTableNames(tableNames);
    return result;
}
 
Example #27
Source File: MongoSettings.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
@Override
public void updateSettings(JsonNode value) {
	BasicDBObject find = new BasicDBObject("nation", nation);
	DBObject obj = (DBObject)JSON.parse(value.toString());
	BasicDBObject update = new BasicDBObject("$set", obj);
	this.users.update(find, update);
}
 
Example #28
Source File: TraceContext.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
JsonNode toJson() {
  ArrayNode jsonLogs = JsonUtils.newArrayNode();
  for (LogEntry log : _logs) {
    jsonLogs.add(log.toJson());
  }
  return JsonUtils.newObjectNode().set(_traceId, jsonLogs);
}
 
Example #29
Source File: MockStep.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> getHeadersMap() {
    ObjectMapper objectMapper = new ObjectMapperProvider().get();
    HashMap<String, Object> headersMap = new HashMap<>();
    try {
        final JsonNode headersNode = request.get("headers");
        if (null != headersNode) {
            headersMap = (HashMap<String, Object>) objectMapper.readValue(headersNode.toString(), HashMap.class);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return headersMap;
}
 
Example #30
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public Map<String, Parameter> getParameters(ObjectNode obj, String location, ParseResult result, boolean underComponents) {
    if (obj == null) {
        return null;
    }
    Map<String, Parameter> parameters = new LinkedHashMap<>();
    Set<String> filter = new HashSet<>();
    Parameter parameter=null;

    Set<String> parameterKeys = getKeys(obj);
    for(String parameterName : parameterKeys) {
        if(underComponents) {
            if (!Pattern.matches("^[a-zA-Z0-9\\.\\-_]+$",
                    parameterName)) {
                result.warning(location, "Parameter name " + parameterName + " doesn't adhere to regular expression ^[a-zA-Z0-9\\.\\-_]+$");
            }
        }

        JsonNode parameterValue = obj.get(parameterName);
        if (parameterValue.getNodeType().equals(JsonNodeType.OBJECT)) {
            ObjectNode parameterObj = (ObjectNode) parameterValue;
            if(parameterObj != null) {
                 parameter = getParameter(parameterObj, String.format("%s.%s", location, parameterName), result);
                if (parameter != null) {
                    if(PATH_PARAMETER.equalsIgnoreCase(parameter.getIn()) && Boolean.FALSE.equals(parameter.getRequired())){
                        result.warning(location, "For path parameter "+ parameterName + " the required value should be true");
                    }
                    parameters.put(parameterName, parameter);
                }
            }
        }

    }
    return parameters;
}