Пример #1
0
  @Test
  public void testLoadTwoRootObjectsWithNoType() throws JsonProcessingException {
    JsonNode data =
        mapper
            .createArrayNode()
            .add(
                mapper.createObjectNode().put("userId", "1").put("name", "Paul").put("sex", "MALE"))
            .add(
                mapper
                    .createObjectNode()
                    .put("userId", "2")
                    .put("name", "Anna")
                    .put("sex", "FEMALE"));

    Resource result =
        mapper
            .reader()
            .withAttribute(RESOURCE_SET, resourceSet)
            .withAttribute(ROOT_ELEMENT, ModelPackage.Literals.USER)
            .treeToValue(data, Resource.class);

    assertNotNull(result);
    assertEquals(2, result.getContents().size());

    User first = (User) result.getContents().get(0);
    User second = (User) result.getContents().get(1);

    assertEquals("1", first.getUserId());
    assertEquals("Paul", first.getName());
    assertEquals("MALE", first.getSex().getLiteral());

    assertEquals("2", second.getUserId());
    assertEquals("Anna", second.getName());
    assertEquals("FEMALE", second.getSex().getLiteral());
  }
Пример #2
0
  public ObjectNode buildFormatsData(final ObjectMapper objectMapper, final Model model) {

    final ObjectNode formatsNode = objectMapper.createObjectNode();

    final Context context = model.getContext();
    final FormatLoader formatLoader = context.getFormatLoader();
    final SortedSet<URI> formatUris = formatLoader.getLoadedFormatUris();
    final URI defaultFormatUri = formatLoader.getDefaultFormatUri();

    for (final URI formatUri : formatUris) {
      final Formatter formatter = formatLoader.getFormatter(formatUri);
      if (formatter.isApplicableTo(model.getSchemaUri())) {

        final Format format = formatLoader.loadFormat(formatUri);
        final String mediaTypeString = String.valueOf(format.getMediaType());
        final ObjectNode formatNode = objectMapper.createObjectNode();
        formatsNode.put(mediaTypeString, formatNode);

        formatNode.put("uri", String.valueOf(formatUri));
        formatNode.put("title", format.getTitle());
        formatNode.put("mediaType", mediaTypeString);
        formatNode.put("fileExtension", format.getFileExtension());
        formatNode.put("isDefault", formatUri.equals(defaultFormatUri));
      }
    }

    return formatsNode;
  }
Пример #3
0
  /**
   * Sends a message envelope on this socket
   *
   * @param envelope The message envelope
   * @return This socket instance
   * @throws IOException Thrown if the message cannot be sent
   */
  public Socket push(final Envelope envelope) throws IOException {
    LOG.log(Level.FINE, "Pushing envelope: {0}", envelope);
    final ObjectNode node = objectMapper.createObjectNode();
    node.put("topic", envelope.getTopic());
    node.put("event", envelope.getEvent());
    node.put("ref", envelope.getRef());
    node.set(
        "payload",
        envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload());
    final String json = objectMapper.writeValueAsString(node);
    LOG.log(Level.FINE, "Sending JSON: {0}", json);

    RequestBody body = RequestBody.create(WebSocket.TEXT, json);

    if (this.isConnected()) {
      try {
        webSocket.sendMessage(body);
      } catch (IllegalStateException e) {
        LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e);
      }
    } else {
      this.sendBuffer.add(body);
    }

    return this;
  }
Пример #4
0
  @Test
  public void testSaveTwoRootObjectsWithNoType() {
    JsonNode expected =
        mapper
            .createArrayNode()
            .add(mapper.createObjectNode().put("userId", "1").put("name", "Paul"))
            .add(
                mapper
                    .createObjectNode()
                    .put("userId", "2")
                    .put("name", "Anna")
                    .put("sex", "FEMALE"));

    User u1 = ModelFactory.eINSTANCE.createUser();
    u1.setUserId("1");
    u1.setName("Paul");

    User u2 = ModelFactory.eINSTANCE.createUser();
    u2.setUserId("2");
    u2.setName("Anna");
    u2.setSex(Sex.FEMALE);

    Resource resource = new JsonResource(URI.createURI("test"), mapper);
    resource.getContents().add(u1);
    resource.getContents().add(u2);

    JsonNode result = mapper.valueToTree(resource);

    assertEquals(expected, result);
  }
Пример #5
0
 /**
  * Convenience method for creating an error response.
  *
  * @param jsonRpc the jsonrpc string
  * @param id the id
  * @param code the error code
  * @param httpCode the http error code
  * @param message the error message
  * @param data the error data (if any)
  * @return the error response
  */
 protected JsonRpcServerResponse createErrorResponse(
     String jsonRpc, Object id, int code, int httpCode, String message, Object data) {
   ObjectNode response = mapper.createObjectNode();
   ObjectNode error = mapper.createObjectNode();
   error.put("code", code);
   error.put("message", message);
   if (data != null) {
     error.put("data", mapper.valueToTree(data));
   }
   response.put("jsonrpc", jsonRpc);
   if (Integer.class.isInstance(id)) {
     response.put("id", Integer.class.cast(id).intValue());
   } else if (Long.class.isInstance(id)) {
     response.put("id", Long.class.cast(id).longValue());
   } else if (Float.class.isInstance(id)) {
     response.put("id", Float.class.cast(id).floatValue());
   } else if (Double.class.isInstance(id)) {
     response.put("id", Double.class.cast(id).doubleValue());
   } else if (BigDecimal.class.isInstance(id)) {
     response.put("id", BigDecimal.class.cast(id));
   } else {
     response.put("id", String.class.cast(id));
   }
   response.put("error", error);
   return new JsonRpcServerResponse(response, httpCode);
 }
Пример #6
0
  @Override
  public void execute() throws MojoExecutionException {
    try {
      JavaProjectBuilder builder = new JavaProjectBuilder();
      builder.addSourceTree(new File(srcDirectory, "src/main/java"));

      ObjectNode root = initializeRoot();
      ArrayNode tags = mapper.createArrayNode();
      ObjectNode paths = mapper.createObjectNode();
      ObjectNode definitions = mapper.createObjectNode();

      root.set("tags", tags);
      root.set("paths", paths);
      root.set("definitions", definitions);

      builder.getClasses().forEach(jc -> processClass(jc, paths, tags, definitions));

      if (paths.size() > 0) {
        getLog().info("Generating ONOS REST API documentation...");
        genCatalog(root);

        if (!isNullOrEmpty(apiPackage)) {
          genRegistrator();
        }
      }

      project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());

    } catch (Exception e) {
      getLog().warn("Unable to generate ONOS REST API documentation", e);
      throw e;
    }
  }
Пример #7
0
  // Temporary solution to add responses to a method
  // TODO Provide annotations in the web resources for responses and parse them
  private void addResponses(ObjectNode methodNode) {
    ObjectNode responses = mapper.createObjectNode();
    methodNode.set("responses", responses);

    ObjectNode success = mapper.createObjectNode();
    success.put("description", "successful operation");
    responses.set("200", success);

    ObjectNode defaultObj = mapper.createObjectNode();
    defaultObj.put("description", "Unexpected error");
    responses.set("default", defaultObj);
  }
  protected void createDataAssociation(
      DataAssociation dataAssociation, boolean incoming, Activity activity) {
    String sourceRef = null;
    String targetRef = null;
    if (incoming) {
      sourceRef = dataAssociation.getSourceRef();
      targetRef = activity.getId();

    } else {
      sourceRef = activity.getId();
      targetRef = dataAssociation.getTargetRef();
    }

    ObjectNode flowNode =
        BpmnJsonConverterUtil.createChildShape(
            dataAssociation.getId(), STENCIL_DATA_ASSOCIATION, 172, 212, 128, 212);
    ArrayNode dockersArrayNode = objectMapper.createArrayNode();
    ObjectNode dockNode = objectMapper.createObjectNode();

    dockNode.put(EDITOR_BOUNDS_X, model.getGraphicInfo(sourceRef).getWidth() / 2.0);
    dockNode.put(EDITOR_BOUNDS_Y, model.getGraphicInfo(sourceRef).getHeight() / 2.0);
    dockersArrayNode.add(dockNode);

    if (model.getFlowLocationGraphicInfo(dataAssociation.getId()).size() > 2) {
      for (int i = 1;
          i < model.getFlowLocationGraphicInfo(dataAssociation.getId()).size() - 1;
          i++) {
        GraphicInfo graphicInfo = model.getFlowLocationGraphicInfo(dataAssociation.getId()).get(i);
        dockNode = objectMapper.createObjectNode();
        dockNode.put(EDITOR_BOUNDS_X, graphicInfo.getX());
        dockNode.put(EDITOR_BOUNDS_Y, graphicInfo.getY());
        dockersArrayNode.add(dockNode);
      }
    }

    dockNode = objectMapper.createObjectNode();
    dockNode.put(EDITOR_BOUNDS_X, model.getGraphicInfo(targetRef).getWidth() / 2.0);
    dockNode.put(EDITOR_BOUNDS_Y, model.getGraphicInfo(targetRef).getHeight() / 2.0);
    dockersArrayNode.add(dockNode);
    flowNode.put("dockers", dockersArrayNode);
    ArrayNode outgoingArrayNode = objectMapper.createArrayNode();
    outgoingArrayNode.add(BpmnJsonConverterUtil.createResourceNode(targetRef));
    flowNode.put("outgoing", outgoingArrayNode);
    flowNode.put("target", BpmnJsonConverterUtil.createResourceNode(targetRef));

    ObjectNode propertiesNode = objectMapper.createObjectNode();
    propertiesNode.put(PROPERTY_OVERRIDE_ID, dataAssociation.getId());

    flowNode.put(EDITOR_SHAPE_PROPERTIES, propertiesNode);
    shapesArrayNode.add(flowNode);
  }
Пример #9
0
  private void processRestMethod(
      JavaMethod javaMethod,
      String method,
      Map<String, ObjectNode> pathMap,
      String resourcePath,
      ArrayNode tagArray,
      ObjectNode definitions) {
    String fullPath = resourcePath, consumes = "", produces = "", comment = javaMethod.getComment();
    DocletTag tag = javaMethod.getTagByName("rsModel");
    for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
      String name = annotation.getType().getName();
      if (name.equals(PATH)) {
        fullPath = resourcePath + "/" + getPath(annotation);
        fullPath = fullPath.replaceFirst("^//", "/");
      }
      if (name.equals(CONSUMES)) {
        consumes = getIOType(annotation);
      }
      if (name.equals(PRODUCES)) {
        produces = getIOType(annotation);
      }
    }
    ObjectNode methodNode = mapper.createObjectNode();
    methodNode.set("tags", tagArray);

    addSummaryDescriptions(methodNode, comment);
    addJsonSchemaDefinition(definitions, tag);
    addJsonSchemaDefinition(definitions, tag);

    processParameters(javaMethod, methodNode, method, tag);

    processConsumesProduces(methodNode, "consumes", consumes);
    processConsumesProduces(methodNode, "produces", produces);
    if (tag == null
        || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))
            && !(tag.getParameters().size() > 1))) {
      addResponses(methodNode, tag, false);
    } else {
      addResponses(methodNode, tag, true);
    }

    ObjectNode operations = pathMap.get(fullPath);
    if (operations == null) {
      operations = mapper.createObjectNode();
      operations.set(method, methodNode);
      pathMap.put(fullPath, operations);
    } else {
      operations.set(method, methodNode);
    }
  }
Пример #10
0
  // Checks whether javaClass has a path tag associated with it and if it does
  // processes its methods and creates a tag for the class on the root
  void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags) {
    // If the class does not have a Path tag then ignore it
    JavaAnnotation annotation = getPathAnnotation(javaClass);
    if (annotation == null) {
      return;
    }

    String path = getPath(annotation);
    if (path == null) {
      return;
    }

    String resourcePath = "/" + path;
    String tagPath = path.isEmpty() ? "/" : path;

    // Create tag node for this class.
    ObjectNode tagObject = mapper.createObjectNode();
    tagObject.put("name", tagPath);
    if (javaClass.getComment() != null) {
      tagObject.put("description", shortText(javaClass.getComment()));
    }
    tags.add(tagObject);

    // Create an array node add to all methods from this class.
    ArrayNode tagArray = mapper.createArrayNode();
    tagArray.add(tagPath);

    processAllMethods(javaClass, resourcePath, paths, tagArray);
  }
Пример #11
0
 public JsonNode toObjectArray(ObjectMapper mapper) throws WampError {
   ArrayNode messageNode = mapper.createArrayNode();
   if (details != null) messageNode.add(details);
   else messageNode.add(mapper.createObjectNode());
   messageNode.add(reason.toString());
   return messageNode;
 }
Пример #12
0
  /** Registers with the Neo4j server and saves some Neo4j server information with this object. */
  public void register() {
    logger.debug("[register] uri = {}", getManagementUri());

    JsonNode jsonNode;
    ObjectMapper objectMapper = jsonObjectMapper.getObjectMapperBinary();
    ObjectNode objectNode = objectMapper.createObjectNode();
    objectNode.put(CommandParameters.METHOD, "register");

    try {
      jsonNode =
          objectMapper.readTree(
              managementConnection.sendWithResult(objectMapper.writeValueAsBytes(objectNode)));
    } catch (Exception e) {
      logger.error("[register] could not register at server");
      return;
    }

    id = jsonNode.get("id").asText();
    setMaster(jsonNode.get("isMaster").asBoolean());

    managementConnection.setServerId(id);

    logger.debug(
        "[register] id = {}, isMaster = {}, uri = {}", getId(), isMaster(), getManagementUri());
  }
  public void testFromMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    root.put(FIELD4, TEXT2);
    root.put(FIELD3, -1);
    root.putArray(FIELD2);
    root.put(FIELD1, DOUBLE_VALUE);

    /* Let's serialize using one of two alternate methods:
     * first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromMap(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromMap(root.toString());
  }
Пример #14
0
  @At("/?/json")
  @Ok("raw")
  public ObjectNode getEditorJson(String modelId) {
    ObjectNode modelNode = null;

    Model model = repositoryService.getModel(modelId);

    if (model != null) {
      try {
        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isNotEmpty(model.getMetaInfo())) {
          modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        } else {
          modelNode = objectMapper.createObjectNode();
          modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
        }
        modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId());
        ObjectNode editorJsonNode =
            (ObjectNode)
                objectMapper.readTree(
                    new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
        modelNode.put("model", editorJsonNode);

      } catch (Exception e) {
        log.error("Error creating model JSON", e);
        throw new ActivitiException("Error creating model JSON", e);
      }
    }
    return modelNode;
  }
Пример #15
0
  /**
   * Converts partition info into a JSON object.
   *
   * @param partitionInfo partition descriptions
   */
  private JsonNode json(List<PartitionInfo> partitionInfo) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode partitions = mapper.createArrayNode();

    // Create a JSON node for each partition
    partitionInfo
        .stream()
        .forEach(
            info -> {
              ObjectNode partition = mapper.createObjectNode();

              // Add each member to the "members" array for this partition
              ArrayNode members = partition.putArray("members");
              info.members().stream().forEach(members::add);

              // Complete the partition attributes and add it to the array
              partition
                  .put("name", info.name())
                  .put("term", info.term())
                  .put("leader", info.leader());
              partitions.add(partition);
            });

    return partitions;
  }
Пример #16
0
 /*
  * (non-Javadoc)
  *
  * @see
  * com.ssachtleben.play.plugin.auth.providers.BaseProvider#handle(play.mvc
  * .Http.Context)
  */
 @Override
 protected AuthUser handle(Context context) {
   String contentType = context.request().getHeader("content-type");
   if ("application/json".equals(contentType)) {
     JsonNode node = context.request().body().asJson();
     return new PasswordEmailAuthUser(
         node.get(RequestParameter.EMAIL).asText(),
         node.get(RequestParameter.PASSWORD).asText(),
         node);
   } else {
     Map<String, String[]> params = context.request().body().asFormUrlEncoded();
     if (params != null
         && params.containsKey(RequestParameter.EMAIL)
         && params.containsKey(RequestParameter.PASSWORD)) {
       ObjectMapper mapper = new ObjectMapper();
       JsonNode data;
       try {
         data = mapper.readTree(mapper.writeValueAsString(params));
       } catch (IOException e) {
         logger().error("Failed to serialize params to json", e);
         data = mapper.createObjectNode();
       }
       return new PasswordEmailAuthUser(
           params.get(RequestParameter.EMAIL)[0], params.get(RequestParameter.PASSWORD)[0], data);
     }
   }
   return null;
 }
Пример #17
0
  // Temporary solution to add responses to a method
  private void addResponses(ObjectNode methodNode, DocletTag tag, boolean responseJson) {
    ObjectNode responses = mapper.createObjectNode();
    methodNode.set("responses", responses);

    ObjectNode success = mapper.createObjectNode();
    success.put("description", "successful operation");
    responses.set("200", success);
    if (tag != null && responseJson) {
      ObjectNode schema = mapper.createObjectNode();
      tag.getParameters().stream().forEach(param -> schema.put("$ref", "#/definitions/" + param));
      success.set("schema", schema);
    }

    ObjectNode defaultObj = mapper.createObjectNode();
    defaultObj.put("description", "Unexpected error");
    responses.set("default", defaultObj);
  }
Пример #18
0
 public JsonNode toObjectArray(ObjectMapper mapper) throws WampError {
   ArrayNode messageNode = mapper.createArrayNode();
   messageNode.add(ID);
   messageNode.add(signature);
   if (extra != null) messageNode.add(extra);
   else messageNode.add(mapper.createObjectNode());
   return messageNode;
 }
  private Settings createSettings() {
    ObjectNode indexConfigSettingsNode = objectMapper.createObjectNode();
    indexConfigSettingsNode.put("number_of_shards", 2).put("number_of_replicas", 1);

    return ImmutableSettings.settingsBuilder()
        .loadFromSource(indexConfigSettingsNode.toString())
        .build();
  }
Пример #20
0
 /** api接口用的 */
 public static String getResponseResult4Value(ObjectMapper objectMapper, JsonNode jsonNode) {
   ObjectNode resultObjectNode = objectMapper.createObjectNode();
   resultObjectNode.put("status", 200);
   if (jsonNode != null) {
     resultObjectNode.put("data", jsonNode);
   }
   resultObjectNode.put("statusText", "OK");
   return resultObjectNode.toString();
 }
  protected void addFieldExtensions(List<FieldExtension> extensions, ObjectNode propertiesNode) {
    ObjectNode fieldExtensionsNode = objectMapper.createObjectNode();
    ArrayNode itemsNode = objectMapper.createArrayNode();
    for (FieldExtension extension : extensions) {
      ObjectNode propertyItemNode = objectMapper.createObjectNode();
      propertyItemNode.put(PROPERTY_SERVICETASK_FIELD_NAME, extension.getFieldName());
      if (StringUtils.isNotEmpty(extension.getStringValue())) {
        propertyItemNode.put(PROPERTY_SERVICETASK_FIELD_STRING_VALUE, extension.getStringValue());
      }
      if (StringUtils.isNotEmpty(extension.getExpression())) {
        propertyItemNode.put(PROPERTY_SERVICETASK_FIELD_EXPRESSION, extension.getExpression());
      }
      itemsNode.add(propertyItemNode);
    }

    fieldExtensionsNode.put("fields", itemsNode);
    propertiesNode.put(PROPERTY_SERVICETASK_FIELDS, fieldExtensionsNode);
  }
Пример #22
0
 public JsonNode toObjectArray(ObjectMapper mapper) throws WampError {
   ArrayNode messageNode = mapper.createArrayNode();
   messageNode.add(ID);
   messageNode.add(requestId);
   if (options != null) messageNode.add(options);
   else messageNode.add(mapper.createObjectNode());
   messageNode.add(procedure.toString());
   return messageNode;
 }
  protected void addFormProperties(List<FormProperty> formProperties, ObjectNode propertiesNode) {
    if (CollectionUtils.isEmpty(formProperties)) return;

    ObjectNode formPropertiesNode = objectMapper.createObjectNode();
    ArrayNode propertiesArrayNode = objectMapper.createArrayNode();
    for (FormProperty property : formProperties) {
      ObjectNode propertyItemNode = objectMapper.createObjectNode();
      propertyItemNode.put(PROPERTY_FORM_ID, property.getId());
      propertyItemNode.put(PROPERTY_FORM_NAME, property.getName());
      propertyItemNode.put(PROPERTY_FORM_TYPE, property.getType());
      if (StringUtils.isNotEmpty(property.getExpression())) {
        propertyItemNode.put(PROPERTY_FORM_EXPRESSION, property.getExpression());
      } else {
        propertyItemNode.putNull(PROPERTY_FORM_EXPRESSION);
      }
      if (StringUtils.isNotEmpty(property.getVariable())) {
        propertyItemNode.put(PROPERTY_FORM_VARIABLE, property.getVariable());
      } else {
        propertyItemNode.putNull(PROPERTY_FORM_VARIABLE);
      }
      if (StringUtils.isNotEmpty(property.getDatePattern())) {
        propertyItemNode.put(PROPERTY_FORM_DATE_PATTERN, property.getDatePattern());
      }
      if (CollectionUtils.isNotEmpty(property.getFormValues())) {
        ArrayNode valuesNode = objectMapper.createArrayNode();
        for (FormValue formValue : property.getFormValues()) {
          ObjectNode valueNode = objectMapper.createObjectNode();
          valueNode.put(PROPERTY_FORM_ENUM_VALUES_NAME, formValue.getName());
          valueNode.put(PROPERTY_FORM_ENUM_VALUES_ID, formValue.getId());
          valuesNode.add(valueNode);
        }
        propertyItemNode.put(PROPERTY_FORM_ENUM_VALUES, valuesNode);
      }
      propertyItemNode.put(PROPERTY_FORM_REQUIRED, property.isRequired());
      propertyItemNode.put(PROPERTY_FORM_READABLE, property.isReadable());
      propertyItemNode.put(PROPERTY_FORM_WRITABLE, property.isWriteable());

      propertiesArrayNode.add(propertyItemNode);
    }

    formPropertiesNode.put("formProperties", propertiesArrayNode);
    propertiesNode.put(PROPERTY_FORM_PROPERTIES, formPropertiesNode);
  }
 @Override
 protected void terminate() {
   log.debug("Cleanup Starts");
   if (ostream == null) {
     return; // no connection to terminate
   }
   this.forwardToPort(
       new JsonClientMessage(mapper.createObjectNode().put(JSON.TYPE, JSON.GOODBYE)), null);
   this.disconnectPort(this.controller);
 }
Пример #25
0
 /**
  * Returns {@code object} serialized to a JsonNode.
  *
  * @throws RuntimeException if deserialization fails
  */
 public static JsonNode toJsonNode(Object object) {
   try {
     ObjectNode rootNode = mapper.createObjectNode();
     JsonNode node = mapper.valueToTree(object);
     rootNode.put(rootNameFor(Types.deProxy(object.getClass())), node);
     return rootNode;
   } catch (Exception e) {
     throw Exceptions.uncheck(e, "Failed to serialize object: {}", object);
   }
 }
Пример #26
0
  // Processes parameters of javaMethod and enters the proper key-values into the methodNode
  private void processParameters(JavaMethod javaMethod, ObjectNode methodNode) {
    ArrayNode parameters = mapper.createArrayNode();
    methodNode.set("parameters", parameters);
    boolean required = true;

    for (JavaParameter javaParameter : javaMethod.getParameters()) {
      ObjectNode individualParameterNode = mapper.createObjectNode();
      Optional<JavaAnnotation> optional =
          javaParameter
              .getAnnotations()
              .stream()
              .filter(
                  annotation ->
                      annotation.getType().getName().equals(PATH_PARAM)
                          || annotation.getType().getName().equals(QUERY_PARAM))
              .findAny();
      JavaAnnotation pathType = optional.isPresent() ? optional.get() : null;

      String annotationName = javaParameter.getName();

      if (pathType != null) { // the parameter is a path or query parameter
        individualParameterNode.put(
            "name", pathType.getNamedParameter("value").toString().replace("\"", ""));
        if (pathType.getType().getName().equals(PATH_PARAM)) {
          individualParameterNode.put("in", "path");
        } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
          individualParameterNode.put("in", "query");
        }
        individualParameterNode.put("type", getType(javaParameter.getType()));
      } else { // the parameter is a body parameter
        individualParameterNode.put("name", annotationName);
        individualParameterNode.put("in", "body");

        // TODO add actual hardcoded schemas and a type
        // body parameters must have a schema associated with them
        ArrayNode schema = mapper.createArrayNode();
        individualParameterNode.set("schema", schema);
      }
      for (DocletTag p : javaMethod.getTagsByName("param")) {
        if (p.getValue().contains(annotationName)) {
          try {
            String description = p.getValue().split(" ", 2)[1].trim();
            if (description.contains("optional")) {
              required = false;
            }
            individualParameterNode.put("description", description);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      individualParameterNode.put("required", required);
      parameters.add(individualParameterNode);
    }
  }
Пример #27
0
  @Test
  public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
    final JsonNode node = mapper.createObjectNode();
    ((ObjectNode) node).put("id", 2016);
    ((ObjectNode) node).put("name", "baeldung.com");

    final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);

    assertEquals(2016, toValue.getId());
    assertEquals("baeldung.com", toValue.getName());
  }
Пример #28
0
 public JsonNode toObjectArray(ObjectMapper mapper) throws WampError {
   ArrayNode messageNode = mapper.createArrayNode();
   messageNode.add(ID);
   messageNode.add(requestId);
   if (details != null) messageNode.add(details);
   else messageNode.add(mapper.createObjectNode());
   if (arguments != null) messageNode.add(arguments);
   else if (argumentsKw != null) messageNode.add(mapper.createArrayNode());
   if (argumentsKw != null) messageNode.add(argumentsKw);
   return messageNode;
 }
 protected <T> ObjectNode toJsonBase(Attribute<T> src) {
   ObjectNode root = mapper.createObjectNode();
   root.put("visibility", src.getVisibility().name());
   if (src.getRemoteIdp() != null) root.put("remoteIdp", src.getRemoteIdp());
   if (src.getTranslationProfile() != null)
     root.put("translationProfile", src.getTranslationProfile());
   ArrayNode values = root.putArray("values");
   AttributeValueSyntax<T> syntax = src.getAttributeSyntax();
   for (T value : src.getValues()) values.add(syntax.serialize(value));
   return root;
 }
Пример #30
0
  @Test
  public void testSaveSingleObjectWithNoType() {
    JsonNode expected = mapper.createObjectNode().put("userId", "1").put("name", "Paul");

    User u1 = ModelFactory.eINSTANCE.createUser();
    u1.setUserId("1");
    u1.setName("Paul");

    JsonNode result = mapper.valueToTree(u1);

    assertEquals(expected, result);
  }