コード例 #1
0
  /**
   * 20141022.
   *
   * @param jObj the j obj
   * @param projectionStr the projection str
   * @return the FQDN value list cms
   * @throws JSONException the JSON exception
   */
  static List<String> getFQDNValueListCMS(JSONObject jObj, String projectionStr)
      throws JSONException {
    final List<String> labelList = new ArrayList<String>();

    if (!jObj.has("result")) {
      logger.error(
          "!!CMS_ERROR! result key is not in jOBJ in getFQDNValueListCMS!!: \njObj:"
              + PcStringUtils.renderJson(jObj));

      return labelList;
    }
    JSONArray jArr = (JSONArray) jObj.get("result");
    if (jArr == null || jArr.length() == 0) {
      return labelList;
    }
    for (int i = 0; i < jArr.length(); ++i) {
      JSONObject agentObj = jArr.getJSONObject(i);
      // properties can be null

      if (!agentObj.has(projectionStr)) {
        continue;
      }
      String label = (String) agentObj.get(projectionStr);

      if (label != null && !label.trim().isEmpty()) {
        labelList.add(label);
      }
    }

    return labelList;
  }
コード例 #2
0
 @Nullable
 private <T> Collection<T> parseOptionalArray(
     boolean shouldUseNestedValueJson,
     JSONObject json,
     JsonWeakParser<T> jsonParser,
     String... path)
     throws JSONException {
   if (shouldUseNestedValueJson) {
     final JSONObject js = JsonParseUtil.getNestedOptionalObject(json, path);
     if (js == null) {
       return null;
     }
     return parseArray(js, jsonParser, VALUE_ATTR);
   } else {
     final JSONArray jsonArray = JsonParseUtil.getNestedOptionalArray(json, path);
     if (jsonArray == null) {
       return null;
     }
     final Collection<T> res = new ArrayList<T>(jsonArray.length());
     for (int i = 0; i < jsonArray.length(); i++) {
       res.add(jsonParser.parse(jsonArray.get(i)));
     }
     return res;
   }
 }
コード例 #3
0
ファイル: MainTest.java プロジェクト: rajapaju/jersey
  /**
   * Test checks that a GET on the resource "/form/colours" with mime-type "application/json" shows
   * the appropriate colours based on the query param "match".
   */
  @Test
  public void testGetColoursAsJson() {
    Response response =
        target().path("form").path("colours").request(MediaType.APPLICATION_JSON).get();
    assertEquals(
        "GET on path '/form/colours' with mime type 'application/json' doesn't give expected response",
        Response.Status.OK,
        response.getStatusInfo());

    JSONArray jsonArray =
        target()
            .path("form")
            .path("colours")
            .request(MediaType.APPLICATION_JSON)
            .get(JSONArray.class);
    assertEquals(
        "Returned JSONArray doesn't have expected number of entries", 7, jsonArray.length());

    // with the query param "match" value "re"
    jsonArray =
        target("form/colours")
            .queryParam("match", "re")
            .request(MediaType.APPLICATION_JSON)
            .get(JSONArray.class);
    assertEquals(
        "Returned JSONArray doesn't have expected number of entries with the query param 'match=re'",
        2,
        jsonArray.length());
  }
コード例 #4
0
  private List<String> unmarshalJSON(JSONArray json) throws JSONException {
    List<String> list = new ArrayList<String>(json.length());

    for (int i = 0; i < json.length(); i++) {
      list.add(json.getString(i));
    }

    return list;
  }
コード例 #5
0
  private HashMap<String, String[]> getCriteria(JSONArray criterias) {
    HashMap<String, String[]> criteriaValues = new HashMap<String, String[]>();
    try {

      for (int i = 0; i < criterias.length(); i++) {
        JSONObject criteria = criterias.getJSONObject(i);
        if (!criteria.has("fieldName")
            && criteria.has("criteria")
            && criteria.has("_constructor")) {
          // nested criteria, eval it recursively
          JSONArray cs = criteria.getJSONArray("criteria");
          HashMap<String, String[]> c = getCriteria(cs);
          for (String k : c.keySet()) {
            criteriaValues.put(k, c.get(k));
          }
          continue;
        }
        final String operator = criteria.getString("operator");
        final String fieldName = criteria.getString("fieldName");
        String[] criterion;
        if (operator.equals(AdvancedQueryBuilder.OPERATOR_EXISTS)
            && criteria.has(AdvancedQueryBuilder.EXISTS_QUERY_KEY)) {
          String value = "";
          JSONArray values = criteria.getJSONArray("value");
          for (int v = 0; v < values.length(); v++) {
            value += value.length() > 0 ? ", " : "";
            value += "'" + values.getString(v) + "'";
          }
          String qry =
              criteria
                  .getString(AdvancedQueryBuilder.EXISTS_QUERY_KEY)
                  .replace(AdvancedQueryBuilder.EXISTS_VALUE_HOLDER, value);

          if (criteriaValues.containsKey(fieldName)) {
            // assuming it is possible to have more than one query for exists in same field, storing
            // them as array
            String[] originalCriteria = criteriaValues.get(fieldName);
            List<String> newCriteria = new ArrayList<String>(Arrays.asList(originalCriteria));
            newCriteria.add(qry);
            criteriaValues.put(fieldName, newCriteria.toArray(new String[newCriteria.size()]));
          } else {
            criteriaValues.put(
                fieldName, new String[] {AdvancedQueryBuilder.EXISTS_QUERY_KEY, qry});
          }
        } else {
          criterion = new String[] {operator, criteria.getString("value")};
          criteriaValues.put(fieldName, criterion);
        }
      }
    } catch (JSONException e) {
      log.error("Error getting criteria for custom query selector", e);
    }
    if (criteriaValues.isEmpty()) {
      return null;
    }
    return criteriaValues;
  }
コード例 #6
0
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  @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();
  }
コード例 #7
0
  /*
   * get a list type of request
   * e.g. GET /api/types/system/instances
   *
   * @param resource WebResource
   *
   * @param valueType class type
   *
   * @return list of objects
   *
   * @throws VnxeException unexpectedDataError
   */
  public List<T> getDataForObjects(Class<T> valueType) throws VNXeException {
    _logger.info("getting data: {}", _url);
    ClientResponse response = sendGetRequest(_resource);
    String emcCsrfToken = response.getHeaders().getFirst(EMC_CSRF_HEADER);
    if (emcCsrfToken != null) {
      saveEmcCsrfToken(emcCsrfToken);
    }

    saveClientCookies();
    String resString = response.getEntity(String.class);
    _logger.info("got data: " + resString);
    JSONObject res;
    List<T> returnedObjects = new ArrayList<T>();
    try {
      res = new JSONObject(resString);
      if (res != null) {
        JSONArray entries = res.getJSONArray(VNXeConstants.ENTRIES);
        if (entries != null && entries.length() > 0) {
          for (int i = 0; i < entries.length(); i++) {
            JSONObject entry = entries.getJSONObject(i);
            JSONObject object = (JSONObject) entry.get(VNXeConstants.CONTENT);
            if (object != null) {
              String objectString = object.toString();
              ObjectMapper mapper = new ObjectMapper();
              try {
                T returnedObject = mapper.readValue(objectString, valueType);
                returnedObjects.add(returnedObject);
              } catch (JsonParseException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);

              } catch (JsonMappingException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);
              } catch (IOException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);
              }
            }
          }
        }
      }
    } catch (JSONException e) {
      _logger.error(String.format("unexpected data returned: %s from: %s", resString, _url), e);
      throw VNXeException.exceptions.unexpectedDataError(resString, e);
    }
    return returnedObjects;
  }
コード例 #8
0
 private <T> List<T> getResponseObjects(Class<T> clazz, ClientResponse response)
     throws JSONException {
   JSONArray resp = response.getEntity(JSONArray.class);
   List<T> result = null;
   if (resp != null && resp.length() > 0) {
     result = new ArrayList<T>();
     for (int i = 0; i < resp.length(); i++) {
       JSONObject entry = resp.getJSONObject(i);
       T respObject = new Gson().fromJson(entry.toString(), clazz);
       result.add(respObject);
     }
   }
   return result;
 }
コード例 #9
0
  // ugly.. but separation into separate test cases would be probably uglier
  @Test
  public void getUserBookmarkList() {
    boolean thrown = false;

    try {
      WebResource webResource = resource();
      JSONObject user =
          webResource
              .path("resources/users/testuid")
              .accept("application/json")
              .get(JSONObject.class);
      assertTrue(user != null);

      webResource = client().resource(user.getString("bookmarks"));

      JSONObject bookmark = new JSONObject();
      bookmark
          .put("uri", "http://java.sun.com")
          .put("sdesc", "test desc")
          .put("ldesc", "long test description");
      webResource.type("application/json").post(bookmark);

      JSONArray bookmarks = webResource.accept("application/json").get(JSONArray.class);
      assertTrue(bookmarks != null);
      int bookmarksSize = bookmarks.length();

      String testBookmarkUrl = bookmarks.getString(0);
      WebResource bookmarkResource = client().resource(testBookmarkUrl);

      bookmark = bookmarkResource.accept("application/json").get(JSONObject.class);
      assertTrue(bookmark != null);

      bookmarkResource.delete();

      bookmarks =
          resource()
              .path("resources/users/testuid/bookmarks")
              .accept("application/json")
              .get(JSONArray.class);
      assertTrue(bookmarks != null);
      assertTrue(bookmarks.length() == (bookmarksSize - 1));

    } catch (Exception e) {
      e.printStackTrace();
      thrown = true;
    }

    assertFalse(thrown);
  }
コード例 #10
0
 private <T> Collection<T> parseArray(
     JSONObject jsonObject, JsonWeakParser<T> jsonParser, String arrayAttribute)
     throws JSONException {
   //        String type = jsonObject.getString("type");
   //        final String name = jsonObject.getString("name");
   final JSONArray valueObject = jsonObject.optJSONArray(arrayAttribute);
   if (valueObject == null) {
     return new ArrayList<T>();
   }
   Collection<T> res = new ArrayList<T>(valueObject.length());
   for (int i = 0; i < valueObject.length(); i++) {
     res.add(jsonParser.parse(valueObject.get(i)));
   }
   return res;
 }
コード例 #11
0
  // this is ugly but it would be probably uglier when divided into separate
  // test cases
  @Test
  public void step5_getUserBookmarkList() {
    boolean thrown = false;

    try {
      JSONObject user =
          target()
              .path("resources/users/testuid")
              .request("application/json")
              .get(JSONObject.class);
      assertTrue(user != null);

      final WebTarget webTarget = target(user.getString("bookmarks"));

      JSONObject bookmark = new JSONObject();
      bookmark
          .put("uri", "http://java.sun.com")
          .put("sdesc", "test desc")
          .put("ldesc", "long test description");
      webTarget.request().post(Entity.entity(bookmark, "application/json"));

      JSONArray bookmarks = webTarget.request("application/json").get(JSONArray.class);
      assertTrue(bookmarks != null);
      int bookmarksSize = bookmarks.length();

      String testBookmarkUrl = bookmarks.getString(0);

      final WebTarget bookmarkResource = target().path(testBookmarkUrl);
      bookmark = bookmarkResource.request("application/json").get(JSONObject.class);
      assertTrue(bookmark != null);

      bookmarkResource.request().delete();

      bookmarks =
          target()
              .path("resources/users/testuid/bookmarks")
              .request("application/json")
              .get(JSONArray.class);
      assertTrue(bookmarks != null);
      assertTrue(bookmarks.length() == (bookmarksSize - 1));

    } catch (Exception e) {
      e.printStackTrace();
      thrown = true;
    }

    assertFalse(thrown);
  }
コード例 #12
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);
 }
コード例 #13
0
  /**
   * In ode code, component names are used to identify a component though the variables storing
   * component names appear to be "type". While there's no harm in ode, here in build server, they
   * need to be separated. This method returns a name-type map, mapping the component names used in
   * ode to the corresponding type, aka fully qualified name. The type will be used to build apk.
   */
  private static Map<String, String> createNameTypeMap(File assetsDir)
      throws IOException, JSONException {
    Map<String, String> nameTypeMap = Maps.newHashMap();

    JSONArray simpleCompsJson =
        new JSONArray(
            Resources.toString(
                ProjectBuilder.class.getResource("/files/simple_components.json"), Charsets.UTF_8));
    for (int i = 0; i < simpleCompsJson.length(); ++i) {
      JSONObject simpleCompJson = simpleCompsJson.getJSONObject(i);
      nameTypeMap.put(simpleCompJson.getString("name"), simpleCompJson.getString("type"));
    }

    File extCompsDir = new File(assetsDir, "external_comps");
    if (!extCompsDir.exists()) {
      return nameTypeMap;
    }

    for (File extCompDir : extCompsDir.listFiles()) {
      if (!extCompDir.isDirectory()) {
        continue;
      }

      File extCompJsonFile = new File(extCompDir, "component.json");
      JSONObject extCompJson =
          new JSONObject(Resources.toString(extCompJsonFile.toURI().toURL(), Charsets.UTF_8));
      nameTypeMap.put(extCompJson.getString("name"), extCompJson.getString("type"));
    }

    return nameTypeMap;
  }
コード例 #14
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);
  }
コード例 #15
0
 public static List<String> parseJSON(JSONArray idJSON) throws JSONException {
   List<String> ids = new ArrayList<String>();
   for (int i = 0; i < idJSON.length(); i++) {
     ids.add(idJSON.getString(i));
   }
   return ids;
 }
コード例 #16
0
  private ComboAvailableList() {
    this.playerCombos = new HashMap<>();
    try {
      JSONObject configs = new JSONObject(FilesTools.readFile(ConfigPath.comboAvailableList));

      Iterator iterator = configs.keys();
      while (iterator.hasNext()) {
        String name = (String) iterator.next();
        EGameObject player = EGameObject.getEnumByValue(name);
        if (player != EGameObject.NULL) {
          this.playerCombos.put(player, new ArrayList<>());
          JSONArray combos = configs.getJSONArray(name);
          for (int i = 0; i < combos.length(); ++i) {
            this.playerCombos
                .get(player)
                .add(
                    new Pair<>(
                        combos.getJSONObject(i).getString("name"),
                        combos.getJSONObject(i).getString("combo")));
          }
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
コード例 #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
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  @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();
  }
コード例 #19
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);
   }
 }
コード例 #20
0
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  @Test
  public void shouldRespectQueryOffsetAndLimit() throws Exception {
    final String NODE_PATH = "nodeForOffsetAndLimitTest";

    createNode("/" + NODE_PATH, 1);
    createNode("/" + NODE_PATH, 2);
    createNode("/" + NODE_PATH, 3);
    createNode("/" + NODE_PATH, 4);

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query?offset=1&limit=2");
    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    String payload = "//element(" + NODE_PATH + ") order by @foo";

    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(2));

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[2]"));

    result = (JSONObject) results.get(1);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[3]"));
  }
コード例 #21
0
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  // @FixFor( "MODE-886" )
  @Test
  public void shouldAllowJcrSql2Query() throws Exception {
    final String NODE_PATH = "nodeForJcrSql2QueryTest";

    createNode("/" + NODE_PATH, 1);

    createNode("/" + NODE_PATH + "/child", 1);
    createNode("/" + NODE_PATH + "/child", 2);
    createNode("/" + NODE_PATH + "/child", 3);
    createNode("/" + NODE_PATH + "/child", 4);

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+sql2");

    String payload = "SELECT * FROM [nt:unstructured] WHERE ISCHILDNODE('/" + NODE_PATH + "')";

    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(4));
  }
コード例 #22
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;
  }
コード例 #23
0
ファイル: ModificarGrupoBean.java プロジェクト: matiasca/tsi2
  @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();
    }
  }
コード例 #24
0
  @POST
  @Path("/addNewParentTestField")
  @Produces("text/plain")
  @Consumes(MediaType.APPLICATION_JSON)
  public String addNewParentField(JSONObject obj) {
    try {
      JSONArray data = obj.getJSONArray("parentfileds");
      Set<ParentTestFields> ParentFieldList = new HashSet<ParentTestFields>();
      for (int curr = 0; curr < data.length(); curr++) {
        ParentTestFields pf = new ParentTestFields();
        pf.setParentField_IDName("PF");
        pf.setParent_FieldName(data.getJSONObject(curr).getString("parent_FieldName"));
        // pf.setfTest_RangeID(testFieldsRangeDBDriver.getTestFieldRangeByID(Integer.parseInt(data.getJSONObject(curr).getString("fTest_RangeID"))));
        pf.setfTest_NameID(
            testNamesDBDriver.getTestNameByID(
                Integer.parseInt(data.getJSONObject(curr).getString("fTest_NameID"))));
        ParentFieldList.add(pf);
      }

      for (ParentTestFields pf : ParentFieldList) {
        parentfieldDBDriver.addNewParentTestField(pf);
      }

    } catch (JSONException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return null;
    }
    return "TRUE";
  }
コード例 #25
0
  @Test
  public void testSubmit() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      String typesAsJSON = TypesSerialization.toJson(typeDefinition);
      System.out.println("typesAsJSON = " + typesAsJSON);

      WebResource resource = service.path("api/atlas/types");

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.POST, ClientResponse.class, typesAsJSON);
      assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);

      JSONObject response = new JSONObject(responseAsString);
      JSONArray typesAdded = response.getJSONArray(AtlasClient.TYPES);
      assertEquals(typesAdded.length(), 1);
      assertEquals(typesAdded.getJSONObject(0).getString("name"), typeDefinition.typeName);
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));
    }
  }
コード例 #26
0
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  @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();
  }
コード例 #27
0
 private boolean parseStructuredClause(JSONArray clauses, String hqlOperator)
     throws JSONException {
   boolean doOr = OPERATOR_OR.equals(hqlOperator);
   boolean doAnd = OPERATOR_AND.equals(hqlOperator);
   for (int i = 0; i < clauses.length(); i++) {
     final JSONObject clause = clauses.getJSONObject(i);
     if (clause.has(VALUE_KEY)
         && clause.get(VALUE_KEY) != null
         && clause.getString(VALUE_KEY).equals("")) {
       continue;
     }
     final boolean clauseResult = parseCriteria(clause);
     if (doOr && clauseResult) {
       return true;
     }
     if (doAnd && !clauseResult) {
       return false;
     }
   }
   if (doOr) {
     return false;
   } else if (doAnd) {
     return true;
   }
   return mainOperatorIsAnd;
 }
コード例 #28
0
  private JSONArray enrichProperties(String operatorClass, JSONArray properties)
      throws JSONException {
    JSONArray result = new JSONArray();
    for (int i = 0; i < properties.length(); i++) {
      JSONObject propJ = properties.getJSONObject(i);
      String propName = WordUtils.capitalize(propJ.getString("name"));
      String getPrefix =
          (propJ.getString("type").equals("boolean")
                  || propJ.getString("type").equals("java.lang.Boolean"))
              ? "is"
              : "get";
      String setPrefix = "set";
      OperatorClassInfo oci =
          getOperatorClassWithGetterSetter(
              operatorClass, setPrefix + propName, getPrefix + propName);
      if (oci == null) {
        result.put(propJ);
        continue;
      }
      MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName);
      MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName);

      if ((getterInfo != null && getterInfo.omitFromUI)
          || (setterInfo != null && setterInfo.omitFromUI)) {
        continue;
      }
      if (setterInfo != null) {
        addTagsToProperties(setterInfo, propJ);
      } else if (getterInfo != null) {
        addTagsToProperties(getterInfo, propJ);
      }
      result.put(propJ);
    }
    return result;
  }
コード例 #29
0
ファイル: ModificarGrupoBean.java プロジェクト: matiasca/tsi2
  public List<NombreMail> listarAdministradores() {

    JSONObject respuesta = new IGrupo().listarAdministradores(sesion.getTokenId());

    JSONArray admins = null;
    listaAdministradores.clear();
    try {

      admins = respuesta.getJSONArray("lista");
      if (admins != null) {

        for (int i = 0; i < admins.length(); i++) {

          JSONObject ob = admins.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaAdministradores.add(b);
        }
      }
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return listaAdministradores;
  }
コード例 #30
0
ファイル: JcrResourcesTest.java プロジェクト: jpav/modeshape
  @Test
  public void shouldRetrieveDataFromXPathQuery() throws Exception {
    final String NODE_PATH = "/nodeForQuery";
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items" + NODE_PATH);
    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\" }}";
    connection.getOutputStream().write(payload.getBytes());

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

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    payload = "//nodeForQuery";
    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

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

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is(NODE_PATH));
    assertThat((String) result.get("jcr:primaryType"), is("nt:unstructured"));
  }