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;
  }
  @Override
  public JSONObject convertToATSJSON() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(ATSConstants.ENTITY, "tez_" + applicationAttemptId.toString());
    jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name());

    // Related Entities
    JSONArray relatedEntities = new JSONArray();
    JSONObject appEntity = new JSONObject();
    appEntity.put(ATSConstants.ENTITY, applicationAttemptId.getApplicationId().toString());
    appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID);
    JSONObject appAttemptEntity = new JSONObject();
    appAttemptEntity.put(ATSConstants.ENTITY, applicationAttemptId.toString());
    appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID);
    relatedEntities.put(appEntity);
    relatedEntities.put(appAttemptEntity);
    jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities);

    // TODO decide whether this goes into different events,
    // event info or other info.
    JSONArray events = new JSONArray();
    JSONObject startEvent = new JSONObject();
    startEvent.put(ATSConstants.TIMESTAMP, startTime);
    startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.AM_STARTED.name());
    events.put(startEvent);
    jsonObject.put(ATSConstants.EVENTS, events);

    return jsonObject;
  }
  /**
   * Parse cn page and write in hbase
   *
   * @param symbol
   */
  public static void parseCNSymbols(String symbol) {
    if (!Hbase.getData(symbol).equals("")) {
      // System.out.println(symbol + " Exists!");
      return;
    }
    String url = "http://xueqiu.com/S/" + symbol + "/historical.csv";
    Response rs = null;
    // System.out.println(url);
    try {
      Connection con = getConnection(url, "historyHttp");
      con.header("Referer", " http://xueqiu.com/S/" + symbol);
      rs = con.execute();
      // System.out.println(rs.body());
    } catch (IOException e1) {
      if (handleError) {
        System.out.println(symbol + " http error");
        errors.add(symbol);
      } else {
        WriteError(symbol);
        System.out.println(symbol + " http error");
      }
      return;
    }

    try {
      BufferedReader reader = new BufferedReader(new StringReader(rs.body())); // 换成你的文件名
      reader.readLine(); // 第一行信息,为标题信息,不用,如果需要,注释掉
      String line = null;
      JSONArray HistoricalData = new JSONArray();
      List<JSONArray> jsonLists = new ArrayList<JSONArray>();
      while ((line = reader.readLine()) != null) {
        String item[] = line.split(","); // CSV格式文件为逗号分隔符文件,这里根据逗号切分
        // System.out.println(item[0]);
        JSONArray DailyData = new JSONArray();
        for (int i = 1; i < item.length; i++) {
          item[i] = item[i].replace("\"", "");
          DailyData.put(item[i]);
        }
        if (Double.valueOf(DailyData.getString(2)) != 0) {
          jsonLists.add(DailyData);
        }
      }
      for (int i = (jsonLists.size() - 1); i >= 0; i--) {
        HistoricalData.put(jsonLists.get(i));
      }
      Hbase.addData(symbol, type, HistoricalData.toString());
      // System.out.println(symbol + " done");
      // System.out.println(jsonLists);
    } catch (Exception e) {

      if (handleError) {
        System.out.println(symbol + " parsing error");
        errors.add(symbol);
      } else {
        WriteError(symbol);
        System.out.println(symbol + " parsing error");
      }
    }
  }
Exemple #4
0
  private void setResponse(HttpServletResponse response, String id_c, String date)
      throws JSONException, IOException, ClassNotFoundException {
    JSONObject json = new JSONObject();
    JSONArray ja = new JSONArray();
    JSONArray jae = new JSONArray();
    try {
      int idcour = Integer.parseInt(id_c);
      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

      java.util.Date date1 = (java.util.Date) sdf1.parse(date);
      Date sqlStartDate = new Date(date1.getTime());
      System.out.println(sqlStartDate);
      System.out.println(date1);
      System.out.println(date);
      System.out.println(idcour);
      ConnectionBD maco = new ConnectionBD();
      ArrayList<Presence> cours = maco.getPresence(sqlStartDate, idcour);
      for (int i = 0; i < cours.size(); i++) {
        JSONObject jsonCour = new JSONObject();
        jsonCour.put("libelle", cours.get(i).getLibelle());
        jsonCour.put("nomE", cours.get(i).getNomEtud());
        jsonCour.put("prenomE", cours.get(i).getPrenomEtud());
        jsonCour.put("date", cours.get(i).getDate());
        jsonCour.put("presence", cours.get(i).getPresence());
        ja.put(jsonCour);
      }
      ArrayList<Eleve> eleves = maco.getEtudiants();
      for (int i = 0; i < eleves.size(); i++) {
        JSONObject jsonEleve = new JSONObject();
        jsonEleve.put("id", eleves.get(i).getId());
        jsonEleve.put("nom", eleves.get(i).getNom());
        jsonEleve.put("prenom", eleves.get(i).getPrenom());
        jsonEleve.put("historisation", eleves.get(i).getHistorisation());
        jsonEleve.put("idCarte", eleves.get(i).getIdCarte());
        jae.put(jsonEleve);
      }
      json.put("etat", "success");
      json.put("Presences", ja);
      json.put("Eleves", jae);
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    } catch (SQLException e) {
      json.put("etat", "Erreur accès base de données !");
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      json.put("etat", "Erreur de parsing de date !");
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    }
  }
  /**
   * Parse nasdq page and write in hbase
   *
   * @param symbol
   */
  public static void parseUSSymbols(String symbol) {
    if (!Hbase.getData(symbol).equals("")) {
      // System.out.println(symbol + " Exists!");
      return;
    }
    String result =
        HttpRequest.sendPost(
            "http://www.nasdaq.com/symbol/" + symbol.toLowerCase() + "/historical",
            length + "|false|" + symbol);
    if (result.equals("")) {
      WriteError(symbol);
      System.out.println(symbol + " result error");
      return;
    }
    // System.out.println(result);
    Document doc = Jsoup.parse(result);
    JSONArray HistoricalData = new JSONArray();
    try {
      Element body = doc.getElementsByTag("tbody").get(0);
      // System.out.println(body.toString());
      Elements nodes = body.getElementsByTag("tr");
      if (nodes.size() == 0) {
        WriteError(symbol);
        System.out.println(symbol + " size 0");
        return;
      }
      // System.out.println(nodes.size());
      for (Element node : nodes) {
        JSONArray DailyData = new JSONArray();
        Elements units = node.getElementsByTag("td");
        for (Element unit : units) {
          if (!unit.text().equals("")) {
            DailyData.put(unit.text());
          }
        }
        if (DailyData.length() > 0) {
          HistoricalData.put(DailyData);
        }
      }
      Hbase.addData(symbol, type, HistoricalData.toString());
      // System.out.println(symbol + " done");
    } catch (Exception e) {
      if (handleError) {
        errors.add(symbol);
      } else {
        WriteError(symbol);
        System.out.println(symbol + " parsing error");
      }

      // TODO: handle exception
    }
  }
Exemple #6
0
  @Test
  public void testArray() throws JSONException {
    Map<String, String> map = new HashMap<String, String>();
    map.put("serviceurl", "http:/");
    JSONArray j = new JSONArray();
    j.put(map);
    j.put(map);
    j.put(map);
    JSONObject arr = new JSONObject();
    arr.put("services", j);

    System.out.println(arr);
  }
Exemple #7
0
  private static JSONArray map2json(Collection<?> collection) throws JSONException, Exception {
    JSONArray result = new JSONArray();

    for (Object object : collection) {
      if (object instanceof Map) {
        result.put(map2json((Map<?, ?>) object));
      } else {
        result.put(object);
      }
    }

    return result;
  }
Exemple #8
0
  @Test
  public void testJSONArrayRepresentation() throws Exception {
    JSONArray array = new JSONArray();
    array.put(CONTENT).put("Two").put("Three").put(1).put(2.0);

    _test(array, JSONOArrayResource.class, MediaType.APPLICATION_JSON_TYPE);
  }
Exemple #9
0
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.TEXT_PLAIN)
  @Path("/userList")
  public String getHotTalkList() throws Exception {
    JSONObject jsonData = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    try {
      List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();
      lst = m_userDao.getUserList();
      if (lst.isEmpty()) {
        jsonData.put("err", "데이터가 없습니다.");
        return jsonData.toString();
      }
      Iterator<Map<String, Object>> itr = lst.iterator();
      int i = 0;
      while (itr.hasNext()) {
        itr.next();
        jsonArray.put(lst.get(i++));
      }
      jsonData.put("userList", jsonArray);
      jsonData.put("err", "");
    } catch (Exception ex) {
      ex.printStackTrace();
      System.out.println(ex.getMessage());
      jsonData.put("err", "시스템오류.");
    }
    // System.out.println("result : " + jsonData.toString());
    return jsonData.toString();
  }
Exemple #10
0
  public Object getAttribute(String userAttribute, boolean optional) throws InvalidClaimException {
    Object attribute = null;

    for (org.xdi.ldap.model.CustomAttribute customAttribute : customAttributes) {
      if (customAttribute.getName().equals(userAttribute)) {
        List<String> values = customAttribute.getValues();
        if (values != null) {
          if (values.size() == 1) {
            attribute = values.get(0);
          } else {
            JSONArray array = new JSONArray();
            for (String v : values) {
              array.put(v);
            }
            attribute = array;
          }
        }

        break;
      }
    }

    if (attribute != null) {
      return attribute;
    } else if (optional) {
      return attribute;
    } else {
      throw new InvalidClaimException("The claim " + userAttribute + " was not found.");
    }
  }
Exemple #11
0
  public void guardarCambiosGrupo() {

    JSONArray lista = new JSONArray();

    for (int i = 0; i < listaTecnicosGrupo.size(); i++) {
      lista.put(listaTecnicosGrupo.get(i).getMail());
    }

    JSONObject respuesta =
        new IGrupo()
            .modificiarGrupo(
                sesion.getTokenId(),
                grupoSeleccionado,
                nuevoNombreGrupo,
                lista,
                parsearMail(nuevoAdministrador));
    try {
      FacesMessage msg;
      if (respuesta.getInt("status") == 2) {
        msg = new FacesMessage("Grupo modificado con exito", "");
        listarGrupos();
      } else msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar grupo.", "");

      FacesContext.getCurrentInstance().addMessage(null, msg);

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 private <T> JSONArray getJSONArray(Collection<T> elements) throws JSONException {
   JSONArray jsonArray = new JSONArray();
   for (T element : elements) {
     jsonArray.put(new JSONObject(element.toString()));
   }
   return jsonArray;
 }
Exemple #13
0
 public static JSONArray concatArray(JSONArray... arrs) throws JSONException {
   JSONArray result = new JSONArray();
   for (JSONArray arr : arrs) {
     for (int i = 0; i < arr.length(); i++) {
       result.put(arr.get(i));
     }
   }
   return result;
 }
Exemple #14
0
  @SuppressWarnings("unchecked")
  public JSONArray ring(String keyspace) throws JSONException {
    JSONArray ring = new JSONArray();
    Map<String, String> tokenToEndpoint = getTokenToEndpointMap();
    List<String> sortedTokens = new ArrayList<String>(tokenToEndpoint.keySet());

    Collection<String> liveNodes = getLiveNodes();
    Collection<String> deadNodes = getUnreachableNodes();
    Collection<String> joiningNodes = getJoiningNodes();
    Collection<String> leavingNodes = getLeavingNodes();
    Collection<String> movingNodes = getMovingNodes();
    Map<String, String> loadMap = getLoadMap();

    String format = "%-16s%-12s%-12s%-7s%-8s%-16s%-20s%-44s%n";

    // Calculate per-token ownership of the ring
    Map<InetAddress, Float> ownerships;
    try {
      ownerships = effectiveOwnership(keyspace);
    } catch (IllegalStateException ex) {
      ownerships = getOwnership();
    }

    for (String token : sortedTokens) {
      String primaryEndpoint = tokenToEndpoint.get(token);
      String dataCenter;
      try {
        dataCenter = getEndpointSnitchInfoProxy().getDatacenter(primaryEndpoint);
      } catch (UnknownHostException e) {
        dataCenter = "Unknown";
      }
      String rack;
      try {
        rack = getEndpointSnitchInfoProxy().getRack(primaryEndpoint);
      } catch (UnknownHostException e) {
        rack = "Unknown";
      }
      String status =
          liveNodes.contains(primaryEndpoint)
              ? "Up"
              : deadNodes.contains(primaryEndpoint) ? "Down" : "?";

      String state = "Normal";

      if (joiningNodes.contains(primaryEndpoint)) state = "Joining";
      else if (leavingNodes.contains(primaryEndpoint)) state = "Leaving";
      else if (movingNodes.contains(primaryEndpoint)) state = "Moving";

      String load = loadMap.containsKey(primaryEndpoint) ? loadMap.get(primaryEndpoint) : "?";
      String owns =
          new DecimalFormat("##0.00%")
              .format(ownerships.get(token) == null ? 0.0F : ownerships.get(token));
      ring.put(createJson(primaryEndpoint, dataCenter, rack, status, state, load, owns, token));
    }
    return ring;
  }
  private String mapTagsField(List<String> tags) {
    JSONArray result = new JSONArray();
    if (tags != null && tags.size() > 0) {

      for (String tag : tags) {
        result.put(JsonUtil.removeJsonKeywords(tag));
      }
    }
    return result.toString();
  }
 @SuppressWarnings("unchecked")
 private <T> void convertToJson(Iterable<T> items, JSONArray results) throws JSONException {
   for (T resultObject : items) {
     if (resultObject instanceof Element) {
       results.put(GraphSONUtility.jsonFromElement((Element) resultObject, null, graphsonMode));
     } else if (resultObject instanceof List) {
       convertToJson((Iterable<T>) resultObject, results);
     }
   }
 }
Exemple #17
0
  /**
   * @param rs
   * @return
   * @throws SQLException
   * @throws JSONException
   */
  public static JSONArray convertToJSONArray(ResultSet rs) throws SQLException, JSONException {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();

    while (rs.next()) {
      int numColumns = rsmd.getColumnCount();
      JSONObject obj = new JSONObject();
      for (int i = 1; i < numColumns + 1; i++) {
        String column_name = rsmd.getColumnLabel(i);

        if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
          obj.put(column_name, rs.getArray(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
          obj.put(column_name, rs.getInt(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
          obj.put(column_name, rs.getBoolean(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
          obj.put(column_name, rs.getBlob(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
          obj.put(column_name, rs.getDouble(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
          obj.put(column_name, rs.getFloat(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
          obj.put(column_name, rs.getInt(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
          obj.put(column_name, rs.getNString(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
          obj.put(column_name, rs.getString(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
          obj.put(column_name, rs.getInt(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
          obj.put(column_name, rs.getInt(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
          obj.put(column_name, rs.getDate(column_name));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
          obj.put(column_name, rs.getTimestamp(column_name));
        } else {
          obj.put(column_name, rs.getObject(column_name));
        }
      }
      json.put(obj);
    }

    return json;
  }
  @GET
  @RolesAllowed({"Supervisor"})
  @Produces(MediaType.APPLICATION_JSON)
  public Response getTipoRelatorio() throws JSONException {
    JSONArray resposta = new JSONArray();

    for (TipoRelatorioEnum tipoRelatorioEnum : TipoRelatorioEnum.values()) {
      JSONObject obj = new JSONObject();
      obj.put("rotulo", tipoRelatorioEnum.getRotulo());
      obj.put("nome", tipoRelatorioEnum.toString());
      resposta.put(obj);
    }

    try {
      return Response.status(Response.Status.OK)
          .entity(resposta)
          .type(MediaType.APPLICATION_JSON)
          .build();
    } catch (Exception ex) {
      LOGGER.error(ex);
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
Exemple #19
0
  /**
   * This method set fixed state of data table.
   *
   * @param incomingData
   * @return
   * @throws Exception
   */
  @POST
  @Path("/submit")
  @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
  @Produces(MediaType.APPLICATION_JSON)
  public Response submitData(String incomingData) throws Exception {

    String returnString = null;
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    SchemaPostgresDB dao = new SchemaPostgresDB();

    try {
      JSONObject data = new JSONObject(incomingData);
      System.out.println("jsonData: " + data.toString());

      // we store info about how many pages and streams we have in our presentation
      int http_code =
          dao.submitData(
              data.optInt("lastpage"), data.optInt("laststream"), data.optInt("totalstreams"));

      if (http_code == 200) {
        jsonObject.put("HTTP_CODE", "200");
        jsonObject.put("MSG", "Data has beed succesfully submit");
        returnString = jsonArray.put(jsonObject).toString();
      } else {
        return Response.status(500).entity("Unable to erase items").build();
      }

      System.out.println("returnString: " + returnString);

    } catch (Exception e) {
      e.printStackTrace();
      return Response.status(500).entity("Server was not able to process your request").build();
    }

    return Response.ok(returnString).build();
  }
Exemple #20
0
  /**
   * This method allow to delete all data from data table and set data table state as unfixed
   *
   * @param incomingData
   * @return
   * @throws Exception
   */
  @POST
  @Path("/reset")
  @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
  @Produces(MediaType.APPLICATION_JSON)
  public Response resetData(String incomingData) throws Exception {

    String returnString = null;
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    SchemaPostgresDB dao = new SchemaPostgresDB();

    try {

      JSONObject data = new JSONObject();

      int http_code = dao.resetData();

      if (http_code == 200) {

        jsonObject.put("HTTP_CODE", "200");
        jsonObject.put("MSG", "Data has beed succesfully erased");

        returnString = jsonArray.put(jsonObject).toString();
      } else {
        return Response.status(500).entity("Unable to erase items").build();
      }

      System.out.println("returnString: " + returnString);

    } catch (Exception e) {
      e.printStackTrace();
      return Response.status(500).entity("Server was not able to process your request").build();
    }

    return Response.ok(returnString).build();
  }
  private String serializeHelper(Message result, ResultFormatter resultFormatter) throws Exception {
    DataResultSnapshot gResult = (DataResultSnapshot) result;

    JSONObject jo = new JSONObject();
    jo.put(Result.FIELD_ID, gResult.getId());
    jo.put(Result.FIELD_TYPE, gResult.getType());

    JSONArray ja = new JSONArray();

    for (GPOMutable value : gResult.getValues()) {
      JSONObject dataValue =
          GPOUtils.serializeJSONObject(
              value, ((DataQuerySnapshot) gResult.getQuery()).getFields(), resultFormatter);
      ja.put(dataValue);
    }

    jo.put(DataResultSnapshot.FIELD_DATA, ja);

    if (!gResult.isOneTime()) {
      jo.put(Result.FIELD_COUNTDOWN, gResult.getCountdown());
    }

    return jo.toString();
  }
  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;
  }
  public JSONObject describeOperator(String clazz) throws Exception {
    TypeGraphVertex tgv = typeGraph.getTypeGraphVertex(clazz);
    if (tgv.isInstantiable()) {
      JSONObject response = new JSONObject();
      JSONArray inputPorts = new JSONArray();
      JSONArray outputPorts = new JSONArray();
      // Get properties from ASM

      JSONObject operatorDescriptor = describeClassByASM(clazz);
      JSONArray properties = operatorDescriptor.getJSONArray("properties");

      properties = enrichProperties(clazz, properties);

      JSONArray portTypeInfo = operatorDescriptor.getJSONArray("portTypeInfo");

      List<CompactFieldNode> inputPortfields = typeGraph.getAllInputPorts(clazz);
      List<CompactFieldNode> outputPortfields = typeGraph.getAllOutputPorts(clazz);

      try {
        for (CompactFieldNode field : inputPortfields) {
          JSONObject inputPort = setFieldAttributes(clazz, field);
          if (!inputPort.has("optional")) {
            inputPort.put(
                "optional",
                false); // input port that is not annotated is default to be not optional
          }
          if (!inputPort.has(SCHEMA_REQUIRED_KEY)) {
            inputPort.put(SCHEMA_REQUIRED_KEY, false);
          }
          inputPorts.put(inputPort);
        }

        for (CompactFieldNode field : outputPortfields) {
          JSONObject outputPort = setFieldAttributes(clazz, field);

          if (!outputPort.has("optional")) {
            outputPort.put(
                "optional", true); // output port that is not annotated is default to be optional
          }
          if (!outputPort.has("error")) {
            outputPort.put("error", false);
          }
          if (!outputPort.has(SCHEMA_REQUIRED_KEY)) {
            outputPort.put(SCHEMA_REQUIRED_KEY, false);
          }
          outputPorts.put(outputPort);
        }

        response.put("name", clazz);
        response.put("properties", properties);
        response.put(PORT_TYPE_INFO_KEY, portTypeInfo);
        response.put("inputPorts", inputPorts);
        response.put("outputPorts", outputPorts);

        OperatorClassInfo oci = classInfo.get(clazz);

        if (oci != null) {
          if (oci.comment != null) {
            String[] descriptions;
            // first look for a <p> tag
            String keptPrefix = "<p>";
            descriptions = oci.comment.split("<p>", 2);
            if (descriptions.length == 0) {
              keptPrefix = "";
              // if no <p> tag, then look for a blank line
              descriptions = oci.comment.split("\n\n", 2);
            }
            if (descriptions.length > 0) {
              response.put("shortDesc", descriptions[0]);
            }
            if (descriptions.length > 1) {
              response.put("longDesc", keptPrefix + descriptions[1]);
            }
          }
          response.put("category", oci.tags.get("@category"));
          String displayName = oci.tags.get("@displayName");
          if (displayName == null) {
            displayName = decamelizeClassName(ClassUtils.getShortClassName(clazz));
          }
          response.put("displayName", displayName);
          String tags = oci.tags.get("@tags");
          if (tags != null) {
            JSONArray tagArray = new JSONArray();
            for (String tag : StringUtils.split(tags, ',')) {
              tagArray.put(tag.trim().toLowerCase());
            }
            response.put("tags", tagArray);
          }
          String doclink = oci.tags.get("@doclink");
          if (doclink != null) {
            response.put("doclink", doclink + "?" + getDocName(clazz));
          } else if (clazz.startsWith("com.datatorrent.lib.")
              || clazz.startsWith("com.datatorrent.contrib.")) {
            response.put("doclink", DT_OPERATOR_DOCLINK_PREFIX + "?" + getDocName(clazz));
          }
        }
      } catch (JSONException ex) {
        throw new RuntimeException(ex);
      }
      return response;
    } else {
      throw new UnsupportedOperationException();
    }
  }
  private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {
      for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
        Method readMethod = pd.getReadMethod();
        if (readMethod != null) {
          if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
            // skip getDeclaringClass
            continue;
          } else if ("class".equals(pd.getName())) {
            // skip getClass
            continue;
          }
        } else {
          // yields com.datatorrent.api.Context on JDK6 and
          // com.datatorrent.api.Context.OperatorContext with JDK7
          if ("up".equals(pd.getName())
              && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
            continue;
          }
        }
        // LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

        Class<?> propertyType = pd.getPropertyType();
        if (propertyType != null) {
          JSONObject propertyObj = new JSONObject();
          propertyObj.put("name", pd.getName());
          propertyObj.put("canGet", readMethod != null);
          propertyObj.put("canSet", pd.getWriteMethod() != null);
          if (readMethod != null) {
            for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
              OperatorClassInfo oci = classInfo.get(c.getName());
              if (oci != null) {
                MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                if (getMethodInfo != null) {
                  addTagsToProperties(getMethodInfo, propertyObj);
                  break;
                }
              }
            }
            // type can be a type symbol or parameterized type
            td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
          } else {
            if (pd.getWriteMethod() != null) {
              td.setTypeArguments(
                  clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj);
            }
          }
          // if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() &&
          // !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
          //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
          // }
          arr.put(propertyObj);
        }
      }
    } catch (JSONException ex) {
      throw new RuntimeException(ex);
    }
    return arr;
  }
  private boolean parseSingleClause(JSONObject jsonCriteria) throws JSONException {
    String operator = jsonCriteria.getString(OPERATOR_KEY);

    if (operator.equals(OPERATOR_BETWEEN)
        || operator.equals(OPERATOR_BETWEENINCLUSIVE)
        || operator.equals(OPERATOR_IBETWEEN)
        || operator.equals(OPERATOR_IBETWEENINCLUSIVE)) {
      return parseBetween(jsonCriteria, operator, true);
    }

    Object value = jsonCriteria.has(VALUE_KEY) ? jsonCriteria.get(VALUE_KEY) : null;

    if (operator.equals(OPERATOR_EXISTS)) {
      // not supported
      return mainOperatorIsAnd;
    }

    String fieldName = jsonCriteria.getString(FIELD_NAME_KEY);

    // translate to a OR for each value
    if (value instanceof JSONArray) {
      final JSONArray jsonArray = (JSONArray) value;
      final JSONObject advancedCriteria = new JSONObject();
      advancedCriteria.put(OPERATOR_KEY, OPERATOR_OR);
      final JSONArray subCriteria = new JSONArray();
      for (int i = 0; i < jsonArray.length(); i++) {
        final JSONObject subCriterion = new JSONObject();
        subCriterion.put(OPERATOR_KEY, operator);
        subCriterion.put(FIELD_NAME_KEY, fieldName);
        subCriterion.put(VALUE_KEY, jsonArray.get(i));
        subCriteria.put(i, subCriterion);
      }
      advancedCriteria.put(CRITERIA_KEY, subCriteria);
      return parseAdvancedCriteria(advancedCriteria);
    }

    // Retrieves the UTC time zone offset of the client
    if (jsonCriteria.has("minutesTimezoneOffset")) {
      int clientMinutesTimezoneOffset =
          Integer.parseInt(jsonCriteria.get("minutesTimezoneOffset").toString());
      Calendar now = Calendar.getInstance();
      // Obtains the UTC time zone offset of the server
      int serverMinutesTimezoneOffset =
          (now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET)) / (1000 * 60);
      // Obtains the time zone offset between the server and the client
      clientUTCMinutesTimeZoneDiff = clientMinutesTimezoneOffset;
      UTCServerMinutesTimeZoneDiff = serverMinutesTimezoneOffset;
    }

    if (operator.equals(OPERATOR_ISNULL) || operator.equals(OPERATOR_NOTNULL)) {
      value = null;
    }

    // if a comparison is done on an equal date then replace
    // with a between start time and end time on that date
    if (operator.equals(OPERATOR_EQUALS) || operator.equals(OPERATOR_EQUALSFIELD)) {
      Object curValue = recordMap.get(fieldName);
      if (curValue instanceof Date) {
        if (operator.equals(OPERATOR_EQUALS)) {
          return parseSimpleClause(fieldName, OPERATOR_GREATEROREQUAL, value)
              && parseSimpleClause(fieldName, OPERATOR_LESSOREQUAL, value);

        } else {
          return parseSimpleClause(fieldName, OPERATOR_GREATEROREQUALFIELD, value)
              && parseSimpleClause(fieldName, OPERATOR_LESSOREQUALFIElD, value);
        }
      }
    }

    return parseSimpleClause(fieldName, operator, value);
  }
  /**
   * Initializes the schema JSON and schema metadata.
   *
   * @throws JSONException This exception is thrown when there is an exception building the schema
   *     for the AppData dimensions schema.
   */
  private void initialize() throws JSONException {
    schema = new JSONObject();

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

    schema.put(SnapshotSchema.FIELD_SCHEMA_TYPE, DimensionalSchema.SCHEMA_TYPE);
    schema.put(SnapshotSchema.FIELD_SCHEMA_VERSION, DimensionalSchema.SCHEMA_VERSION);

    if (!configurationSchema.getTags().isEmpty()) {
      schema.put(FIELD_TAGS, new JSONArray(configurationSchema.getTags()));
    }

    // time
    time = new JSONObject();
    schema.put(FIELD_TIME, time);
    JSONArray bucketsArray = new JSONArray(configurationSchema.getBucketsString());
    time.put(FIELD_TIME_BUCKETS, bucketsArray);
    time.put(FIELD_SLIDING_AGGREGATE_SUPPORTED, true);

    // keys
    keys = new JSONArray(configurationSchema.getKeysString());

    for (int keyIndex = 0; keyIndex < keys.length(); keyIndex++) {
      JSONObject keyJo = keys.getJSONObject(keyIndex);
      String keyName = keyJo.getString(DimensionalConfigurationSchema.FIELD_KEYS_NAME);
      List<String> tags = configurationSchema.getKeyToTags().get(keyName);

      if (!tags.isEmpty()) {
        keyJo.put(FIELD_TAGS, new JSONArray(tags));
      }
    }

    schema.put(DimensionalConfigurationSchema.FIELD_KEYS, keys);

    // values
    JSONArray values = new JSONArray();
    schema.put(SnapshotSchema.FIELD_VALUES, values);

    FieldsDescriptor inputValuesDescriptor = configurationSchema.getInputValuesDescriptor();
    Map<String, Map<String, Type>> allValueToAggregator =
        configurationSchema.getSchemaAllValueToAggregatorToType();

    for (Map.Entry<String, Map<String, Type>> entry : allValueToAggregator.entrySet()) {
      String valueName = entry.getKey();

      for (Map.Entry<String, Type> entryAggType : entry.getValue().entrySet()) {
        String aggregatorName = entryAggType.getKey();
        Type outputValueType = entryAggType.getValue();

        JSONObject value = new JSONObject();
        String combinedName =
            valueName + DimensionalConfigurationSchema.ADDITIONAL_VALUE_SEPERATOR + aggregatorName;
        value.put(SnapshotSchema.FIELD_VALUES_NAME, combinedName);
        value.put(SnapshotSchema.FIELD_VALUES_TYPE, outputValueType.getName());

        List<String> tags = configurationSchema.getValueToTags().get(valueName);

        if (!tags.isEmpty()) {
          value.put(FIELD_TAGS, new JSONArray(tags));
        }

        values.put(value);
      }
    }

    JSONArray dimensions = new JSONArray();

    for (int combinationID = 0;
        combinationID < configurationSchema.getDimensionsDescriptorIDToKeys().size();
        combinationID++) {

      Fields fields = configurationSchema.getDimensionsDescriptorIDToKeys().get(combinationID);
      Map<String, Set<String>> fieldToAggregatorAdditionalValues =
          configurationSchema
              .getDimensionsDescriptorIDToFieldToAggregatorAdditionalValues()
              .get(combinationID);

      JSONObject combination = new JSONObject();
      JSONArray combinationArray = new JSONArray();

      for (String field : fields.getFields()) {
        combinationArray.put(field);
      }

      combination.put(
          DimensionalConfigurationSchema.FIELD_DIMENSIONS_COMBINATIONS, combinationArray);

      if (!fieldToAggregatorAdditionalValues.isEmpty()) {
        JSONArray additionalValueArray = new JSONArray();

        for (Map.Entry<String, Set<String>> entry : fieldToAggregatorAdditionalValues.entrySet()) {
          String valueName = entry.getKey();

          for (String aggregatorName : entry.getValue()) {
            JSONObject additionalValueObject = new JSONObject();
            String combinedName =
                valueName
                    + DimensionalConfigurationSchema.ADDITIONAL_VALUE_SEPERATOR
                    + aggregatorName;
            Type inputValueType = inputValuesDescriptor.getType(valueName);

            if (!configurationSchema.getAggregatorRegistry().isAggregator(aggregatorName)) {
              if (aggregatorName == null) {
                LOG.error("{} is not a valid aggregator.", aggregatorName);
              }
            }

            Type outputValueType;

            if (configurationSchema
                .getAggregatorRegistry()
                .isIncrementalAggregator(aggregatorName)) {
              IncrementalAggregator aggregator =
                  configurationSchema
                      .getAggregatorRegistry()
                      .getNameToIncrementalAggregator()
                      .get(aggregatorName);

              outputValueType = aggregator.getOutputType(inputValueType);
            } else {
              outputValueType =
                  configurationSchema
                      .getAggregatorRegistry()
                      .getNameToOTFAggregators()
                      .get(aggregatorName)
                      .getOutputType();
            }

            additionalValueObject.put(
                DimensionalConfigurationSchema.FIELD_VALUES_NAME, combinedName);
            additionalValueObject.put(
                DimensionalConfigurationSchema.FIELD_VALUES_TYPE, outputValueType.getName());
            additionalValueArray.put(additionalValueObject);
          }
        }

        combination.put(
            DimensionalConfigurationSchema.FIELD_DIMENSIONS_ADDITIONAL_VALUES,
            additionalValueArray);
      }

      dimensions.put(combination);
    }

    schema.put(DimensionalConfigurationSchema.FIELD_DIMENSIONS, dimensions);

    this.schemaJSON = this.schema.toString();
  }
Exemple #27
0
  /*
   * public ArrayList<com.application.baatna.bean.User> usersToBeRated(int
   * userId) {
   *
   * Session session=null;
   * ArrayList<com.application.baatna.bean.User>users=null; try { session =
   * DBUtil.getSessionFactory().openSession(); Transaction transaction =
   * session.beginTransaction();
   *
   * users= new ArrayList<com.application.baatna.bean.User>(); String sql =
   * "SELECT * FROM USER WHERE USERID IN (SELECT USER_TWO_ID FROM USERWISH WHERE USERID= :userId AND WISH_STATUS= :status)"
   * ; SQLQuery query = session.createSQLQuery(sql);
   * query.addEntity(com.application.baatna.bean.User.class);
   * query.setParameter("userId", userId); query.setParameter("status",
   * CommonLib.STATUS_ACCEPTED);
   *
   *
   * java.util.List results = (java.util.List) query.list(); UserDAO dao= new
   * UserDAO(); for (Iterator iterator = ((java.util.List)
   * results).iterator(); iterator.hasNext();) {
   * users.add((com.application.baatna.bean.User)iterator.next()); }
   *
   * String sql2=
   * "SELECT * FROM USER WHERE USERID IN (SELECT USERID FROM USERWISH WHERE USER_TWO_ID= :userIdone AND WISH_STATUS= :statusone)"
   * ; SQLQuery query2=session.createSQLQuery(sql2);
   * query2.addEntity(com.application.baatna.bean.User.class);
   * query2.setParameter("userIdone",userId);
   * query2.setParameter("statusone",CommonLib.STATUS_ACCEPTED);
   *
   * java.util.List results2=(java.util.List)query2.list(); for (Iterator
   * iterator = ((java.util.List) results2).iterator(); iterator.hasNext();) {
   * users.add((com.application.baatna.bean.User)iterator.next()); }
   * transaction.commit(); session.close(); }catch (HibernateException e) {
   * System.out.println(e.getMessage()); System.out.println("error"); }
   * finally { if (session != null && session.isOpen()) session.close(); }
   *
   * return users; }
   */
  public JSONArray usersToBeRated(int userId) {
    Session session = null;
    JSONArray usersJson = new JSONArray();
    ArrayList<com.application.baatna.bean.User> users = null;
    try {
      session = DBUtil.getSessionFactory().openSession();
      Transaction transaction = session.beginTransaction();

      {
        String sql =
            "SELECT * FROM USERWISH WHERE USERID=:userId AND WISH_STATUS= :status AND U1RATEDU2= :zero_rating";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(com.application.baatna.bean.UserWish.class);
        query.setParameter("userId", userId);
        query.setParameter("status", CommonLib.STATUS_FULLFILLED);
        query.setParameter("zero_rating", 0);

        java.util.List results = (java.util.List) query.list();
        for (Iterator iterator = ((java.util.List) results).iterator(); iterator.hasNext(); ) {
          User user = null;
          Wish wish = null;
          UserWish userWish = (UserWish) iterator.next();
          String sql2 = "SELECT * FROM USER WHERE USERID= :userId";
          SQLQuery query2 = session.createSQLQuery(sql2);
          query2.addEntity(User.class);
          query2.setParameter("userId", userWish.getUserTwoId());

          java.util.List results2 = (java.util.List) query2.list();
          for (Iterator iterator2 = ((java.util.List) results2).iterator(); iterator2.hasNext(); ) {
            user = (User) iterator2.next();
            break;
          }

          String sql3 = "SELECT * FROM WISH WHERE USERID= :userId AND WISHID= :wishId";
          SQLQuery query3 = session.createSQLQuery(sql3);
          query3.addEntity(Wish.class);
          query3.setParameter("userId", userWish.getUserId());
          query3.setParameter("wishId", userWish.getWishId());

          java.util.List results3 = (java.util.List) query3.list();
          for (Iterator iterator3 = ((java.util.List) results3).iterator(); iterator3.hasNext(); ) {
            wish = (Wish) iterator3.next();
            break;
          }

          try {
            if (user != null && wish != null) {
              JSONObject userWishJson = JsonUtil.getUserWishJson(user, wish);
              usersJson.put(userWishJson);
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
      {
        String sql =
            "SELECT * FROM USERWISH WHERE USER_TWO_ID=:userId AND WISH_STATUS= :status AND U2RATEDU1= :zero_rating";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(com.application.baatna.bean.UserWish.class);
        query.setParameter("userId", userId);
        query.setParameter("status", CommonLib.STATUS_FULLFILLED);
        query.setParameter("zero_rating", 0);

        java.util.List results = (java.util.List) query.list();
        for (Iterator iterator = ((java.util.List) results).iterator(); iterator.hasNext(); ) {
          User user = null;
          Wish wish = null;
          UserWish userWish = (UserWish) iterator.next();
          String sql2 = "SELECT * FROM USER WHERE USERID= :userId";
          SQLQuery query2 = session.createSQLQuery(sql2);
          query2.addEntity(User.class);
          query2.setParameter("userId", userWish.getUserId());

          java.util.List results2 = (java.util.List) query2.list();
          for (Iterator iterator2 = ((java.util.List) results2).iterator(); iterator2.hasNext(); ) {
            user = (User) iterator2.next();
            break;
          }

          String sql3 = "SELECT * FROM WISH WHERE USERID= :userId AND WISHID= :wishId";
          SQLQuery query3 = session.createSQLQuery(sql3);
          query3.addEntity(Wish.class);
          query3.setParameter("userId", userWish.getUserId());
          query3.setParameter("wishId", userWish.getWishId());

          java.util.List results3 = (java.util.List) query3.list();
          for (Iterator iterator3 = ((java.util.List) results3).iterator(); iterator3.hasNext(); ) {
            wish = (Wish) iterator3.next();
            break;
          }

          try {
            if (user != null && wish != null) {
              JSONObject userWishJson = JsonUtil.getUserWishJson(user, wish);
              usersJson.put(userWishJson);
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }

    } catch (HibernateException e) {
      System.out.println(e.getMessage());
      System.out.println("error");
      e.printStackTrace();

    } finally {
      if (session != null && session.isOpen()) session.close();
    }
    return usersJson;
  }
Exemple #28
0
  @Path("/read/{ObjID}/{ObjInsId}/{resourceId}")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response sendRead(
      @PathParam("ObjID") Integer objectId,
      @PathParam("ObjInsId") Integer objectInstanceId,
      @PathParam("resourceId") Integer resourceID,
      @QueryParam("ep") String endPoint)
      throws Exception {
    String directory =
        "{"
            + "\"operation\":\"read\""
            + ","
            + "\""
            + "directory\":"
            + "\""
            + objectId
            + "/"
            + objectInstanceId
            + "/"
            + resourceID
            + "\"}";
    Info.setInfo(endPoint, directory);
    CountDownLatch signal = Info.getCountDown(endPoint);
    if (signal == null) {
      return Response.status(200).entity("Devices not registerd yet").build();
    }
    signal.countDown();

    CountDownLatch signalRead = new CountDownLatch(1);
    Info.setCountDownLatchMessageMap(endPoint, signalRead);
    signalRead.await();

    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class).filter("client_bs_obj.device_id =", endPoint).asList();

    JSONArray jsonArray = new JSONArray();
    if (objectInstanceId == 0) {

      Map<Date, Double> hashMap;
      hashMap =
          clientObjects
              .get(0)
              .getObjectMap()
              .get(objectId)
              .getObjInstanceMap()
              .get(objectInstanceId)
              .getResourceMap()
              .get(resourceID)
              .getValue();
      Map<Date, Double> sortedMap = new TreeMap<Date, Double>(hashMap);

      Iterator it = sortedMap.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        JSONArray jsonArray1 = new JSONArray();
        Date date = (Date) pair.getKey();
        jsonArray1.put(date.getTime()).put(pair.getValue());
        jsonArray.put(jsonArray1);
        it.remove(); // avoids a ConcurrentModificationException
      }
    } else if (objectInstanceId == 1) {

      Map<Date, Integer> hashMap;
      hashMap =
          clientObjects
              .get(0)
              .getObjectMap()
              .get(objectId)
              .getObjInstanceMap()
              .get(objectInstanceId)
              .getResourceMap()
              .get(resourceID)
              .getMvalue();
      Map<Date, Integer> sortedMap = new TreeMap<Date, Integer>(hashMap);
      Iterator it = sortedMap.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        JSONArray jsonArray1 = new JSONArray();
        Date date = (Date) pair.getKey();

        jsonArray1.put(date.getTime()).put(pair.getValue());
        jsonArray.put(jsonArray1);
        it.remove(); // avoids a ConcurrentModificationException
      }
    }

    return Response.status(200).entity(jsonArray.toString()).build();
  }
  @Override
  public String getSchemaJSON() {
    if (!changed && schemaJSON != null) {
      // If there are no changes, return the pre computed JSON
      return schemaJSON;
    }

    if (changedSchemaKeys) {
      // If the schema keys change, recompute the schema keys portion of the JSON
      changedSchemaKeys = false;

      if (schemaKeys == null) {
        schema.remove(Schema.FIELD_SCHEMA_KEYS);
      } else {
        try {
          schema.put(Schema.FIELD_SCHEMA_KEYS, SchemaUtils.createJSONObject(schemaKeys));
        } catch (JSONException ex) {
          throw new RuntimeException(ex);
        }
      }
    }

    if (changedFromTo) {
      // If the from to times have changed then recompute the time portion of the schema.
      changedFromTo = false;
      Preconditions.checkState(
          !(from == null ^ to == null),
          "Either both from and to should be set or both should be not set.");

      if (from != null) {
        Preconditions.checkState(
            to >= from, "to {} must be greater than or equal to from {}.", to, from);
      }

      if (from == null) {
        time.remove(FIELD_TIME_FROM);
        time.remove(FIELD_TIME_TO);
      } else {
        try {
          time.put(FIELD_TIME_FROM, from);
          time.put(FIELD_TIME_TO, to);
        } catch (JSONException ex) {
          throw new RuntimeException(ex);
        }
      }
    }

    if (this.areEnumsUpdated) {
      // If the enums have been updated, recompute the key portion of the schema.
      for (int keyIndex = 0; keyIndex < keys.length(); keyIndex++) {
        JSONObject keyData;
        String name;

        try {
          keyData = keys.getJSONObject(keyIndex);
          name = keyData.getString(DimensionalConfigurationSchema.FIELD_KEYS_NAME);
        } catch (JSONException ex) {
          throw new RuntimeException(ex);
        }

        List<Object> enumVals = currentEnumVals.get(name);

        if (enumVals == null || enumVals.isEmpty()) {
          keyData.remove(DimensionalConfigurationSchema.FIELD_KEYS_ENUMVALUES);
          continue;
        }

        JSONArray newEnumValues = new JSONArray();

        for (Object enumVal : enumVals) {
          newEnumValues.put(enumVal);
        }

        try {
          keyData.put(DimensionalConfigurationSchema.FIELD_KEYS_ENUMVALUES, newEnumValues);
        } catch (JSONException ex) {
          throw new RuntimeException(ex);
        }
      }

      this.areEnumsUpdated = false;
    }

    // Rebuild the schema JSON string.
    schemaJSON = schema.toString();
    return schemaJSON;
  }
Exemple #30
0
  /**
   * This method allow to insert data to the data table.
   *
   * @param incomingData
   * @return
   * @throws Exception
   */
  @POST
  @Path("/insert")
  @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
  @Produces(MediaType.APPLICATION_JSON)
  public Response addData(String incomingData) throws Exception {

    String returnString = null;
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    SchemaPostgresDB dao = new SchemaPostgresDB();

    try {

      /*
       * We can create a new instance and it will accept a JSON string
       * By doing this, we can now access the data.
       */
      JSONObject data = new JSONObject(incomingData);
      System.out.println("jsonData: " + data.toString());

      /*
       * Example:
       * data.optString("stream");
       * The optString example above will also return data but if stream does not
       * exist, it will return a BLANK string.
       *
       * data.optString("stream", NULL);
       * You can add a second parameter, it will return NULL if stream does not
       * exist.
       */
      int http_code =
          dao.insertIntoData(
              data.optInt("stream"),
              data.optInt("page"),
              data.optString("content"),
              data.optInt("jumpToPage"),
              data.optInt("jumpToStream"),
              data.optString("desc"));

      if (http_code == 200) {
        /*
         * The put method allows you to add data to a JSONObject.
         * The first parameter is the KEY (no spaces)
         * The second parameter is the Value
         */
        jsonObject.put("HTTP_CODE", "200");
        jsonObject.put("MSG", "Item has been entered successfully");
        /*
         * When you are dealing with JSONArrays, the put method is used to add
         * JSONObjects into JSONArray.
         */
        returnString = jsonArray.put(jsonObject).toString();
      } else {
        return Response.status(500).entity("Unable to enter Item").build();
      }

      System.out.println("returnString: " + returnString);

    } catch (Exception e) {
      e.printStackTrace();
      return Response.status(500).entity("Server was not able to process your request").build();
    }

    return Response.ok(returnString).build();
  }