예제 #1
0
  @Path("/writeAttribute")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response writeAttributeResponse(String input) throws Exception {

    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    resource.Object obj = clientObject.getObjectMap().get(inputObj.getInt("ObjectId"));
    obj.setPmin(inputObj.getJSONObject("value").getString("pmin"));
    obj.setPmax(inputObj.getJSONObject("value").getString("pmax"));
    obj.setLessThan(inputObj.getJSONObject("value").getString("lt"));
    obj.setGreaterThan(inputObj.getJSONObject("value").getString("gt"));
    obj.setStep(inputObj.getJSONObject("value").getString("st"));
    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
예제 #2
0
  @Test
  public void testUpdatePreference() throws JSONException {

    JSONObject createPreferenceResult =
        mp.createPreference(
            "{'items':[{'title':'Prueba','quantity':1,'currency_id':'ARS','unit_price':10.5}]}");

    String createdPreferenceId = createPreferenceResult.getJSONObject("response").getString("id");

    JSONObject updatePreferenceResult =
        mp.updatePreference(
            createdPreferenceId, "{'items':[{'title':'Modified','quantity':2,'unit_price':2.2}]}");

    assertEquals(updatePreferenceResult.getInt("status"), 200);

    JSONObject getPreferenceResult = mp.getPreference(createdPreferenceId);

    assertEquals(getPreferenceResult.getInt("status"), 200);

    JSONObject obtainedPreference =
        (JSONObject) getPreferenceResult.getJSONObject("response").getJSONArray("items").get(0);

    assertEquals(obtainedPreference.getString("title"), "Modified");
    assertEquals(obtainedPreference.getInt("quantity"), 2);
    assertEquals(obtainedPreference.getDouble("unit_price"), 2, 2d);
  }
예제 #3
0
 @Test
 public void getMBean() throws JSONException {
   JSONObject jo =
       r.path(MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN)
           .accept("application/json")
           .get(JSONObject.class);
   assertEquals(
       "Not correct mbean name", jo.get("name"), MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN);
   assertEquals(
       "Not correct attribute value " + jo,
       MBeanServerSetup.DEFAULT,
       jo.getJSONObject("attributes").getJSONObject("MyAttr").get("value"));
   boolean isWritable =
       ((Boolean) jo.getJSONObject("attributes").getJSONObject("MyAttr").get("writable"))
           .booleanValue();
   assertTrue("Attrubute should be writable " + jo, isWritable);
   JSONArray operations = jo.getJSONArray("operations");
   for (int i = 0; i < operations.length(); i++) {
     JSONObject op = operations.getJSONObject(i);
     if (op.getString("name").equals("simpleMethod")) {
       return;
     }
   }
   fail("Should contain simpleMethod " + jo);
 }
  @Test
  public void testAppDataPush() throws Exception {
    final String topic = "xyz";
    final List<String> messages = new ArrayList<>();
    EmbeddedWebSocketServer server = new EmbeddedWebSocketServer(0);
    server.setWebSocket(
        new WebSocket.OnTextMessage() {

          @Override
          public void onMessage(String data) {
            messages.add(data);
          }

          @Override
          public void onOpen(WebSocket.Connection connection) {}

          @Override
          public void onClose(int closeCode, String message) {}
        });
    try {
      server.start();
      int port = server.getPort();
      TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class);
      GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class);
      dag.addStream("o1.outport", o1.outport, o2.inport1);
      dag.setAttribute(LogicalPlan.METRICS_TRANSPORT, new AutoMetricBuiltInTransport(topic));
      dag.setAttribute(LogicalPlan.GATEWAY_CONNECT_ADDRESS, "localhost:" + port);
      dag.setAttribute(LogicalPlan.PUBSUB_CONNECT_TIMEOUT_MILLIS, 2000);

      StramLocalCluster lc = new StramLocalCluster(dag);
      StreamingContainerManager dnmgr = lc.dnmgr;
      StramAppContext appContext = new StramTestSupport.TestAppContext(dag.getAttributes());

      AppDataPushAgent pushAgent = new AppDataPushAgent(dnmgr, appContext);
      pushAgent.init();
      pushAgent.pushData();
      Thread.sleep(1000);
      Assert.assertTrue(messages.size() > 0);
      pushAgent.close();
      JSONObject message = new JSONObject(messages.get(0));
      Assert.assertEquals(topic, message.getString("topic"));
      Assert.assertEquals("publish", message.getString("type"));
      JSONObject data = message.getJSONObject("data");
      Assert.assertTrue(StringUtils.isNotBlank(data.getString("appId")));
      Assert.assertTrue(StringUtils.isNotBlank(data.getString("appUser")));
      Assert.assertTrue(StringUtils.isNotBlank(data.getString("appName")));

      JSONObject logicalOperators = data.getJSONObject("logicalOperators");
      for (String opName : new String[] {"o1", "o2"}) {
        JSONObject opObj = logicalOperators.getJSONObject(opName);
        Assert.assertTrue(opObj.has("totalTuplesProcessed"));
        Assert.assertTrue(opObj.has("totalTuplesEmitted"));
        Assert.assertTrue(opObj.has("tuplesProcessedPSMA"));
        Assert.assertTrue(opObj.has("tuplesEmittedPSMA"));
        Assert.assertTrue(opObj.has("latencyMA"));
      }
    } finally {
      server.stop();
    }
  }
예제 #5
0
    @SuppressWarnings("unchecked")
    public static void assertEquals(@NotNull JSONObject expected, @NotNull JSONObject target)
        throws JSONException {

      for (Iterator<String> iterator = expected.keys(); iterator.hasNext(); ) {
        String key = iterator.next();

        // match the key names
        assertThat(target.get(key)).isNotNull();

        Object expectedValue = expected.get(key);
        Object targetValue = target.get(key);

        // match the value class types
        assertThat(expectedValue).isInstanceOf(targetValue.getClass());

        if (expectedValue instanceof JSONObject) {
          // For now, recurse only the JSON object
          assertThat(expected.getJSONObject(key)).isEqualTo(target.getJSONObject(key));
        } else if (expectedValue instanceof JSONArray) {
          // TODO handle JSONArray in the future
          Assert.fail();
        } else {
          // compare values
          assertThat(expectedValue).isEqualTo(targetValue);
        }
      }
    }
 private JSONObject getFieldUnisex(JSONObject json, String attributeName) throws JSONException {
   final JSONObject fieldsJson = json.getJSONObject(FIELDS);
   final JSONObject fieldJson = fieldsJson.getJSONObject(attributeName);
   if (fieldJson.has(VALUE_ATTR)) {
     return fieldJson.getJSONObject(VALUE_ATTR); // pre 5.0 way
   } else {
     return fieldJson; // JIRA 5.0 way
   }
 }
예제 #7
0
  @Test
  public void shouldPostNodeToValidPathWithMixinTypes() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:mixinTypes\": \"mix:referenceable\"}}";
    connection.getOutputStream().write(payload.getBytes());

    JSONObject body = new JSONObject(getResponseFor(connection));
    assertThat(body.length(), is(1));

    JSONObject properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    JSONArray values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    connection = (HttpURLConnection) postUrl.openConnection();

    // Make sure that we can retrieve the node with a GET
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
    body = new JSONObject(getResponseFor(connection));

    assertThat(body.length(), is(1));

    properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK));
    connection.disconnect();
  }
 private void setAttributeRec(int i, String[] parts, JSONObject attrs, Object value)
     throws JSONException {
   if (i == parts.length - 1) {
     attrs.put(parts[i], value);
     return;
   }
   if (attrs.has(parts[i])) {
     setAttributeRec(i + 1, parts, attrs.getJSONObject(parts[i]), value);
   } else {
     attrs.put(parts[i], new JSONObject());
     setAttributeRec(i + 1, parts, attrs.getJSONObject(parts[i]), value);
   }
 }
예제 #9
0
  @Test
  public void testTaskIdCountersDefault() throws JSONException, Exception {
    WebResource r = resource();
    Map<JobId, Job> jobsMap = appContext.getAllJobs();
    for (JobId id : jobsMap.keySet()) {
      String jobId = MRApps.toString(id);
      for (Task task : jobsMap.get(id).getTasks().values()) {

        String tid = MRApps.toString(task.getID());
        ClientResponse response =
            r.path("ws")
                .path("v1")
                .path("history")
                .path("mapreduce")
                .path("jobs")
                .path(jobId)
                .path("tasks")
                .path(tid)
                .path("counters")
                .get(ClientResponse.class);
        assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
        JSONObject json = response.getEntity(JSONObject.class);
        assertEquals("incorrect number of elements", 1, json.length());
        JSONObject info = json.getJSONObject("jobTaskCounters");
        verifyHsJobTaskCounters(info, task);
      }
    }
  }
예제 #10
0
 @Test
 public void testTasksQueryReduce() throws JSONException, Exception {
   WebResource r = resource();
   Map<JobId, Job> jobsMap = appContext.getAllJobs();
   for (JobId id : jobsMap.keySet()) {
     String jobId = MRApps.toString(id);
     String type = "r";
     ClientResponse response =
         r.path("ws")
             .path("v1")
             .path("history")
             .path("mapreduce")
             .path("jobs")
             .path(jobId)
             .path("tasks")
             .queryParam("type", type)
             .accept(MediaType.APPLICATION_JSON)
             .get(ClientResponse.class);
     assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
     JSONObject json = response.getEntity(JSONObject.class);
     assertEquals("incorrect number of elements", 1, json.length());
     JSONObject tasks = json.getJSONObject("tasks");
     JSONArray arr = tasks.getJSONArray("task");
     assertEquals("incorrect number of elements", 1, arr.length());
     verifyHsTask(arr, jobsMap.get(id), type);
   }
 }
예제 #11
0
  public static FinancialAccounting fromJSON(JSONObject jObj) throws JSONException, ParseException {
    if (jObj.has("result") && nullStringToNull(jObj, "result") != null) {
      jObj = jObj.getJSONObject("result");
    }

    final FinancialAccounting financialAccounting =
        new FinancialAccounting.Builder().revision(jObj.getLong("revision")).build();

    if (!jObj.isNull("items")) {
      final List<FinancialAccountingItem> items = new ArrayList<FinancialAccountingItem>();

      final JSONArray jItems = jObj.getJSONArray("items");

      for (int i = 0; i < jItems.length(); i++) {
        final JSONObject jItem = jItems.getJSONObject(i);

        final FinancialAccountingItem financialAccountingItem =
            FinancialAccountingItem.fromJSON(jItem);

        items.add(financialAccountingItem);
      }

      financialAccounting.setItems(items);
    }

    return financialAccounting;
  }
예제 #12
0
  @Override
  protected void createContainerRef() throws Exception {
    JSONObject dbConnObj = getDbConnObj(dbId);
    JSONObject dbInfoObj = dbConnObj.getJSONObject("dbInfo");
    String dbType = dbConnObj.getString("dbType").toUpperCase();
    String connName = dbConnObj.getString("name");
    String dbName = dbInfoObj.getString("dbName");

    setQualifiedDbName(
        DxtStoreUtil.formatQualifiedName(dbType.toLowerCase(), connName, "default", dbName));
    containerRef =
        DxtStoreUtil.createDxtRef(
            RelationalDataTypes.DATA_CONTAINER_SUPER_TYPE.getValue(),
            qualifiedDbName,
            DxtConstant.CONTAINER_TRAIT,
            getStepTraitName());

    containerRef.set("name", dbName);
    containerRef.set("id", dbConnObj.getString("id"));
    // todo: need to be modified
    containerRef.set("tag", "Just for hangzhou");
    containerRef.set("status", "AVAILABLE");
    containerRef.set("dbType", DxtDbType.findByName(dbType).getValue());

    accInfoRef = createAccInfoRef(dbConnObj, dbInfoObj);
    containerRef.set("accessInfo", accInfoRef);
  }
예제 #13
0
  @Test
  public void shouldRetrieveRootNodeForValidRepository() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    JSONObject body = new JSONObject(getResponseFor(connection));
    assertThat(body.length(), is(2));

    JSONObject properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(2));
    assertThat(properties.getString("jcr:primaryType"), is("mode:root"));
    assertThat(properties.get("jcr:uuid"), is(notNullValue()));

    JSONArray children = body.getJSONArray("children");
    assertThat(children.length(), is(1));
    assertThat(children.getString(0), is("jcr:system"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK));
    connection.disconnect();
  }
예제 #14
0
  @PostConstruct
  public void listarGrupos() {

    JSONArray lista = null;
    try {
      JSONObject respuesta = new IGrupo().listarGrupos(sesion.getTokenId());

      lista = respuesta.getJSONArray("lista");
      listaGrupos.clear();
      if (lista != null) {
        int len = lista.length();
        for (int i = 0; i < len; i++) {
          try {
            JSONObject ob = lista.getJSONObject(i);
            JSONObject ob2 = ob.getJSONObject("grupo");
            listaGrupos.add(ob2.getString("nombre"));
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }

      } else {
        listaGrupos.clear();
      }

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  @Override
  public boolean doWork(Message message) {

    try {
      // either create and insert a new payload:
      // JSONObject json_out = new JSONObject();
      // json_out.put("processed", true);
      // message.setPayload(json_out);

      // or work on the existing one:
      JSONObject tweet = message.getPayload();

      if (processTweet(tweet)) {
        JSONObject result = new JSONObject();
        result.put("tweet_id", tweet.getLong("id"));
        result.put("date_posted", tweet.getLong("date_posted"));
        if (tweet.has("images")) result.put("images", tweet.getJSONArray("images"));
        if (tweet.has("coordinates") && !tweet.isNull("coordinates"))
          result.put("coordinates", tweet.getJSONObject("coordinates"));
        message.setPayload(result);

        return true;
      } else {
        return false;
      }
    } catch (JSONException e) {
      log.error("JSONException: " + e);
      logConn.error("JSONException: " + e);
      return false;
    }
  }
예제 #16
0
  // verify the exception object default format is JSON
  @Test
  public void testNodeAppsStateInvalidDefault() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    Application app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    addAppContainers(app2);

    try {
      r.path("ws")
          .path("v1")
          .path("node")
          .path("apps")
          .queryParam("state", "FOO_STATE")
          .get(JSONObject.class);
      fail("should have thrown exception on invalid user query");
    } catch (UniformInterfaceException ue) {
      ClientResponse response = ue.getResponse();

      assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
      assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
      JSONObject msg = response.getEntity(JSONObject.class);
      JSONObject exception = msg.getJSONObject("RemoteException");
      assertEquals("incorrect number of elements", 3, exception.length());
      String message = exception.getString("message");
      String type = exception.getString("exception");
      String classname = exception.getString("javaClassName");
      verifyStateInvalidException(message, type, classname);
    }
  }
예제 #17
0
  public void testNodeHelper(String path, String media) throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);

    ClientResponse response =
        r.path("ws").path("v1").path("node").path(path).accept(media).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 2, appInfo.length());
    String id = appInfo.getJSONObject(0).getString("id");
    if (id.matches(app.getAppId().toString())) {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app2, hash2);
    } else {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app, hash);
    }
  }
예제 #18
0
  @Test
  public void testNodeAppsState() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    MockApp app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);
    app2.setState(ApplicationState.RUNNING);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .queryParam("state", ApplicationState.RUNNING.toString())
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 1, appInfo.length());
    verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
  }
예제 #19
0
  @Test
  public void shouldPostNodeToValidPathWithPrimaryType() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/nodeA");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload =
        "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}}";
    connection.getOutputStream().write(payload.getBytes());

    JSONObject body = new JSONObject(getResponseFor(connection));
    assertThat(body.length(), is(1));

    JSONObject properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("testProperty"), is("testValue"));
    assertThat(properties.get("multiValuedProperty"), instanceOf(JSONArray.class));

    JSONArray values = properties.getJSONArray("multiValuedProperty");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(2));
    assertThat(values.getString(0), is("value1"));
    assertThat(values.getString(1), is("value2"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();
  }
 private String getFieldStringUnisex(JSONObject json, String attributeName) throws JSONException {
   final JSONObject fieldsJson = json.getJSONObject(FIELDS);
   final Object fieldJson = fieldsJson.get(attributeName);
   if (fieldJson instanceof JSONObject) {
     return ((JSONObject) fieldJson).getString(VALUE_ATTR); // pre 5.0 way
   }
   return fieldJson.toString(); // JIRA 5.0 way
 }
예제 #21
0
 /**
  * The time zone is a complex Object encoded like <code><pre>
  * timezone: {
  *     dstOffset: -5
  *     gmtOffset: -6
  *     timeZoneId: "America/Chicago"
  * }
  * </pre></code> This mehtod does not further parse this data.
  *
  * @return the {@link JSONObject} with the time zone information
  */
 public JSONObject getTimezone() {
   try {
     return data.getJSONObject(ToponymProperty.timezone.name());
   } catch (JSONException e) {
     throw new IllegalStateException(
         String.format("Unable to parse %s form %s", ToponymProperty.timezone, data));
   }
 }
 private Map<String, String> parseSchema(JSONObject json) throws JSONException {
   final HashMap<String, String> res = Maps.newHashMap();
   final Iterator<String> it = getStringKeys(json);
   while (it.hasNext()) {
     final String fieldId = it.next();
     JSONObject fieldDefinition = json.getJSONObject(fieldId);
     res.put(fieldId, fieldDefinition.getString("type"));
   }
   return res;
 }
  /**
   * This is a helper method extracts and validates the information contained in the schema stub for
   * this schema.
   *
   * @param schemaStub The schema stub to extract information from and validate.
   * @throws JSONException This exception is thrown if there is an error processing the provided
   *     JSON schemaStub.
   */
  private void setSchemaStub(String schemaStub) throws JSONException {
    JSONObject jo = new JSONObject(schemaStub);
    SchemaUtils.checkValidKeysEx(jo, VALID_KEYS);

    JSONObject tempTime = jo.getJSONObject(FIELD_TIME);
    SchemaUtils.checkValidKeys(jo, VALID_TIME_KEYS);

    this.from = tempTime.getLong(FIELD_TIME_FROM);
    this.to = tempTime.getLong(FIELD_TIME_TO);
  }
예제 #24
0
  public void verifyClusterSchedulerFifo(JSONObject json) throws JSONException, Exception {
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("scheduler");
    assertEquals("incorrect number of elements", 1, info.length());
    info = info.getJSONObject("schedulerInfo");
    assertEquals("incorrect number of elements", 11, info.length());

    verifyClusterSchedulerFifoGeneric(
        info.getString("type"),
        info.getString("qstate"),
        (float) info.getDouble("capacity"),
        (float) info.getDouble("usedCapacity"),
        info.getInt("minQueueMemoryCapacity"),
        info.getInt("maxQueueMemoryCapacity"),
        info.getInt("numNodes"),
        info.getInt("usedNodeCapacity"),
        info.getInt("availNodeCapacity"),
        info.getInt("totalNodeCapacity"),
        info.getInt("numContainers"));
  }
예제 #25
0
 @Nullable
 protected static String getComposerBinDir(String composerPath) {
   try {
     String composerJsonContent = new String(Files.readAllBytes(Paths.get(composerPath)));
     JSONObject obj = new JSONObject(composerJsonContent);
     return obj.getJSONObject("config").get("bin-dir").toString();
   } catch (JSONException e) {
     return null;
   } catch (IOException e) {
     return null;
   }
 }
 private Collection<Field> parseFields(JSONObject json) throws JSONException {
   ArrayList<Field> res = new ArrayList<Field>(json.length());
   final Iterator<String> iterator = getStringKeys(json);
   while (iterator.hasNext()) {
     final String key = iterator.next();
     if (SPECIAL_FIELDS.contains(key)) {
       continue;
     }
     res.add(fieldParser.parse(json.getJSONObject(key), key));
   }
   return res;
 }
예제 #27
0
 private Employee jsonToEmployee(String jsonString) throws JSONException {
   // Creating a JSONObject from a String
   JSONObject nodeRoot = new JSONObject(jsonString);
   // Creating a sub-JSONObject from another JSONObject
   JSONObject nodeStats = nodeRoot.getJSONObject("employee");
   // Getting the value of a attribute in a JSONObject
   String firstName = nodeStats.getString("firstName");
   String lastName = nodeStats.getString("lastName");
   String department = nodeStats.getString("department");
   Double salary = nodeStats.getDouble("salary");
   return new Employee(firstName, lastName, department, salary);
 }
  private String getFieldStringValue(JSONObject json, String attributeName) throws JSONException {
    final JSONObject fieldsJson = json.getJSONObject(FIELDS);

    final Object summaryObject = fieldsJson.get(attributeName);
    if (summaryObject instanceof JSONObject) { // pre JIRA 5.0 way
      return ((JSONObject) summaryObject).getString(VALUE_ATTR);
    }
    if (summaryObject instanceof String) { // JIRA 5.0 way
      return (String) summaryObject;
    }
    throw new JSONException("Cannot parse [" + attributeName + "] from available fields");
  }
예제 #29
0
 @Test
 public void invokeMethodReturnMap() throws Exception {
   JSONObject o = new JSONObject();
   JSONArray params = new JSONArray(Arrays.asList("foo"));
   o.put("params", params);
   JSONObject jo =
       r.path(MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN + "/ops/methodReturnMap")
           .type("application/json")
           .post(JSONObject.class, o);
   assertEquals(
       "No correct return value " + jo, "value", jo.getJSONObject("return").getString("key"));
 }
예제 #30
0
  @Test
  public void shouldRetrieveNodeTypeSubgraphFromJcrSystemBranchIncludingSameNameSiblingChildren()
      throws Exception {
    URL postUrl =
        new URL(
            SERVER_URL
                + "/mode%3arepository/default/items/jcr:system/jcr:nodeTypes/nt:base?mode:depth=4");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
    JSONObject body = new JSONObject(getResponseFor(connection));
    connection.disconnect();

    JSONObject children = body.getJSONObject("children");
    JSONObject propDefn1 = children.getJSONObject("jcr:propertyDefinition");
    JSONObject propDefn2 = children.getJSONObject("jcr:propertyDefinition[2]");
    assertThat(propDefn1, is(notNullValue()));
    assertThat(propDefn2, is(notNullValue()));
  }