Example #1
0
  /**
   * Get the first XMPP url of an agent from its id. If no agent with given id is connected via
   * XMPP, null is returned.
   *
   * @param agentId The id of the agent
   * @return agentUrl
   */
  @Override
  public String getAgentUrl(String agentId) {
    try {
      ArrayNode conns = getConns(agentId);
      if (conns != null) {
        for (JsonNode conn : conns) {
          ObjectNode params = (ObjectNode) conn;

          String encryptedUsername =
              params.has("username") ? params.get("username").textValue() : null;
          String encryptedResource =
              params.has("resource") ? params.get("resource").textValue() : null;
          if (encryptedUsername != null) {
            String username = EncryptionUtil.decrypt(encryptedUsername);
            String resource = null;
            if (encryptedResource != null) {
              resource = EncryptionUtil.decrypt(encryptedResource);
            }
            return generateUrl(username, host, resource);
          }
        }
      }
    } catch (Exception e) {
      LOG.log(Level.WARNING, "", e);
    }
    return null;
  }
  public ExternalDocs externalDocs(ObjectNode node, String location, ParseResult result) {
    ExternalDocs output = null;

    if (node != null) {
      output = new ExternalDocs();
      Set<String> keys = getKeys(node);

      String value = getString("description", node, false, location, result);
      output.description(value);

      value = getString("url", node, true, location, result);
      output.url(value);

      // extra keys
      for (String key : keys) {
        if (key.startsWith("x-")) {
          output.setVendorExtension(key, extension(node.get(key)));
        } else if (!EXTERNAL_DOCS_KEYS.contains(key)) {
          result.extra(location + ".externalDocs", key, node.get(key));
        }
      }
    }

    return output;
  }
Example #3
0
 @Test
 public void testUser() {
   final JsonBuilder jb = new JsonBuilder();
   final String randomId = UUID.randomUUID().toString();
   final User user =
       new User() {
         @Override
         public String getId() {
           return randomId;
         }
       };
   user.setName("Test User");
   user.setEmail("*****@*****.**");
   user.setVerified(true);
   // Get JSON
   final ObjectNode json = jb.toJson(user, false);
   assertThat(json.get("id")).isNotNull();
   assertThat(json.get("id").asText()).isEqualTo(user.getId());
   assertThat(json.get("name")).isNotNull();
   assertThat(json.get("name").asText()).isEqualTo(user.getName());
   assertThat(json.get("email")).isNotNull();
   assertThat(json.get("email").asText()).isEqualTo(user.getEmail());
   assertThat(json.get("isAdmin")).isNotNull();
   assertThat(json.get("isAdmin").asBoolean()).isEqualTo(false);
   assertThat(json.get("isVerified")).isNotNull();
   assertThat(json.get("isVerified").asBoolean()).isEqualTo(true);
 }
  public Tag tag(ObjectNode node, String location, ParseResult result) {
    Tag tag = null;

    if (node != null) {
      tag = new Tag();
      Set<String> keys = getKeys(node);

      String value = getString("name", node, true, location, result);
      tag.name(value);

      value = getString("description", node, false, location, result);
      tag.description(value);

      ObjectNode externalDocs = getObject("externalDocs", node, false, location, result);
      ExternalDocs docs = externalDocs(externalDocs, location + "externalDocs", result);
      tag.externalDocs(docs);

      // extra keys
      for (String key : keys) {
        if (key.startsWith("x-")) {
          tag.setVendorExtension(key, extension(node.get(key)));
        } else if (!TAG_KEYS.contains(key)) {
          result.extra(location + ".externalDocs", key, node.get(key));
        }
      }
    }

    return tag;
  }
Example #5
0
  @Test
  public void testNotification() {
    final JsonBuilder jb = new JsonBuilder();
    final String randomId = UUID.randomUUID().toString();
    final Notification notification =
        new Notification() {
          @Override
          public String getId() {
            return randomId;
          }

          @Override
          public Date getCreated() {
            return new Date(0);
          }
        };
    notification.setMessage("Test message.");
    // Get JSON
    final ObjectNode json = jb.toJson(notification);
    assertThat(json.get("id")).isNotNull();
    assertThat(json.get("id").asText()).isEqualTo(notification.getId());
    assertThat(json.get("read")).isNotNull();
    assertThat(json.get("read").asBoolean()).isEqualTo(false);
    assertThat(json.get("message")).isNotNull();
    assertThat(json.get("message").asText()).isEqualTo(notification.getMessage());
    assertThat(json.get("timestamp")).isNotNull();
    assertThat(json.get("timestamp").asText())
        .isEqualTo(ISO8601Utils.format(notification.getCreated(), true, TimeZone.getDefault()));
  }
Example #6
0
  /**
   * Disconnect the agent from the connected messaging service(s) (if any)
   *
   * @param agentId
   */
  @Access(AccessType.UNAVAILABLE)
  public final void disconnect(String agentId) {

    try {
      ArrayNode conns = getConns(agentId);
      if (conns != null) {
        for (JsonNode conn : conns) {
          ObjectNode params = (ObjectNode) conn;

          String encryptedUsername =
              params.has("username") ? params.get("username").textValue() : null;
          String encryptedResource =
              params.has("resource") ? params.get("resource").textValue() : null;
          if (encryptedUsername != null) {
            String username = EncryptionUtil.decrypt(encryptedUsername);
            String resource = null;
            if (encryptedResource != null) {
              resource = EncryptionUtil.decrypt(encryptedResource);
            }

            String url = generateUrl(username, host, resource);
            AgentConnection connection = connectionsByUrl.get(url);
            if (connection != null) {
              connection.disconnect();
              connectionsByUrl.remove(url);
            }
          }
        }
      }
      delConnections(agentId);
    } catch (Exception e) {
      LOG.log(Level.WARNING, "", e);
    }
  }
Example #7
0
 @Override
 public void reconnect(String agentId) throws JSONRPCException, IOException {
   ArrayNode conns = getConns(agentId);
   if (conns != null) {
     for (JsonNode conn : conns) {
       ObjectNode params = (ObjectNode) conn;
       LOG.info("Initializing connection:" + agentId + " --> " + params);
       try {
         String encryptedUsername =
             params.has("username") ? params.get("username").textValue() : null;
         String encryptedPassword =
             params.has("password") ? params.get("password").textValue() : null;
         String encryptedResource =
             params.has("resource") ? params.get("resource").textValue() : null;
         if (encryptedUsername != null && encryptedPassword != null) {
           String username = EncryptionUtil.decrypt(encryptedUsername);
           String password = EncryptionUtil.decrypt(encryptedPassword);
           String resource = null;
           if (encryptedResource != null) {
             resource = EncryptionUtil.decrypt(encryptedResource);
           }
           connect(agentId, username, password, resource);
         }
       } catch (Exception e) {
         throw new JSONRPCException("Failed to connect XMPP.", e);
       }
     }
   }
 }
  @Test
  public void testCollector4() throws Exception {

    ModelPath a =
        ModelPath.builder("Container.parent.backrefs.Content.authors.refs.User.value")
            .addPathMember(
                new ModelPathStep(
                    true, newHashSet("Content"), "parent", backRefs, newHashSet("Container"), null))
            .addPathMember(
                new ModelPathStep(
                    false, newHashSet("Content"), "authors", refs, newHashSet("User"), null))
            .addPathMember(
                new ModelPathStep(
                    false, newHashSet("User"), null, value, null, Arrays.asList("name")))
            .build();

    viewFieldsCollector.add(
        viewDescriptor,
        a,
        new Id[] {new Id(1), new Id(2), new Id(3)},
        new String[] {"Container", "Content", "User"},
        new ViewValue(new long[] {1, 2, 3}, "{\"name\":\"bob\"}".getBytes()),
        1L);
    viewFieldsCollector.done();

    Set<Id> permissions = new HashSet<>();
    permissions.add(new Id(1L));
    permissions.add(new Id(3L));
    ViewResponse viewResponse = viewFieldsCollector.getView(permissions);
    ObjectNode view = viewResponse.getViewBody();
    System.out.println("view=" + view);
    Assert.assertTrue(view.get("all_parent").isArray());
    Assert.assertEquals(view.get("all_parent").size(), 0);
  }
  protected void localize(ProcessInstance processInstance) {
    ExecutionEntity processInstanceExecution = (ExecutionEntity) processInstance;
    processInstanceExecution.setLocalizedName(null);
    processInstanceExecution.setLocalizedDescription(null);

    if (locale != null) {
      String processDefinitionId = processInstanceExecution.getProcessDefinitionId();
      if (processDefinitionId != null) {
        ObjectNode languageNode =
            Context.getLocalizationElementProperties(
                locale,
                processInstanceExecution.getProcessDefinitionKey(),
                processDefinitionId,
                withLocalizationFallback);
        if (languageNode != null) {
          JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
          if (languageNameNode != null && languageNameNode.isNull() == false) {
            processInstanceExecution.setLocalizedName(languageNameNode.asText());
          }

          JsonNode languageDescriptionNode =
              languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
          if (languageDescriptionNode != null && languageDescriptionNode.isNull() == false) {
            processInstanceExecution.setLocalizedDescription(languageDescriptionNode.asText());
          }
        }
      }
    }
  }
  public Response response(ObjectNode node, String location, ParseResult result) {
    if (node == null) return null;

    Response output = new Response();
    JsonNode ref = node.get("$ref");
    if (ref != null) {
      if (ref.getNodeType().equals(JsonNodeType.STRING)) {
        return refResponse((TextNode) ref, location, result);
      } else {
        result.invalidType(location, "$ref", "string", node);
        return null;
      }
    }

    String value = getString("description", node, true, location, result);
    output.description(value);

    ObjectNode schema = getObject("schema", node, false, location, result);
    if (schema != null) {
      output.schema(Json.mapper().convertValue(schema, Property.class));
    }
    ObjectNode headersNode = getObject("headers", node, false, location, result);
    if (headersNode != null) {
      // TODO
      Map<String, Property> headers =
          Json.mapper()
              .convertValue(
                  headersNode,
                  Json.mapper()
                      .getTypeFactory()
                      .constructMapType(Map.class, String.class, Property.class));
      output.headers(headers);
    }

    ObjectNode examplesNode = getObject("examples", node, false, location, result);
    if (examplesNode != null) {
      Map<String, Object> examples =
          Json.mapper()
              .convertValue(
                  examplesNode,
                  Json.mapper()
                      .getTypeFactory()
                      .constructMapType(Map.class, String.class, Object.class));
      output.setExamples(examples);
    }

    // extra keys
    Set<String> keys = getKeys(node);
    for (String key : keys) {
      if (key.startsWith("x-")) {
        output.setVendorExtension(key, extension(node.get(key)));
      } else if (!RESPONSE_KEYS.contains(key)) {
        result.extra(location, key, node.get(key));
      }
    }
    return output;
  }
  public Model allOfModel(ObjectNode node, String location, ParseResult result) {
    JsonNode sub = node.get("$ref");
    JsonNode allOf = node.get("allOf");

    if (sub != null) {
      if (sub.getNodeType().equals(JsonNodeType.OBJECT)) {
        return refModel((ObjectNode) sub, location, result);
      } else {
        result.invalidType(location, "$ref", "object", sub);
        return null;
      }
    } else if (allOf != null) {
      ComposedModel model = null;
      // we only support one parent, no multiple inheritance or composition
      if (allOf.getNodeType().equals(JsonNodeType.ARRAY)) {
        model = new ComposedModel();
        int pos = 0;
        for (JsonNode part : allOf) {
          if (part.getNodeType().equals(JsonNodeType.OBJECT)) {
            Model segment = definition((ObjectNode) part, location, result);
            if (segment != null) {
              model.getAllOf().add(segment);
            }
          } else {
            result.invalidType(location, "allOf[" + pos + "]", "object", part);
          }
          pos++;
        }

        List<Model> allComponents = model.getAllOf();
        if (allComponents.size() >= 1) {
          model.setParent(allComponents.get(0));
          if (allComponents.size() >= 2) {
            model.setChild(allComponents.get(allComponents.size() - 1));
            List<RefModel> interfaces = new ArrayList<RefModel>();
            int size = allComponents.size();
            for (Model m : allComponents.subList(1, size - 1)) {
              if (m instanceof RefModel) {
                RefModel ref = (RefModel) m;
                interfaces.add(ref);
              }
            }
            model.setInterfaces(interfaces);
          } else {
            model.setChild(new ModelImpl());
          }
        }
        return model;
      } else {
        result.invalidType(location, "allOf", "array", allOf);
      }

      return model;
    }
    return null;
  }
Example #12
0
 /**
  * 获取聊天消息
  *
  * @param queryStrNode
  */
 public static ObjectNode getChatMessages(ObjectNode queryStrNode) {
   ObjectNode objectNode = factory.objectNode();
   // check appKey format
   if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
     LOGGER.error("Bad format of Appkey: " + APPKEY);
     objectNode.put("message", "Bad format of Appkey");
     return objectNode;
   }
   try {
     JerseyWebTarget webTarget =
         EndPoints.CHATMESSAGES_TARGET
             .resolveTemplate("org_name", APPKEY.split("#")[0])
             .resolveTemplate("app_name", APPKEY.split("#")[1]);
     if (null != queryStrNode
         && null != queryStrNode.get("ql")
         && !StringUtils.isEmpty(queryStrNode.get("ql").asText())) {
       webTarget = webTarget.queryParam("ql", queryStrNode.get("ql").asText());
     }
     if (null != queryStrNode
         && null != queryStrNode.get("limit")
         && !StringUtils.isEmpty(queryStrNode.get("limit").asText())) {
       webTarget = webTarget.queryParam("limit", queryStrNode.get("limit").asText());
     }
     if (null != queryStrNode
         && null != queryStrNode.get("cursor")
         && !StringUtils.isEmpty(queryStrNode.get("cursor").asText())) {
       webTarget = webTarget.queryParam("cursor", queryStrNode.get("cursor").asText());
     }
     objectNode =
         JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_GET, null);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return objectNode;
 }
 /** Parses execution options from a json object. Unrecognized elements are ignored. */
 public static ExecutionOptions fromJson(ObjectNode node) {
   ExecutionOptions ret = new ExecutionOptions();
   JsonNode x = node.get("timeLimit");
   if (x != null) {
     ret.timeLimit = x.asLong();
   }
   x = node.get("asynchronous");
   if (x != null) {
     ret.asynchronous = x.asLong();
   }
   return ret;
 }
Example #14
0
 public static void main(String[] args) {
   ObjectNode objectNode = new ObjectMapper().createObjectNode();
   objectNode.put("int", 444);
   objectNode.put("str", "");
   objectNode.put("str1", "ff");
   objectNode.putPOJO("object", null);
   objectNode.put("node", new ObjectMapper().createObjectNode());
   jsonNodeIsNull(objectNode.get("int"));
   jsonNodeIsNull(objectNode.get("str"));
   jsonNodeIsNull(objectNode.get("str1"));
   jsonNodeIsNull(objectNode.get("object"));
   jsonNodeIsNull(objectNode.get("node"));
 }
 @Override
 public boolean isDuplicate(T base, String candidate) {
   ObjectNode main;
   try {
     main = mapper.readValue(candidate, ObjectNode.class);
   } catch (Exception e) {
     throw new InternalException("Can't perform JSON deserialization", e);
   }
   if (!main.has("ownerEntityId")) return false;
   long ownerEntityId = main.get("ownerEntityId").asLong();
   String value = main.get("value").asText();
   return base.getOwnerEntityId() == ownerEntityId && base.getValue().equals(value);
 }
  @Override
  public ObjectNode readResource(String id) throws Exception {
    if (file != null) {
      ObjectNode tree = read();

      if (id.equals(ExtensionService.MODULE)) {
        return (ObjectNode) tree.get("config");
      } else {
        return (ObjectNode) tree.get("instances").get(id);
      }
    } else {
      return JsonNodeFactory.instance.objectNode();
    }
  }
  public <T> void fromJson(byte[] json, AttributeExt<T> target) {
    if (json == null) return;
    ObjectNode main;
    try {
      main = mapper.readValue(json, ObjectNode.class);
    } catch (Exception e) {
      throw new InternalException("Can't perform JSON deserialization", e);
    }

    fromJsonBase(main, target);

    if (main.has("creationTs")) target.setCreationTs(new Date(main.get("creationTs").asLong()));
    if (main.has("updateTs")) target.setUpdateTs(new Date(main.get("updateTs").asLong()));
  }
Example #18
0
  static void getAuthCode() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("/home/sead/refresh.txt").delete();

    if (gProps == null) {
      initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

      String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

      HttpPost codeRequest = new HttpPost(codeUri);

      MultipartEntityBuilder meb = MultipartEntityBuilder.create();
      meb.addTextBody("client_id", gProps.client_id);
      meb.addTextBody("scope", "email profile");
      HttpEntity reqEntity = meb.build();

      codeRequest.setEntity(reqEntity);
      CloseableHttpResponse response = httpclient.execute(codeRequest);
      try {

        if (response.getStatusLine().getStatusCode() == 200) {
          HttpEntity resEntity = response.getEntity();
          if (resEntity != null) {
            String responseJSON = EntityUtils.toString(resEntity);
            ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
            device_code = root.get("device_code").asText();
            user_code = root.get("user_code").asText();
            verification_url = root.get("verification_url").asText();
            expires_in = root.get("expires_in").asInt();
          }
        } else {
          log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
      } finally {
        response.close();
        httpclient.close();
      }
    } catch (IOException e) {
      log.error("Error reading sead-google.json or making http requests for code.");
      log.error(e.getMessage());
    }
  }
Example #19
0
  @Test
  public void issue_171() {

    String json = "{\n" + "  \"can delete\": \"this\",\n" + "  \"can't delete\": \"this\"\n" + "}";

    DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(json);
    context.set("$.['can delete']", null);
    context.set("$.['can\\'t delete']", null);

    ObjectNode objectNode = context.read("$");

    assertThat(objectNode.get("can delete").isNull());
    assertThat(objectNode.get("can't delete").isNull());
  }
Example #20
0
  /**
   * Create an empty keep
   *
   * <p>The creator becomes the keep owner
   */
  @RequestMapping(method = RequestMethod.POST)
  public ResponseEntity<Void> create(@RequestBody ObjectNode keepJ, Principal principal) {
    if (keepJ == null || !keepJ.has("name") || !keepJ.has("description")) {
      return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
    }

    String name = keepJ.get("name").textValue();
    String description = keepJ.get("description").textValue();

    Keep keep = new Keep(name, description);
    keepDAO.save(keep);

    return new ResponseEntity<Void>(HttpStatus.CREATED);
  }
  @Override
  public void run() {
    if (SystemConstants.REGISTER_GROUP0 == this.isCreateGroup) {
      ObjectNode dataObjectNode = JsonNodeFactory.instance.objectNode();
      dataObjectNode.put("groupname", groupName);
      dataObjectNode.put("desc", groupDesc);
      dataObjectNode.put("approval", true);
      dataObjectNode.put("public", true);
      dataObjectNode.put("maxusers", 333);
      dataObjectNode.put("owner", username);
      ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
      arrayNode.add(username);
      // arrayNode.add("xiaojianguo003");
      dataObjectNode.put("members", arrayNode);
      ObjectNode creatChatGroupNode = EasemobChatGroups.creatChatGroups(dataObjectNode);
      if ("200".equals(creatChatGroupNode.get("statusCode").toString())) {
        String groupIdResult =
            creatChatGroupNode.get("data").get("groupid").asText().replaceAll("\"", "");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("activityId", activityId);
        param.put("groupId", groupIdResult);
        param.put("groupName", groupName);
        // 将groupId存储到活动主表中
        try {
          commonService.updateObj("hotelActivity.updateHotelActivityGroup", param);
        } catch (BaseException e) {
          e.printStackTrace();
        }
      }

    } else if (SystemConstants.REGISTER_GROUP1 == this.isCreateGroup) {
      String addToChatgroupid = groupId;
      String toAddUsername = username;
      ObjectNode addUserToGroupNode =
          EasemobChatGroups.addUserToGroup(addToChatgroupid, toAddUsername);
      // 将报名人加入群组标记为已加入(is_reg_group设置为1)
      if ("200".equals(addUserToGroupNode.get("statusCode").toString())) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("activityDtlId", activityDtlId);
        param.put("isRegGroup", 1);
        // 将groupId存储到活动主表中
        try {
          commonService.updateObj("hotelActivity.updateRegGroupByActDtlId", param);
        } catch (BaseException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #22
0
 private void runImpl(TestRun run) {
   try {
     String result = strategy.runTest(run);
     if (result == null) {
       run.getCallback().complete();
       return;
     }
     ObjectMapper mapper = new ObjectMapper();
     ObjectNode resultObject = (ObjectNode) mapper.readTree(result);
     String status = resultObject.get("status").asText();
     switch (status) {
       case "ok":
         if (!run.getExpectedExceptions().isEmpty()) {
           run.getCallback().error(new AssertionError("Expected exception was not thrown"));
         } else {
           run.getCallback().complete();
         }
         break;
       case "exception":
         {
           String stack = resultObject.get("stack").asText();
           String exception =
               resultObject.has("exception") ? resultObject.get("exception").asText() : null;
           Class<?> exceptionClass;
           if (exception != null) {
             try {
               exceptionClass = Class.forName(exception, false, TestRunner.class.getClassLoader());
             } catch (ClassNotFoundException e) {
               exceptionClass = null;
             }
           } else {
             exceptionClass = null;
           }
           if (exceptionClass != null) {
             Class<?> caught = exceptionClass;
             if (run.getExpectedExceptions().stream().anyMatch(e -> e.isAssignableFrom(caught))) {
               run.getCallback().complete();
               break;
             }
           }
           run.getCallback().error(new AssertionError(exception + "\n" + stack));
           break;
         }
     }
   } catch (Exception e) {
     run.getCallback().error(e);
   }
 }
Example #23
0
  private void storeConnection(String agentId, String username, String password, String resource)
      throws JSONRPCException, IOException, InvalidKeyException, InvalidAlgorithmParameterException,
          NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException {

    State state = agentHost.getStateFactory().get(agentId);

    String conns = (String) state.get(CONNKEY);
    ArrayNode newConns;
    if (conns != null) {
      newConns = (ArrayNode) JOM.getInstance().readTree(conns);
    } else {
      newConns = JOM.createArrayNode();
    }

    ObjectNode params = JOM.createObjectNode();
    params.put("username", EncryptionUtil.encrypt(username));
    params.put("password", EncryptionUtil.encrypt(password));
    if (resource != null && !resource.isEmpty()) {
      params.put("resource", EncryptionUtil.encrypt(resource));
    }
    for (JsonNode item : newConns) {
      if (item.get("username").equals(params.get("username"))) {
        return;
      }
    }
    newConns.add(params);
    if (!state.putIfUnchanged(CONNKEY, JOM.getInstance().writeValueAsString(newConns), conns)) {
      // recursive retry
      storeConnection(agentId, username, password, resource);
    }
  }
 @Override
 public Criterion decodeCriterion(ObjectNode json) {
   String ip =
       nullIsIllegal(json.get(CriterionCodec.IP), CriterionCodec.IP + MISSING_MEMBER_MESSAGE)
           .asText();
   return Criteria.matchIPv6Dst(IpPrefix.valueOf(ip));
 }
Example #25
0
  /**
   * 发送消息
   *
   * @param targetType 消息投递者类型:users 用户, chatgroups 群组
   * @param target 接收者ID 必须是数组,数组元素为用户ID或者群组ID
   * @param msg 消息内容
   * @param from 发送者
   * @param ext 扩展字段
   * @return 请求响应
   */
  public static ObjectNode sendMessages(
      String targetType, ArrayNode target, ObjectNode msg, String from, ObjectNode ext) {

    ObjectNode objectNode = factory.objectNode();

    ObjectNode dataNode = factory.objectNode();

    // check appKey format
    if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
      LOGGER.error("Bad format of Appkey: " + APPKEY);

      objectNode.put("message", "Bad format of Appkey");

      return objectNode;
    }

    // check properties that must be provided
    if (!("users".equals(targetType) || "chatgroups".equals(targetType))) {
      LOGGER.error("TargetType must be users or chatgroups .");

      objectNode.put("message", "TargetType must be users or chatgroups .");

      return objectNode;
    }

    try {
      // 构造消息体
      dataNode.put("target_type", targetType);
      dataNode.put("target", target.toString());
      dataNode.put("msg", msg);
      dataNode.put("from", from);
      dataNode.put("ext", ext);

      JerseyWebTarget webTarget =
          EndPoints.MESSAGES_TARGET
              .resolveTemplate("org_name", APPKEY.split("#")[0])
              .resolveTemplate("app_name", APPKEY.split("#")[1]);

      objectNode =
          JerseyUtils.sendRequest(webTarget, dataNode, credential, HTTPMethod.METHOD_POST, null);

      objectNode = (ObjectNode) objectNode.get("data");
      for (int i = 0; i < target.size(); i++) {
        String resultStr = objectNode.path(target.path(i).asText()).asText();
        if ("success".equals(resultStr)) {
          LOGGER.error(
              String.format(
                  "Message has been send to user[%s] successfully .", target.path(i).asText()));
        } else if (!"success".equals(resultStr)) {
          LOGGER.error(
              String.format("Message has been send to user[%s] failed .", target.path(i).asText()));
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return objectNode;
  }
 @Override
 public Criterion decodeCriterion(ObjectNode json) {
   JsonNode ochSignalId =
       nullIsIllegal(
           json.get(CriterionCodec.OCH_SIGNAL_ID),
           CriterionCodec.GRID_TYPE + MISSING_MEMBER_MESSAGE);
   GridType gridType =
       GridType.valueOf(
           nullIsIllegal(
                   ochSignalId.get(CriterionCodec.GRID_TYPE),
                   CriterionCodec.GRID_TYPE + MISSING_MEMBER_MESSAGE)
               .asText());
   ChannelSpacing channelSpacing =
       ChannelSpacing.valueOf(
           nullIsIllegal(
                   ochSignalId.get(CriterionCodec.CHANNEL_SPACING),
                   CriterionCodec.CHANNEL_SPACING + MISSING_MEMBER_MESSAGE)
               .asText());
   int spacingMultiplier =
       nullIsIllegal(
               ochSignalId.get(CriterionCodec.SPACING_MULIPLIER),
               CriterionCodec.SPACING_MULIPLIER + MISSING_MEMBER_MESSAGE)
           .asInt();
   int slotGranularity =
       nullIsIllegal(
               ochSignalId.get(CriterionCodec.SLOT_GRANULARITY),
               CriterionCodec.SLOT_GRANULARITY + MISSING_MEMBER_MESSAGE)
           .asInt();
   return Criteria.matchLambda(
       Lambda.ochSignal(gridType, channelSpacing, spacingMultiplier, slotGranularity));
 }
    @Override
    public Criterion decodeCriterion(ObjectNode json) {
      JsonNode oduSignalId =
          nullIsIllegal(
              json.get(CriterionCodec.ODU_SIGNAL_ID),
              CriterionCodec.TRIBUTARY_PORT_NUMBER + MISSING_MEMBER_MESSAGE);

      int tributaryPortNumber =
          nullIsIllegal(
                  oduSignalId.get(CriterionCodec.TRIBUTARY_PORT_NUMBER),
                  CriterionCodec.TRIBUTARY_PORT_NUMBER + MISSING_MEMBER_MESSAGE)
              .asInt();
      int tributarySlotLen =
          nullIsIllegal(
                  oduSignalId.get(CriterionCodec.TRIBUTARY_SLOT_LEN),
                  CriterionCodec.TRIBUTARY_SLOT_LEN + MISSING_MEMBER_MESSAGE)
              .asInt();
      byte[] tributarySlotBitmap =
          HexString.fromHexString(
              nullIsIllegal(
                      oduSignalId.get(CriterionCodec.TRIBUTARY_SLOT_BITMAP),
                      CriterionCodec.TRIBUTARY_SLOT_BITMAP + MISSING_MEMBER_MESSAGE)
                  .asText());

      return Criteria.matchOduSignalId(
          OduSignalId.oduSignalId(tributaryPortNumber, tributarySlotLen, tributarySlotBitmap));
    }
Example #28
0
 private static CacheSize getCacheSizeDeprecated(final ObjectNode response) {
   if (!response.has(CACHE_SIZE_DEPRECATED)) {
     return CacheSize.NOT_CHOSEN;
   }
   double size = 0;
   try {
     size = response.get(CACHE_SIZE_DEPRECATED).asDouble();
   } catch (final NullPointerException e) {
     Log.e("OkapiClient.getCacheSize", e);
   }
   switch ((int) Math.round(size)) {
     case 1:
       return CacheSize.MICRO;
     case 2:
       return CacheSize.SMALL;
     case 3:
       return CacheSize.REGULAR;
     case 4:
       return CacheSize.LARGE;
     case 5:
       return CacheSize.VERY_LARGE;
     default:
       break;
   }
   return CacheSize.NOT_CHOSEN;
 }
Example #29
0
 /** Parses the entity, client identification and execution options from the given json object */
 protected void parse(ObjectNode node) {
   entityVersion = new EntityVersion();
   JsonNode x = node.get("entity");
   if (x != null && !(x instanceof NullNode)) {
     entityVersion.setEntity(x.asText());
   }
   x = node.get("entityVersion");
   if (x != null && !(x instanceof NullNode)) {
     entityVersion.setVersion(x.asText());
   }
   // TODO: clientIdentification
   x = node.get("execution");
   if (x != null) {
     execution = ExecutionOptions.fromJson((ObjectNode) x);
   }
 }
  /**
   * Update details of a specified path id.
   *
   * @param id path id
   * @param stream pce path from json
   * @return 200 OK, 404 if given identifier does not exist
   */
  @PUT
  @Path("{path_id}")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updatePath(@PathParam("path_id") String id, final InputStream stream) {
    log.debug("Update path by identifier {}.", id);
    try {
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      JsonNode pathNode = jsonTree.get("path");
      PcePath path = codec(PcePath.class).decode((ObjectNode) pathNode, this);
      // Assign cost
      List<Constraint> constrntList = new LinkedList<Constraint>();
      // TODO: need to uncomment below lines once CostConstraint class is ready
      if (path.costConstraint() != null) {
        // CostConstraint.Type costType = CostConstraint.Type.values()[path.constraint().cost()];
        // constrntList.add(CostConstraint.of(costType));
      }

      // Assign bandwidth. Data rate unit is in BPS.
      if (path.bandwidthConstraint() != null) {
        // TODO: need to uncomment below lines once BandwidthConstraint class is ready
        // constrntList.add(LocalBandwidthConstraint
        //        .of(path.constraint().bandwidth(), DataRateUnit.valueOf("BPS")));
      }

      Boolean result =
          nullIsNotFound(
              get(PceService.class).updatePath(TunnelId.valueOf(id), constrntList),
              PCE_PATH_NOT_FOUND);
      return Response.status(OK).entity(result.toString()).build();
    } catch (IOException e) {
      log.error("Update path failed because of exception {}.", e.toString());
      throw new IllegalArgumentException(e);
    }
  }