Ejemplo n.º 1
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";
  }
Ejemplo n.º 2
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);
    }
  }
Ejemplo n.º 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);
 }
  /**
   * 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;
  }
Ejemplo n.º 5
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();
    }
  }
Ejemplo n.º 6
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;
  }
  /**
   * 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;
  }
Ejemplo n.º 8
0
  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;
  }
  @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));
    }
  }
Ejemplo n.º 10
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);
  }
 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;
 }
  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;
  }
Ejemplo n.º 13
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();
    }
  }
Ejemplo n.º 14
0
  public void cargarDatosGrupo() {

    JSONObject respuesta =
        new IGrupo().listarMiembrosDeGrupo(sesion.getTokenId(), grupoSeleccionado);
    JSONObject respuesta2 =
        new IGrupo().tecnicosFueraDelGrupo(sesion.getTokenId(), grupoSeleccionado);
    try {

      if (respuesta.has("jefe")) {
        JSONObject objetoJefe = respuesta.getJSONObject("jefe");
        nuevoAdministrador =
            objetoJefe.getString("nombre") + " " + objetoJefe.getString("apellido");
        if (!objetoJefe.getString("nombre").equals(""))
          nuevoAdministrador = nuevoAdministrador + " - ";
        nuevoAdministrador = nuevoAdministrador + objetoJefe.getString("correo");
      } else nuevoAdministrador = "No tiene administrador.";

      listaTecnicosGrupo.clear();
      JSONArray objetoIntegantes = respuesta.getJSONArray("grupo");
      if (objetoIntegantes != null) {
        for (int i = 0; i < objetoIntegantes.length(); i++) {
          JSONObject ob = objetoIntegantes.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaTecnicosGrupo.add(b);
        }
      }

      listaRestoTecnicos.clear();
      JSONArray objetoTecnicos = respuesta2.getJSONArray("Tecnicos");

      if (objetoTecnicos != null) {
        for (int i = 0; i < objetoTecnicos.length(); i++) {
          JSONObject ob = objetoTecnicos.getJSONObject(i);
          NombreMail b = new NombreMail();
          b.setMail(ob.getString("correo"));
          b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido"));
          listaRestoTecnicos.add(b);
        }
      }

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private void readCriteria(Map<String, String> parameters) throws JSONException {
    JSONArray criteriaArray = (JSONArray) JsonUtils.buildCriteria(parameters).get("criteria");
    selectedIds = new ArrayList<String>();
    selectedChValues = new HashMap<String, List<CharacteristicValue>>();
    nameFilter = null;
    searchKeyFilter = null;
    variantCreated = null;

    for (int i = 0; i < criteriaArray.length(); i++) {
      JSONObject criteria = criteriaArray.getJSONObject(i);
      // Basic advanced criteria handling
      if (criteria.has("_constructor")
          && "AdvancedCriteria".equals(criteria.getString("_constructor"))
          && criteria.has("criteria")) {
        JSONArray innerCriteriaArray = new JSONArray(criteria.getString("criteria"));
        criteria = innerCriteriaArray.getJSONObject(0);
      }
      String fieldName = criteria.getString("fieldName");
      // String operatorName = criteria.getString("operator");
      String value = criteria.getString("value");
      if (fieldName.equals("name")) {
        nameFilter = value;
      } else if (fieldName.equals("searchKey")) {
        searchKeyFilter = value;
      } else if (fieldName.equals("id")) {
        selectedIds.add(value);
      } else if (fieldName.equals("variantCreated")) {
        variantCreated = criteria.getBoolean("value");
      } else if (fieldName.equals("characteristicDescription")) {
        JSONArray values = new JSONArray(value);
        // All values belong to the same characteristicId, get the first one.
        String strCharacteristicId = null;
        List<CharacteristicValue> chValueIds = new ArrayList<CharacteristicValue>();
        for (int j = 0; j < values.length(); j++) {
          CharacteristicValue chValue =
              OBDal.getInstance().get(CharacteristicValue.class, values.getString(j));
          chValueIds.add(chValue);
          if (strCharacteristicId == null) {
            strCharacteristicId = (String) DalUtil.getId(chValue.getCharacteristic());
          }
        }
        selectedChValues.put(strCharacteristicId, chValueIds);
      }
    }
  }
  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;
  }
 /** @param configurable A topic type, an association type, or an association definition. */
 public ViewConfigurationModel(JSONObject configurable) {
   try {
     JSONArray topics = configurable.optJSONArray("view_config_topics");
     if (topics != null) {
       for (int i = 0; i < topics.length(); i++) {
         addConfigTopic(new TopicModel(topics.getJSONObject(i)));
       }
     }
   } catch (Exception e) {
     throw new RuntimeException(
         "Parsing ViewConfigurationModel failed (JSONObject=" + configurable + ")", e);
   }
 }
Ejemplo n.º 18
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;
  }
Ejemplo n.º 19
0
  public void verifyHsJobTaskCounters(JSONObject info, Task task) throws JSONException {

    assertEquals("incorrect number of elements", 2, info.length());

    WebServicesTestUtils.checkStringMatch(
        "id", MRApps.toString(task.getID()), info.getString("id"));
    // just do simple verification of fields - not data is correct
    // in the fields
    JSONArray counterGroups = info.getJSONArray("taskCounterGroup");
    for (int i = 0; i < counterGroups.length(); i++) {
      JSONObject counterGroup = counterGroups.getJSONObject(i);
      String name = counterGroup.getString("counterGroupName");
      assertTrue("name not set", (name != null && !name.isEmpty()));
      JSONArray counters = counterGroup.getJSONArray("counter");
      for (int j = 0; j < counters.length(); j++) {
        JSONObject counter = counters.getJSONObject(j);
        String counterName = counter.getString("name");
        assertTrue("name not set", (counterName != null && !counterName.isEmpty()));
        long value = counter.getLong("value");
        assertTrue("value  >= 0", value >= 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;
 }
Ejemplo n.º 21
0
 public List<Service> getAllVMs() throws ServiceInstantiationException {
   WebResource r = client.resource(base_url + "/vms");
   try {
     JSONArray services_json = r.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class);
     // JSONArray services_json = res.getJSONArray(SERVICES_TAG);
     List<Service> services = new LinkedList<Service>();
     for (int i = 0; i < services_json.length(); i++) {
       JSONObject service_json = services_json.getJSONObject(i);
       Service s = new Service(service_json.getString(ID_TAG));
       JSONArray vms_json = service_json.getJSONArray(RESOURCES_TAG);
       for (int j = 0; j < vms_json.length(); j++) {
         s.addVM(extractVMProperties(vms_json.getJSONObject(j)));
       }
       services.add(s);
     }
     return services;
   } catch (JSONEncodingException e) {
     throw new ServiceInstantiationException(
         "There was a problem when extracting the information about the VMs", e);
   } catch (JSONException e) {
     throw new ServiceInstantiationException(
         "There was a problem when extracting the information about the VMs", e);
   }
 }
Ejemplo n.º 22
0
 @Test
 public void getTaskmanagers() {
   try {
     String json = getFromHTTP("http://localhost:" + port + "/taskmanagers/");
     JSONObject parsed = new JSONObject(json);
     JSONArray taskManagers = parsed.getJSONArray("taskmanagers");
     Assert.assertNotNull(taskManagers);
     Assert.assertEquals(cluster.numTaskManagers(), taskManagers.length());
     JSONObject taskManager = taskManagers.getJSONObject(0);
     Assert.assertNotNull(taskManager);
     Assert.assertEquals(4, taskManager.getInt("freeSlots"));
   } catch (Throwable e) {
     e.printStackTrace();
     Assert.fail(e.getMessage());
   }
 }
 boolean applyFilter() throws JSONException {
   if (criteriaArray == null) {
     return true;
   }
   boolean finalResult = mainOperatorIsAnd;
   for (int i = 0; i < criteriaArray.length(); i++) {
     // Each element of the criteria array is added assuming an OR statement.
     JSONObject criteria = criteriaArray.getJSONObject(i);
     boolean critResult = parseCriteria(criteria);
     if (mainOperatorIsAnd) {
       finalResult &= critResult;
     } else {
       finalResult |= critResult;
     }
   }
   return finalResult;
 }
Ejemplo n.º 24
0
  /** 结束活动 */
  public synchronized void finish(
      Session session, String personExpression, String username, String userid) throws Exception {
    // 解析传递过来的对象属性
    JSONArray array = new JSONArray(personExpression);
    JSONObject firstObj = array.getJSONObject(0);
    final String data = firstObj.getString("data");
    JSONObject dataObj = new JSONObject(data);

    // 把前台传过来的,活动对应的人员,转换成json串
    state = "结束";
    // 设置完成人,完成时间
    this.setPerson(username);
    this.setUserid(userid);
    this.setFinishTime(new Date());
    // 根据每个转移创建任务和活动
    ProcessDef procDef = ProcessDefManager.getInstance().getProcessDef(processName);
    ActivityDef actDef = procDef.getActivity(defid);
    for (DiversionDef divDef : actDef.getSplits()) {
      ActivityDef tailDef = divDef.getTail();

      // 给流程中的变量赋值
      this.process.putVar(dataObj);

      // 如果不满足表达式条件,继续下一个
      String expression = divDef.getExpression();
      if (expression != null
          && !expression.equals("")
          && !this.process.getExpressionValue(expression)) {
        continue;
      }

      // 根据人员表达式,产生人员对照表
      String exp = tailDef.getPersonExpression();
      if (dataObj.has(tailDef.getName())) {
        String pExp = dataObj.getString(tailDef.getName());
        exp = pExp;
      }
      PersonService.Run(exp, session);

      ActivityInstance actIns = new ActivityInstance(tailDef, process, exp, username, userid, this);

      session.save(actIns);
    }
    session.update(this);
  }
Ejemplo n.º 25
0
  public void verifyHsTask(JSONArray arr, Job job, String type) throws JSONException {
    for (Task task : job.getTasks().values()) {
      TaskId id = task.getID();
      String tid = MRApps.toString(id);
      Boolean found = false;
      if (type != null && task.getType() == MRApps.taskType(type)) {

        for (int i = 0; i < arr.length(); i++) {
          JSONObject info = arr.getJSONObject(i);
          if (tid.matches(info.getString("id"))) {
            found = true;
            verifyHsSingleTask(info, task);
          }
        }
        assertTrue("task with id: " + tid + " not in web service output", found);
      }
    }
  }
Ejemplo n.º 26
0
  /**
   * This is a helper method to initialize the schema.
   *
   * @throws JSONException This exception is thrown if there is an error parsing the JSON which
   *     specified this schema.
   */
  private void initialize() throws JSONException {
    schema = new JSONObject(schemaJSON);

    Preconditions.checkState(
        schema.length() == NUM_KEYS_FIRST_LEVEL,
        "Expected "
            + NUM_KEYS_FIRST_LEVEL
            + " keys in the first level but found "
            + schema.length());

    if (schemaKeys != null) {
      schema.put(Schema.FIELD_SCHEMA_KEYS, SchemaUtils.createJSONObject(schemaKeys));
    }

    valueToType = Maps.newHashMap();

    JSONArray values = schema.getJSONArray(FIELD_VALUES);

    Preconditions.checkState(values.length() > 0, "The schema does not specify any values.");

    for (int index = 0; index < values.length(); index++) {
      JSONObject value = values.getJSONObject(index);
      String name = value.getString(FIELD_VALUES_NAME);
      String typeName = value.getString(FIELD_VALUES_TYPE);

      Type type = Type.NAME_TO_TYPE.get(typeName);
      valueToType.put(name, type);

      Preconditions.checkArgument(type != null, typeName + " is not a valid type.");
    }

    valueToType = Collections.unmodifiableMap(valueToType);
    valuesDescriptor = new FieldsDescriptor(valueToType);

    try {
      schema.put(FIELD_SCHEMA_TYPE, SCHEMA_TYPE);
      schema.put(FIELD_SCHEMA_VERSION, SCHEMA_VERSION);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }

    schemaJSON = this.schema.toString();
  }
Ejemplo n.º 27
0
  public List<VMProperties> getServiceVMs(String serviceId) throws ServiceInstantiationException {
    WebResource r = client.resource(base_url + "/vms/" + serviceId);
    try {
      JSONObject res = r.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class);

      JSONArray vms_json = res.getJSONArray(RESOURCES_TAG);
      List<VMProperties> vms = new LinkedList<VMProperties>();
      for (int i = 0; i < vms_json.length(); i++) {
        vms.add(extractVMProperties(vms_json.getJSONObject(i)));
      }
      return vms;
    } catch (JSONEncodingException e) {
      throw new ServiceInstantiationException(
          "There was a problem when extracting the information about the VMs", e);
    } catch (JSONException e) {
      throw new ServiceInstantiationException(
          "There was a problem when extracting the information about the VMs", e);
    }
  }
Ejemplo n.º 28
0
 /**
  * alternate names of this place as a list of string arrays with two entries the first entry is
  * the label and the second represents the language
  *
  * @return the alternateNames as comma separated list
  */
 public List<String[]> getAlternateNames() {
   try {
     if (data.has(ToponymProperty.alternateNames.name())) {
       List<String[]> parsedNames = new ArrayList<String[]>();
       JSONArray altNames = data.getJSONArray(ToponymProperty.alternateNames.name());
       for (int i = 0; i < altNames.length(); i++) {
         JSONObject altName = altNames.getJSONObject(i);
         if (altName.has("name")) {
           parsedNames.add(
               new String[] {
                 altName.getString("name"), altName.has("lang") ? altName.getString("lang") : null
               });
         } // else ignore alternate names without a name
       }
       return parsedNames;
     } else {
       return Collections.emptyList();
     }
   } catch (JSONException e) {
     throw new IllegalStateException(
         String.format("Unable to parse %s form %s", ToponymProperty.alternateNames, data));
   }
 }
Ejemplo n.º 29
0
  private String assertEntityIsRegistered(final String query, String... arg) throws Exception {
    waitFor(
        2000,
        new Predicate() {
          @Override
          public boolean evaluate() throws Exception {
            JSONArray results = dgiCLient.search(query);
            return results.length() == 1;
          }
        });

    String column = (arg.length > 0) ? arg[0] : "_col_0";

    JSONArray results = dgiCLient.search(query);
    JSONObject row = results.getJSONObject(0);
    if (row.has("__guid")) {
      return row.getString("__guid");
    } else if (row.has("$id$")) {
      return row.getJSONObject("$id$").getString("id");
    } else {
      return row.getJSONObject(column).getString("id");
    }
  }
  private Boolean processTweet(JSONObject jobj) {
    Date dd;
    String expandedUrl;
    JSONArray urlsjson, mediajson;

    Set<String> shortUrls = new HashSet<>();
    List<String> imageUrls = new ArrayList<>();

    // JSONObject objectToBeSent = new JSONObject();
    JSONArray finalUrls;

    try {
      // extract date_posted
      try {
        dd = dateFormatter.parse(jobj.getString("created_at"));
      } catch (ParseException ex) {
        log.error("ParseException during parsing creation date in processTweet: " + ex);
        logConn.error("ParseException during parsing creation date in processTweet: " + ex);
        dd = new Date();
      }
      jobj.put("date_posted", dd.getTime());

      // extract links 1
      if (jobj.getJSONObject("entities").has("urls")) {
        urlsjson = jobj.getJSONObject("entities").getJSONArray("urls");

        if (urlsjson != null && urlsjson.length() > 0)
          for (int i = 0; i < urlsjson.length(); i++) {
            // name expanded_url is misleading
            shortUrls.add(urlsjson.getJSONObject(i).getString("expanded_url"));
          }
      }

      // extract links 2
      if (jobj.getJSONObject("entities").has("media")) {
        mediajson = jobj.getJSONObject("entities").getJSONArray("media");

        if (mediajson != null && mediajson.length() > 0) {
          // extract tweet url
          if (mediajson.optJSONObject(0) != null)
            jobj.put("tweet_url", mediajson.getJSONObject(0).optString("url", null));

          for (int i = 0; i < mediajson.length(); i++) {
            shortUrls.add(mediajson.getJSONObject(i).getString("media_url"));
          }
        }
      }

      // follow and expand urls
      for (String myURL : shortUrls) {
        try {
          expandedUrl = expandShortURL(myURL);

          imageUrls.add(expandedUrl);
        } catch (IOException ex) {
          log.error("IOException during expanding URL: " + myURL + " : " + ex);
          logConn.error("IOException during expanding URL: " + myURL + " : " + ex);
        }
      }

      //            if (imageUrls.isEmpty())
      //                return false;

      if (imageUrls.size() > 0) {
        finalUrls = new JSONArray();
        for (String u : imageUrls) {
          finalUrls.put(u);
        }
        jobj.put("images", finalUrls);
      }
    } catch (JSONException ex) {
      log.error("JSONException during processing JSON object in consumer:" + ex);
      logConn.error("JSONException during processing JSON object in consumer:" + ex);
      return false;
    }

    return true;
  }