コード例 #1
0
  /** data set attributes can load values just like report attributes */
  @Test
  public void loadAttributeValues() {
    ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange);
    node.put(
        "attributes",
        new ObjectMapper()
            .createArrayNode()
            .add(builder.buildAttributeNode(id, name, code, "string")));
    server.register(dataSetsUri + "/" + dataSetId, node.toString());
    DataSet dataSet = service.loadDataSet(dataSetId);
    Attribute attribute = dataSet.getAttributes().get(0);

    String label = "label";
    String value = "value";
    final ObjectNode valueNode = new ObjectMapper().createObjectNode();
    valueNode.put(
        "values",
        new ObjectMapper().createArrayNode().add(builder.buildAttributeValueNode(label, value)));

    server.register(
        dataSetsUri + "/" + dataSetId + "/attributes/" + code + "/values", valueNode.toString());

    List<AttributeValue> values = attribute.getValues().load().get();
    assertEquals(values.size(), 1);

    assertEquals(values.get(0).getLabel(), label);
    assertEquals(values.get(0).getValue(), value);

    assertEquals(attribute.toString(), name);
    assertEquals(values.get(0).toString(), label);
  }
コード例 #2
0
ファイル: AlarmsWebResource.java プロジェクト: Mohdrz/Onos
  /**
   * Update book-keeping fields on the alarm. Returns an up-to-date version of the alarm. Some of
   * its fields may have been updated since the REST client last retrieved the alarm being updated.
   *
   * @param alarmIdPath
   * @param stream input JSON
   * @return updated JSON encoded alarm
   */
  @PUT
  @Path("{alarm_id}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response update(
      @PathParam("alarm_id") final String alarmIdPath, final InputStream stream) {
    log.info("PUT NEW ALARM at /{}", alarmIdPath);

    try {
      final ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      log.info("jsonTree={}", jsonTree);

      final Alarm alarm = codec(Alarm.class).decode(jsonTree, this);

      final AlarmService service = get(AlarmService.class);

      if (Long.parseLong(alarmIdPath) != alarm.id().fingerprint()) {
        throw new IllegalArgumentException(
            "id in path is "
                + Long.parseLong(alarmIdPath)
                + " but payload uses id="
                + alarm.id().fingerprint());
      }
      final Alarm updated = service.update(alarm);
      final ObjectNode encoded = new AlarmCodec().encode(updated, this);
      return ok(encoded.toString()).build();

    } catch (IOException ioe) {
      throw new IllegalArgumentException(ioe);
    }
  }
コード例 #3
0
ファイル: addReviewTest.java プロジェクト: xpg94/praksa
  @Test
  public void addValidReview() {
    running(
        fakeApplication(),
        () -> {
          ObjectNode node = JsonNodeFactory.instance.objectNode();
          node.put("text", "text of review");
          node.put("rating", 4);
          JsonNode json = null;
          try {
            json = (JsonNode) new ObjectMapper().readTree(node.toString());
          } catch (IOException e) {
            e.printStackTrace();
          }

          Http.RequestBuilder rb =
              new Http.RequestBuilder()
                  .method(POST)
                  .uri("/v1/restaurants/1601994/reviews")
                  .bodyJson(json);
          Result result = route(rb);

          assertEquals(Http.Status.OK, result.status());
          assertTrue(PersistenceManager.getRestaurantById(1601994).getReviews().size() != 0);
          assertTrue(
              PersistenceManager.getRestaurantById(1601994)
                  .getReviews()
                  .get(0)
                  .getText()
                  .equals("text of review"));
        });
  }
コード例 #4
0
 public String parseData(JsonNode node, String f)
     throws JsonProcessingException, IOException, JSONException {
   System.out.println("---");
   ObjectNode json = factory.objectNode();
   type.push(f);
   Iterator<String> fieldNames = node.fieldNames();
   String uri = type.toString().replaceAll(", ", ".").replaceAll("[\\[\\]]", "");
   json.put("type_uri", uri);
   ObjectNode object = factory.objectNode();
   while (fieldNames.hasNext()) {
     String fieldName = fieldNames.next();
     JsonNode fieldValue = node.get(fieldName);
     // if (node.findParent("description").get("description") != null)
     // json.set("value", node.findParent("description").get("description"));
     if (fieldValue.isObject()) {
       ObjectNode assoc = factory.objectNode();
       assoc.set(uri + "." + parseData(fieldValue, fieldName).replaceAll("\n", ""), fieldValue);
       json.set("composite", assoc);
     } else {
       json.set(fieldName, fieldValue);
     }
   }
   // json.append("}");
   System.out.println("xxx");
   System.out.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(json));
   TopicModel t = new TopicModel(new JSONObject(json.toString()));
   System.err.println(t.getUri());
   System.err.println(t.getChildTopicsModel());
   return type.pop();
 }
コード例 #5
0
  /** Checks if the rest operation returns an error as expected */
  protected void assertErrorResult(String url, ObjectNode body, int statusCode) throws IOException {

    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    executeHttpRequest(post, statusCode);
  }
コード例 #6
0
  protected void assertResultsPresentInPostDataResponseWithStatusCheck(
      String url, ObjectNode body, int expectedStatusCode, String... expectedResourceIds)
      throws JsonProcessingException, IOException {
    int numberOfResultsExpected = 0;
    if (expectedResourceIds != null) {
      numberOfResultsExpected = expectedResourceIds.length;
    }

    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    HttpResponse response = executeHttpRequest(post, expectedStatusCode);

    if (expectedStatusCode == HttpStatus.SC_OK) {
      // Check status and size
      JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
      JsonNode dataNode = rootNode.get("data");
      assertEquals(numberOfResultsExpected, dataNode.size());

      // Check presence of ID's
      if (expectedResourceIds != null) {
        List<String> toBeFound = new ArrayList<String>(Arrays.asList(expectedResourceIds));
        Iterator<JsonNode> it = dataNode.iterator();
        while (it.hasNext()) {
          String id = it.next().get("id").textValue();
          toBeFound.remove(id);
        }
        assertTrue(
            "Not all entries have been found in result, missing: "
                + StringUtils.join(toBeFound, ", "),
            toBeFound.isEmpty());
      }
    }
  }
コード例 #7
0
ファイル: addReviewTest.java プロジェクト: xpg94/praksa
  @Test
  public void addToInvalidRestaurant() {
    running(
        fakeApplication(),
        () -> {
          ObjectNode node = JsonNodeFactory.instance.objectNode();
          node.put("text", "text of review");
          node.put("rating", 4);
          JsonNode json = null;
          try {
            json = (JsonNode) new ObjectMapper().readTree(node.toString());
          } catch (IOException e) {
            e.printStackTrace();
          }

          Http.RequestBuilder rb =
              new Http.RequestBuilder()
                  .method(POST)
                  .uri("/v1/restaurants/3213123/reviews")
                  .bodyJson(json);
          Result result = route(rb);

          assertEquals(Http.Status.NOT_FOUND, result.status());
        });
  }
コード例 #8
0
  private static void testJson() {
    String json1 = "[\"hello\"]";
    JsonNode jsonNode = Json.parse(json1);
    Json.stringify(jsonNode);
    System.out.println(jsonNode.toString());
    System.out.println(Json.stringify(jsonNode));
    ObjectNode jsonObject = Json.newObject();
    jsonObject.put("hello", jsonNode);
    jsonObject.put("hello", 56);
    System.out.println(jsonObject.toString());
    List<Object> strings = new ArrayList<Object>();
    strings.add("hello");
    strings.add("world");
    jsonObject.put("test", Json.toJson(strings));
    System.out.println(jsonObject.toString());
    jsonObject.put("test2", Json.toJson("string"));
    jsonObject.put("test2", Json.toJson("sshshhs"));
    List<String> list = new ArrayList<String>();
    list.add("hello me");
    // ObjectNode objectNode = Json.newObject();

    jsonObject.put("me", Json.toJson(list));
    System.out.println(jsonObject.toString());
    System.out.println(jsonObject.size());
    System.out.println(jsonObject.get("test").isArray());
    JsonNode jsonNode1 = jsonObject.get("test");
    Iterator iterator = jsonNode1.iterator();
    while ((iterator.hasNext())) {
      System.out.println(iterator.next());
    }
    Iterator<JsonNode> iterator1 = jsonObject.iterator();
    while (iterator1.hasNext()) {
      System.out.println("----------------------");
      JsonNode jsonNode2 = iterator1.next();
      if (jsonNode2.isArray()) {
        Iterator iterator2 = jsonNode2.iterator();
        while ((iterator2.hasNext())) {
          System.out.println(iterator2.next());
        }
      } else {
        if (jsonNode2.isTextual()) {
          System.out.println("String:" + jsonNode2);
        }
      }
    }
  }
コード例 #9
0
 @Override
 public String toBulkJson(final ObjectNode node) {
   ObjectNode index = node.putObject("delete");
   index.put("_index", this.index);
   index.put("_type", type);
   index.put("_id", id);
   return node.toString();
 }
コード例 #10
0
  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();
  }
コード例 #11
0
  /** Empty attributes array means no attributes. */
  public void attributesEmpty() {
    ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange);
    node.put("attributes", new ObjectMapper().createArrayNode());
    server.register(dataSetsUri + "/" + dataSetId, node.toString());
    DataSet dataSet = service.loadDataSet(dataSetId);

    assertEquals(dataSet.getAttributes(), Collections.emptyList());
  }
コード例 #12
0
ファイル: JsonUtil.java プロジェクト: dminor112/baselib
 /** 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();
 }
コード例 #13
0
  /** Invalid indicators are ignored. */
  @Test(dataProvider = "invalidIndicators")
  public void indicatorInvalid(JsonNode indicator) {
    ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange);
    node.put("indicators", new ObjectMapper().createArrayNode().add(indicator));
    server.register(dataSetsUri + "/" + dataSetId, node.toString());
    DataSet dataSet = service.loadDataSet(dataSetId);

    assertEquals(dataSet.getIndicators(), Collections.emptyList());
  }
コード例 #14
0
ファイル: PortPairWebResource.java プロジェクト: Mohdrz/Onos
 /**
  * Get details of a specified port pair id.
  *
  * @param id port pair id
  * @return 200 OK, 404 if given identifier does not exist
  */
 @GET
 @Path("{pair_id}")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getPortPair(@PathParam("pair_id") String id) {
   PortPair portPair =
       nullIsNotFound(
           get(PortPairService.class).getPortPair(PortPairId.of(id)), PORT_PAIR_NOT_FOUND);
   ObjectNode result = mapper().createObjectNode();
   result.set("port_pair", codec(PortPair.class).encode(portPair, this));
   return ok(result.toString()).build();
 }
コード例 #15
0
  /** Test method for {@link com.mychaelstyle.nlp.Juman#parse(java.lang.String)}. */
  @Test
  public void testParse() {
    Juman juman = new Juman();
    try {
      ObjectNode result =
          juman.parse("本システムは,計算機による日本語の解析の研究を目指す多くの研究者に共通に使える形態素解析ツールを提供するために開発されました。");
      assertThat(result, notNullValue());
      System.out.println(result.toString());

      result = juman.parse("JUMANは、日本語の形態素解析システムです。");
      System.out.println(result.toString());

      result = juman.parse("人手で整備した辞書に基づいており、ChaSenの元となったシステム。");
      System.out.println(result.toString());

    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
コード例 #16
0
 /**
  * Retrieve details of a specified path id.
  *
  * @param id path id
  * @return 200 OK, 404 if given identifier does not exist
  */
 @GET
 @Path("{path_id}")
 @Produces(MediaType.APPLICATION_JSON)
 public Response queryPath(@PathParam("path_id") String id) {
   log.debug("Query path by identifier {}.", id);
   Tunnel tunnel =
       nullIsNotFound(get(PceService.class).queryPath(TunnelId.valueOf(id)), PCE_PATH_NOT_FOUND);
   PcePath path = DefaultPcePath.builder().of(tunnel).build();
   ObjectNode result = mapper().createObjectNode();
   result.set("path", codec(PcePath.class).encode(path, this));
   return ok(result.toString()).build();
 }
コード例 #17
0
ファイル: EditorAction.java プロジェクト: Wizzercn/wzflow
  @At("/?/save")
  @PUT
  @Ok("http:200")
  public void saveModel(String modelId, HttpServletRequest req) {
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      String body = urlUtil.readStreamParameter(req.getInputStream());
      String[] str = StringUtils.split(body, "&");
      for (int i = 0; i < str.length; i++) {
        String[] temp = StringUtils.split(str[i], "=");
        if (temp.length > 1) {
          map.put(temp[0], URLDecoder.decode(temp[1], "utf-8"));
        } else {
          map.put(temp[0], "");
        }
      }
      Model model = repositoryService.getModel(modelId);
      ObjectMapper objectMapper = new ObjectMapper();

      ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

      modelJson.put(ModelDataJsonConstants.MODEL_NAME, Strings.sNull(map.get("name")));
      modelJson.put(
          ModelDataJsonConstants.MODEL_DESCRIPTION, Strings.sNull(map.get("description")));
      model.setMetaInfo(modelJson.toString());
      model.setName(Strings.sNull(map.get("name")));

      repositoryService.saveModel(model);

      repositoryService.addModelEditorSource(
          model.getId(), Strings.sNull(map.get("json_xml")).getBytes("utf-8"));

      InputStream svgStream =
          new ByteArrayInputStream(Strings.sNull(map.get("svg_xml")).getBytes("utf-8"));
      TranscoderInput input = new TranscoderInput(svgStream);

      PNGTranscoder transcoder = new PNGTranscoder();
      // Setup output
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      TranscoderOutput output = new TranscoderOutput(outStream);

      // Do the transformation
      transcoder.transcode(input, output);
      final byte[] result = outStream.toByteArray();
      repositoryService.addModelEditorSourceExtra(model.getId(), result);
      outStream.close();

    } catch (Exception e) {
      log.error("Error saving model", e);
      throw new ActivitiException("Error saving model", e);
    }
  }
コード例 #18
0
ファイル: AlarmsWebResource.java プロジェクト: Mohdrz/Onos
  /**
   * Get specified alarm. Returns details of the specified alarm.
   *
   * @param id ONOS allocated identifier
   * @return JSON encoded alarm
   */
  @GET
  @Path("{id}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAlarm(@PathParam("id") final String id) {
    log.info("HTTP GET alarm for id={}", id);

    final AlarmId alarmId = toAlarmId(id);
    final Alarm alarm = get(AlarmService.class).getAlarm(alarmId);

    final ObjectNode result = mapper().createObjectNode();
    result.set("alarm", codec(Alarm.class).encode(alarm, this));
    return ok(result.toString()).build();
  }
コード例 #19
0
ファイル: PortPairWebResource.java プロジェクト: Mohdrz/Onos
 /**
  * Get details of all port pairs created.
  *
  * @return 200 OK
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getPortPairs() {
   Iterable<PortPair> portPairs = get(PortPairService.class).getPortPairs();
   ObjectNode result = mapper().createObjectNode();
   ArrayNode portPairEntry = result.putArray("port_pairs");
   if (portPairs != null) {
     for (final PortPair portPair : portPairs) {
       portPairEntry.add(codec(PortPair.class).encode(portPair, this));
     }
   }
   return ok(result.toString()).build();
 }
コード例 #20
0
ファイル: OnosSwaggerMojo.java プロジェクト: rvhub/onos
 // Writes the swagger.json file using the supplied JSON root.
 private void genCatalog(ObjectNode root) {
   File swaggerCfg = new File(dstDirectory, JSON_FILE);
   if (dstDirectory.exists() || dstDirectory.mkdirs()) {
     try (FileWriter fw = new FileWriter(swaggerCfg);
         PrintWriter pw = new PrintWriter(fw)) {
       pw.println(root.toString());
     } catch (IOException e) {
       getLog().warn("Unable to write " + JSON_FILE);
     }
   } else {
     getLog().warn("Unable to create " + dstDirectory);
   }
 }
コード例 #21
0
ファイル: AlarmsWebResource.java プロジェクト: Mohdrz/Onos
  /**
   * Get all alarms. Returns a list of all alarms across all devices.
   *
   * @param includeCleared include recently cleared alarms in response
   * @return JSON encoded set of alarms
   */
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAlarms(
      @DefaultValue("false") @QueryParam("includeCleared") final boolean includeCleared) {

    log.info("Requesting all alarms, includeCleared={}", includeCleared);
    final AlarmService service = get(AlarmService.class);

    final Iterable<Alarm> alarms = includeCleared ? service.getAlarms() : service.getActiveAlarms();

    final ObjectNode result = new ObjectMapper().createObjectNode();
    result.set("alarms", codec(Alarm.class).encode(alarms, this));
    return ok(result.toString()).build();
  }
コード例 #22
0
 protected DBObject prepareObject(StreamsDatum streamsDatum) {
   DBObject dbObject = null;
   if (streamsDatum.getDocument() instanceof String) {
     dbObject = (DBObject) JSON.parse((String) streamsDatum.getDocument());
   } else {
     try {
       ObjectNode node = mapper.valueToTree(streamsDatum.getDocument());
       dbObject = (DBObject) JSON.parse(node.toString());
     } catch (Exception e) {
       e.printStackTrace();
       LOGGER.error("Unsupported type: " + streamsDatum.getDocument().getClass(), e);
     }
   }
   return dbObject;
 }
コード例 #23
0
 /**
  * Retrieve details of all paths created.
  *
  * @return 200 OK
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response queryAllPath() {
   log.debug("Query all paths.");
   Iterable<Tunnel> tunnels = get(PceService.class).queryAllPath();
   ObjectNode result = mapper().createObjectNode();
   ArrayNode pathEntry = result.putArray("paths");
   if (tunnels != null) {
     for (final Tunnel tunnel : tunnels) {
       PcePath path = DefaultPcePath.builder().of(tunnel).build();
       pathEntry.add(codec(PcePath.class).encode(path, this));
     }
   }
   return ok(result.toString()).build();
 }
コード例 #24
0
  @Override
  public Token getToken() {
    if (null == token || token.isExpired()) {
      try {
        ObjectNode objectNode = factory.objectNode();
        objectNode.put("grant_type", "client_credentials");
        objectNode.put("client_id", tokenKey1);
        objectNode.put("client_secret", tokenKey2);
        List<NameValuePair> headers = new ArrayList<>();
        headers.add(new BasicNameValuePair("Content-Type", "application/json"));

        HttpPost httpPost = new HttpPost();
        httpPost.setURI(tokenURL.toURI());

        for (NameValuePair nameValuePair : headers) {
          httpPost.addHeader(nameValuePair.getName(), nameValuePair.getValue());
        }
        httpPost.setEntity(new StringEntity(objectNode.toString(), "UTF-8"));

        HttpResponse tokenResponse = client.execute(httpPost);
        HttpEntity entity = tokenResponse.getEntity();

        String results = EntityUtils.toString(entity, "UTF-8");

        if (tokenResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

          ObjectMapper mapper = new ObjectMapper();

          JsonFactory factory = mapper.getJsonFactory();
          JsonParser jp = factory.createJsonParser(results);
          JsonNode json = mapper.readTree(jp);

          String accessToken = json.get("access_token").asText();
          Long expiredAt = System.currentTimeMillis() + json.get("expires_in").asLong() * 1000;

          db.updateToken(accessToken, expiredAt);

          token = new Token(accessToken, expiredAt);
        }
      } catch (Exception e) {
        throw new RuntimeException(
            "Some errors occurred while fetching a token by username and password .");
      }
    }

    return token;
  }
コード例 #25
0
  /** Valid attribute types are parsed correctly. */
  @Test(dataProvider = "attributeTypes")
  public void attributeTypes(String jsonType, AttributeType type) {
    ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange);
    node.put(
        "attributes",
        new ObjectMapper()
            .createArrayNode()
            .add(builder.buildAttributeNode(id, name, code, jsonType)));
    server.register(dataSetsUri + "/" + dataSetId, node.toString());
    DataSet dataSet = service.loadDataSet(dataSetId);

    assertEquals(dataSet.getAttributes().size(), 1);

    Attribute attribute = dataSet.getAttributes().get(0);
    assertEquals(attribute.getId(), id);
    assertEquals(attribute.getName(), name);
    assertEquals(attribute.getCode(), code);
    assertEquals(attribute.getType(), type);
  }
コード例 #26
0
  /** Indicator groups are parsed correctly. */
  public void groupIndicator() {
    ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange);
    node.put(
        "indicators",
        new ObjectMapper()
            .createArrayNode()
            .add(builder.buildIndicatorNode(id, name, code, formula, "indicator_group")));
    server.register(dataSetsUri + "/" + dataSetId, node.toString());
    DataSet dataSet = service.loadDataSet(dataSetId);

    assertEquals(dataSet.getIndicators().size(), 1);

    Indicator indicator = dataSet.getIndicators().get(0);
    assertEquals(indicator.getId(), id);
    assertEquals(indicator.getName(), name);
    assertEquals(indicator.getCode(), null);
    assertEquals(indicator.getFormula(), null);
    assertEquals(indicator.getType(), IndicatorType.GROUP);
  }
コード例 #27
0
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createPorts(InputStream input) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      ObjectNode portNode = (ObjectNode) mapper.readTree(input);

      OpenstackPort openstackPort = PORT_CODEC.decode(portNode, this);
      OpenstackSwitchingService switchingService = getService(OpenstackSwitchingService.class);
      switchingService.createPorts(openstackPort);

      log.debug("REST API ports is called with {}", portNode.toString());
      return Response.status(Response.Status.OK).build();

    } catch (Exception e) {
      log.error("Creates Port failed because of exception {}", e.toString());
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.toString()).build();
    }
  }
コード例 #28
0
ファイル: KafkaSinkTestIT.java プロジェクト: bwboy/Ingestion
  //    @Ignore
  @Test
  public void test() throws EventDeliveryException, UnsupportedEncodingException {
    Transaction tx = channel.getTransaction();
    tx.begin();

    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("myString", "foo");
    jsonBody.put("myInt32", 32);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar");
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
    channel.put(event);

    tx.commit();
    tx.close();

    kafkaSink.process();

    kafka.api.FetchRequest req =
        new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100).build();
    FetchResponse fetchResponse = simpleConsumer.fetch(req);
    ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0);

    //        Assert.assertTrue(messageSet.sizeInBytes() > 0);
    for (MessageAndOffset messageAndOffset : messageSet) {
      ByteBuffer payload = messageAndOffset.message().payload();
      byte[] bytes = new byte[payload.limit()];
      payload.get(bytes);
      String message = new String(bytes, "UTF-8");
      Assert.assertNotNull(message);
      Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}");
    }
  }
コード例 #29
0
ファイル: JsonRpcServer.java プロジェクト: sdhjob/jsonrpc4j
  /**
   * Handles the given {@link ObjectNode} and writes the responses to the given {@link
   * OutputStream}.
   *
   * @param node the {@link JsonNode}
   * @param ops the {@link OutputStream}
   * @throws IOException on error
   */
  protected void handleObject(ObjectNode node, OutputStreamWrapper opsw) throws IOException {
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Request: " + node.toString());
    }

    // validate request
    if (!backwardsComaptible && !node.has("jsonrpc") || !node.has("method")) {
      writeAndFlushResponse(
          opsw, createErrorResponse("jsonrpc", "null", StandardJsonError.INVALID_REQUEST, null));
      return;
    }

    // get nodes
    JsonNode jsonPrcNode = node.get("jsonrpc");
    JsonNode methodNode = node.get("method");
    JsonNode idNode = node.get("id");
    JsonNode paramsNode = node.get("params");

    // get node values
    String jsonRpc = (jsonPrcNode != null && !jsonPrcNode.isNull()) ? jsonPrcNode.asText() : "2.0";
    String methodName = (methodNode != null && !methodNode.isNull()) ? methodNode.asText() : null;
    Object id = parseId(idNode);

    // find methods
    Set<Method> methods = new HashSet<Method>();
    methods.addAll(ReflectionUtil.findMethods(getHandlerClass(), methodName));
    if (methods.isEmpty()) {
      writeAndFlushResponse(
          opsw, createErrorResponse(jsonRpc, id, StandardJsonError.METHOD_NOT_FOUND, null));
      return;
    }

    // choose a method
    MethodAndArgs methodArgs = findBestMethodByParamsNode(methods, paramsNode);
    if (methodArgs == null) {
      writeAndFlushResponse(
          opsw, createErrorResponse(jsonRpc, id, StandardJsonError.INVALID_PARAMS, null));
      return;
    }

    // invoke the method
    JsonNode result = null;
    Throwable thrown = null;
    try {
      result = invoke(methodArgs.method, methodArgs.arguments);
    } catch (Throwable e) {
      thrown = e;
    }

    // respond if it's not a notification request
    if (id != null) {

      // attempt to resolve the error
      JsonError error = null;
      if (thrown != null) {

        // get cause of exception
        Throwable e = thrown;
        if (InvocationTargetException.class.isInstance(e)) {
          e = InvocationTargetException.class.cast(e).getTargetException();
        }

        // resolve error
        if (errorResolver != null) {
          error = errorResolver.resolveError(e, methodArgs.method, methodArgs.arguments);
        } else {
          error = DEFAULT_ERRROR_RESOLVER.resolveError(e, methodArgs.method, methodArgs.arguments);
        }

        // make sure we have a JsonError
        if (error == null) {
          error =
              new com.googlecode.jsonrpc4j.ErrorResolver.BasicJsonError(
                  0, e.getMessage(), e.getClass().getName());
        }
      }

      // the resoponse object
      JsonRpcServerResponse response = null;

      // build error
      if (error != null) {
        response =
            createErrorResponse(
                jsonRpc, id, error.getCode(), 500, error.getMessage(), error.getData());

        // build success
      } else {
        response = createSuccessResponse(jsonRpc, id, result);
      }

      // write it
      writeAndFlushResponse(opsw, response);
    }

    // log and potentially re-throw errors
    if (thrown != null) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(Level.SEVERE, "Error in JSON-RPC Service", thrown);
      }
      if (rethrowExceptions) {
        throw new RuntimeException(thrown);
      }
    }
  }
コード例 #30
0
  public static void main(String[] args) {
    //  检测用户是否在线
    String targetuserPrimaryKey = "kenshinnuser000";
    ObjectNode usernode = getUserStatus(targetuserPrimaryKey);
    if (null != usernode) {
      LOGGER.info("检测用户是否在线: " + usernode.toString());
    }

    // 给用户发一条文本消息
    String from = "kenshinnuser000";
    String targetTypeus = "users";
    ObjectNode ext = factory.objectNode();
    ArrayNode targetusers = factory.arrayNode();
    targetusers.add("kenshinnuser001");
    targetusers.add("kenshinnuser002");
    ObjectNode txtmsg = factory.objectNode();
    txtmsg.put("msg", "Hello Easemob!");
    txtmsg.put("type", "txt");
    ObjectNode sendTxtMessageusernode = sendMessages(targetTypeus, targetusers, txtmsg, from, ext);
    if (null != sendTxtMessageusernode) {
      LOGGER.info("给用户发一条文本消息: " + sendTxtMessageusernode.toString());
    }

    // 给一个群组发文本消息
    String targetTypegr = "chatgroups";
    ArrayNode chatgroupidsNode = (ArrayNode) EasemobChatGroups.getAllChatgroupids().path("data");
    ArrayNode targetgroup = factory.arrayNode();
    targetgroup.add(chatgroupidsNode.get(0).path("groupid").asText());
    ObjectNode sendTxtMessagegroupnode = sendMessages(targetTypegr, targetgroup, txtmsg, from, ext);
    if (null != sendTxtMessagegroupnode) {
      LOGGER.info("给一个群组发文本消息: " + sendTxtMessagegroupnode.toString());
    }

    // 给用户发一条图片消息
    File uploadImgFile = new File("/home/lynch/Pictures/24849.jpg");
    ObjectNode imgDataNode = EasemobFiles.mediaUpload(uploadImgFile);
    String imgFileUUID = imgDataNode.path("entities").get(0).path("uuid").asText();
    String shareSecret = imgDataNode.path("entities").get(0).path("share-secret").asText();
    if (null != imgDataNode) {
      LOGGER.info("上传图片文件: " + imgDataNode.toString());
    }
    ObjectNode imgmsg = factory.objectNode();
    imgmsg.put("type", "img");
    imgmsg.put(
        "url",
        EndPoints.CHATFILES_TARGET
                .resolveTemplate("org_name", APPKEY.split("#")[0])
                .resolveTemplate("app_name", APPKEY.split("#")[1])
                .getUri()
                .toString()
            + imgFileUUID);
    imgmsg.put("filename", "24849.jpg");
    imgmsg.put("length", 10);
    imgmsg.put("secret", shareSecret);
    ObjectNode sendimgMessageusernode = sendMessages(targetTypeus, targetusers, imgmsg, from, ext);
    if (null != sendimgMessageusernode) {
      LOGGER.info("给一个群组发文本消息: " + sendimgMessageusernode.toString());
    }

    // 给一个群组发图片消息
    ObjectNode sendimgMessagegroupnode = sendMessages(targetTypegr, targetgroup, imgmsg, from, ext);
    if (null != sendimgMessagegroupnode) {
      LOGGER.info("给一个群组发文本消息: " + sendimgMessagegroupnode.toString());
    }

    // 给用户发一条语音消息
    File uploadAudioFile = new File("/home/lynch/Music/music.MP3");
    ObjectNode audioDataNode = EasemobFiles.mediaUpload(uploadAudioFile);
    String audioFileUUID = audioDataNode.path("entities").get(0).path("uuid").asText();
    String audioFileShareSecret =
        audioDataNode.path("entities").get(0).path("share-secret").asText();
    if (null != audioDataNode) {
      LOGGER.info("上传语音文件: " + audioDataNode.toString());
    }
    ObjectNode audiomsg = factory.objectNode();
    audiomsg.put("type", "audio");
    audiomsg.put(
        "url",
        EndPoints.CHATFILES_TARGET
                .resolveTemplate("org_name", APPKEY.split("#")[0])
                .resolveTemplate("app_name", APPKEY.split("#")[1])
                .getUri()
                .toString()
            + audioFileUUID);
    audiomsg.put("filename", "music.MP3");
    audiomsg.put("length", 10);
    audiomsg.put("secret", audioFileShareSecret);
    ObjectNode sendaudioMessageusernode =
        sendMessages(targetTypeus, targetusers, audiomsg, from, ext);
    if (null != sendaudioMessageusernode) {
      LOGGER.info("给用户发一条语音消息: " + sendaudioMessageusernode.toString());
    }

    // 给一个群组发语音消息
    ObjectNode sendaudioMessagegroupnode =
        sendMessages(targetTypegr, targetgroup, audiomsg, from, ext);
    if (null != sendaudioMessagegroupnode) {
      LOGGER.info("给一个群组发语音消息: " + sendaudioMessagegroupnode.toString());
    }

    // 给用户发一条透传消息
    ObjectNode cmdmsg = factory.objectNode();
    cmdmsg.put("action", "gogogo");
    cmdmsg.put("type", "cmd");
    ObjectNode sendcmdMessageusernode = sendMessages(targetTypeus, targetusers, cmdmsg, from, ext);
    if (null != sendcmdMessageusernode) {
      LOGGER.info("给用户发一条透传消息: " + sendcmdMessageusernode.toString());
    }
  }