Пример #1
0
 public static Namelist fromJSONtoNamelist(JSONObject jsonObj) {
   logger.info("Convert json object to namelist...");
   if (jsonObj != null) {
     String name = jsonObj.getString("_name");
     String species = jsonObj.getString("_species");
     if (species == null) {
       JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata");
       if (metadataJSONObj != null) {
         species = metadataJSONObj.getString("species");
       }
     }
     int size = jsonObj.getInt("_size");
     JSONArray data =
         jsonObj.containsKey("_data")
             ? jsonObj.getJSONArray("_data")
             : jsonObj.getJSONArray("gaggle-data");
     String[] names = new String[data.size()];
     for (int i = 0; i < data.size(); i++) {
       logger.info("Data item: " + data.getString(i));
       names[i] = data.getString(i);
     }
     logger.info("Species: " + species + " Names: " + names);
     Namelist nl = new Namelist(name, species, names);
     return nl;
   }
   return null;
 }
  public JSONObject objectForTargetXPath(JSONObject object, String xpath) {
    System.out.println("objectForTargetXPath: " + object.getString("name") + " - " + xpath);

    if (xpath.startsWith("/")) {
      xpath = xpath.replaceFirst("/", "");
    }
    String[] tokens = xpath.split("/");
    if (tokens.length > 0) {
      log.debug("looking path:" + xpath + " in object:" + object);
      if (object.has("name")) {
        if (tokens[0].equals(object.getString("name"))) {
          if (tokens.length == 1) {
            return object;
          } else {
            String path = tokens[1];
            for (int i = 2; i < tokens.length; i++) {
              path += "/" + tokens[i];
            }

            if (path.startsWith("@")) {
              if (object.has("attributes")) {
                return this.objectForTargetXPath(object.getJSONArray("attributes"), path);
              }
            } else {
              if (object.has("children")) {
                return this.objectForTargetXPath(object.getJSONArray("children"), path);
              }
            }
          }
        }
      }
    }

    return null;
  }
  public JSONObject setFixedRecursive(JSONObject object, boolean fixed) {
    this.setFixed(object, fixed);
    if (object.has("attributes")) {
      this.setArrayFixed(object.getJSONArray("attributes"), fixed);
    }

    if (object.has("children")) {
      this.setArrayFixed(object.getJSONArray("children"), fixed);
    }

    return object;
  }
Пример #4
0
  public static ArrayList<String> getOnStartList() throws TalesException {
    load();

    ArrayList<String> list = new ArrayList<String>();

    if (json.has("onStart")) {
      for (int i = 0; i < json.getJSONArray("onStart").size(); i++) {
        list.add(json.getJSONArray("onStart").getString(i));
      }
    }

    return list;
  }
  public void setXPathMapping(String xpath, String type, JSONObject target, int index) {
    JSONArray mappings = target.getJSONArray("mappings");
    JSONObject mapping = null;

    target.remove("warning");

    if (index > -1) {
      mapping = mappings.getJSONObject(index);
      mapping.put("type", "xpath");
      mapping.put("value", xpath);
    } else {
      mapping = new JSONObject();
      mapping.put("type", "xpath");
      mapping.put("value", xpath);
      mappings.add(mapping);
    }

    if (mapping != null) {
      if (target.has("type") && type != null && type.length() > 0) {
        if (target.getString("type").equalsIgnoreCase("dateUnion")) {
          if (!type.equalsIgnoreCase("date")
              && !type.equalsIgnoreCase("dateTime")
              && !type.equalsIgnoreCase("dateUnion")) {
            target.element("warning", type);
          }
        } else if (!target.getString("type").equalsIgnoreCase(type)
            || (mappings.size() > 1 && !type.equalsIgnoreCase("string"))) {
          target.element("warning", type);
        }
      }
    }

    // mappings.clear();
  }
  /** Tests {@link ExternalResource#toJson()}. */
  @PrepareForTest(Hudson.class)
  @Test
  public void testToJson() {
    Hudson hudson = MockUtils.mockHudson();
    MockUtils.mockMetadataValueDescriptors(hudson);

    String name = "name";
    String description = "description";
    String id = "id";
    ExternalResource resource =
        new ExternalResource(name, description, id, true, new LinkedList<MetadataValue>());
    String me = "me";
    resource.setReserved(
        new StashInfo(
            StashInfo.StashType.INTERNAL, me, new Lease(Calendar.getInstance(), "iso"), "key"));
    TreeStructureUtil.addValue(resource, "value", "descript", "some", "path");

    JSONObject json = resource.toJson();
    assertEquals(name, json.getString(JsonUtils.NAME));
    assertEquals(id, json.getString(JSON_ATTR_ID));
    assertTrue(json.getBoolean(JSON_ATTR_ENABLED));
    assertTrue(json.getJSONObject(JSON_ATTR_LOCKED).isNullObject());
    JSONObject reserved = json.getJSONObject(JSON_ATTR_RESERVED);
    assertNotNull(reserved);
    assertEquals(StashInfo.StashType.INTERNAL.name(), reserved.getString(Constants.JSON_ATTR_TYPE));
    assertEquals(me, reserved.getString(Constants.JSON_ATTR_STASHED_BY));
    assertEquals(1, json.getJSONArray(JsonUtils.CHILDREN).size());
  }
Пример #7
0
  /**
   * 查询所有分组
   *
   * @return 分组列表
   */
  public static List<UserGroup> getGroup() {

    List<UserGroup> list = new ArrayList<UserGroup>();

    String url = GET_GROUP_URL.replace("ACCESS_TOKEN", WeixinUtil.getToken());

    JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null);
    if (null != jsonObject) {
      if (StringUtil.isNotEmpty(jsonObject.get("errcode")) && jsonObject.get("errcode") != "0") {
        log.error(
            "获取分组失败,errcode:"
                + jsonObject.getInt("errcode")
                + ",errmsg:"
                + jsonObject.getString("errmsg"));
      } else {
        JSONArray arr = jsonObject.getJSONArray("groups");
        for (int i = 0; i < arr.size(); i++) {
          UserGroup group = new UserGroup();
          group.setId(arr.getJSONObject(i).getString("id"));
          group.setName(arr.getJSONObject(i).getString("name"));
          group.setCount(arr.getJSONObject(i).getInt("count"));
          list.add(group);
        }
      }
    }
    return list;
  }
Пример #8
0
  public JSONArray getUserTimezoneHistory(
      UpdateInfo updateInfo, String api_key, OAuthConsumer consumer) throws Exception {
    long then = System.currentTimeMillis();
    String requestUrl = "http://api.bodymedia.com/v2/json/timezone?api_key=" + api_key;

    HttpGet request = new HttpGet(requestUrl);
    consumer.sign(request);
    HttpClient client = env.getHttpClient();
    enforceRateLimits(getRateDelay(updateInfo));
    HttpResponse response = client.execute(request);
    final int statusCode = response.getStatusLine().getStatusCode();
    final String reasonPhrase = response.getStatusLine().getReasonPhrase();
    if (statusCode == 200) {
      countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl);
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String json = responseHandler.handleResponse(response);
      JSONObject userInfo = JSONObject.fromObject(json);
      return userInfo.getJSONArray("timezones");
    } else {
      countFailedApiCall(
          updateInfo.apiKey,
          updateInfo.objectTypes,
          then,
          requestUrl,
          "",
          statusCode,
          reasonPhrase);
      throw new Exception(
          "Error: "
              + statusCode
              + " Unexpected error trying to bodymedia timezone for user "
              + updateInfo.apiKey.getGuestId());
    }
  }
Пример #9
0
  @Override
  public void updateConnectorData(UpdateInfo updateInfo) throws Exception {
    int retrievedItems = ITEMS_PER_PAGE;
    long lastUploadTime = getLastUploadTime(updateInfo);
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed =
          retrievePhotoHistory(updateInfo, lastUploadTime, System.currentTimeMillis(), page);

      if (!(feed.getString("stat").equalsIgnoreCase("ok"))) {
        String message = "n/a";
        if (feed.containsKey("message")) message = feed.getString("message");
        throw new Exception("There was an error calling the Flickr API: " + message);
      }

      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        if (photosWrapper.containsKey("photo")) {
          JSONArray photos = photosWrapper.getJSONArray("photo");
          retrievedItems = photos.size();
          apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
        } else break;
      } else break;
    }
  }
    @Override
    public synchronized boolean configure(StaplerRequest req, JSONObject formData)
        throws FormException {

      // The following codes are bad...
      // How to bind formData to List<Discriptor> ?

      if (nexusMap == null) {
        nexusMap = new HashMap<String, NexusDescriptor>();
      }

      try {
        JSONObject json = formData.getJSONObject("nexusList");
        nexusMap.clear();
        NexusDescriptor desc = parse(json);
        nexusMap.put(desc.getName(), desc);
      } catch (JSONException e) {
        try {
          JSONArray jsons = formData.getJSONArray("nexusList");
          nexusMap.clear();
          for (Object json : jsons) {
            NexusDescriptor desc = parse((JSONObject) json);
            nexusMap.put(desc.getName(), desc);
          }
        } catch (JSONException ee) {
          // exec in this path only if nexusList is empty.
        }
      }

      save();
      return super.configure(req, formData);
    }
Пример #11
0
  public void pick() throws IOException {
    while (true) {
      pickUrl =
          String.format(
              "http://web.im.baidu.com/pick?v=30&session=&source=22&type=23&flag=1&seq=%d&ack=%s&guid=%s",
              sequence, ack, guid);

      HttpGet getRequest = new HttpGet(pickUrl);
      HttpResponse pickRes = httpClient.execute(getRequest);
      String entityStr = EntityUtils.toString(pickRes.getEntity());
      System.out.println("Pick result:" + entityStr);
      EntityUtils.consume(pickRes.getEntity());

      JSONObject jsonObject = JSONObject.fromObject(entityStr);
      JSONObject content = jsonObject.getJSONObject("content");
      if (content != null && content.get("ack") != null) {
        ack = (String) content.get("ack");
        JSONArray fields = content.getJSONArray("fields");
        JSONObject o = fields.getJSONObject(0);
        String fromUser = (String) o.get("from");
        System.out.println("++++Message from: " + fromUser);
      }
      updateSequence();

      if (sequence > 4) {
        break;
      }
    }
  }
  /**
   * 删除存生成运行线时临时数据
   *
   * @param reqStr
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/deletePlanTrainInfoTemp", method = RequestMethod.DELETE)
  public Result deletePlanTrainInfoTemp(@RequestBody String reqStr) {
    Result result = new Result();
    logger.info("deletePlanTrainInfoTemp~~reqStr==" + reqStr);

    JSONObject reqObj = JSONObject.fromObject(reqStr);

    try {
      List<String> ids = null;
      ids = reqObj.getJSONArray("ids");
      //
      if (!ids.isEmpty()) {
        for (String id : ids) {
          planTrainInfoTempService.deletePlanTrainInFoTemp(id);
        }
      }

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      result.setCode(StaticCodeType.SYSTEM_ERROR.getCode());
      result.setMessage(StaticCodeType.SYSTEM_ERROR.getDescription());
    }

    return result;
  }
 @Function("public")
 public void doQuery(
     Context context, @Param(name = "from") String from, @Param(name = "to") String to) {
   try {
     Date start = new Date();
     Date end = new Date();
     if (from == null || to == null) {
       end = new Date();
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(end);
       calendar.add(Calendar.DATE, -1); // 得到前一天
       start = calendar.getTime();
     } else {
       SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy");
       start = fmt.parse(from);
       end = fmt.parse(to);
     }
     EucaConsoleMessage message = eucaAC.genVolumeReport(start, end);
     JSONObject object = (JSONObject) message.getData();
     JSONArray resluts = object.getJSONArray("reports");
     context.put("json", resluts);
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
   }
 }
  public JSONObject removeNode(String id) {
    JSONObject result = new JSONObject();
    JSONObject targetElement = this.elementCache.get(id);
    JSONObject parent = this.parentCache.get(id);

    JSONArray children = parent.getJSONArray("children");
    if (children != null && !children.isEmpty()) {
      int targetIndex = -1;
      int targetCount = 0;
      for (int i = 0; i < children.size(); i++) {
        JSONObject child = (JSONObject) children.get(i);
        if (child.getString("id").equals(id)) {
          targetIndex = i;
        }
      }

      if (targetIndex >= 0) {
        children.remove(targetIndex);
        this.elementCache.remove(id);
        this.parentCache.remove(id);
      }

      result = result.element("id", id);
    } else {
      result = result.element("error", "could not find target element");
    }

    this.saveMappings();

    return result;
  }
Пример #15
0
  @Override
  protected void updateConnectorDataHistory(UpdateInfo updateInfo)
      throws RateLimitReachedException, Exception {
    // taking care of resetting the data if things went wrong before
    if (!connectorUpdateService.isHistoryUpdateCompleted(updateInfo.apiKey, -1))
      apiDataService.eraseApiData(updateInfo.apiKey, -1);
    int retrievedItems = ITEMS_PER_PAGE;
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed = retrievePhotoHistory(updateInfo, 0, System.currentTimeMillis(), page);
      if (feed.has("stat")) {
        String stat = feed.getString("stat");
        if (stat.equalsIgnoreCase("fail")) {
          String message = feed.getString("message");
          throw new RuntimeException("Could not retrieve Flickr history: " + message);
        }
      }
      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        JSONArray photos = photosWrapper.getJSONArray("photo");
        retrievedItems = photos.size();
        apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
      } else break;
    }
  }
Пример #16
0
    /**
     * Parses the raw response from Google
     *
     * @param rawResponse The raw, unparsed response from Google
     * @return Returns the parsed response.
     */
    void parseResponse(String rawResponse, GoogleResponse googleResponse) {
        try {
            JSONObject json = JSONObject.fromObject(rawResponse);
            int status = json.getInt("status");

            if (status == 0) {
                JSONArray hypotheses = json.getJSONArray("hypotheses");

                for (int index = 0; index < hypotheses.size(); index++) {
                    JSONObject hypothese = (JSONObject) hypotheses.get(index);

                    if (hypothese.containsKey(CONFIDENCE)) {
                        googleResponse.setResponse(hypothese.getString("utterance"));
                        googleResponse.setConfidence(hypothese.getDouble(CONFIDENCE) + "");
                    } else {
                        googleResponse.getOtherPossibleResponses().add(hypothese.getString("utterance"));
                    }
                }
            } else {
                Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, "status: {0}", status);
            }
        } catch (JSONException e) {
            Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, e.getLocalizedMessage(), e);
        }
    }
Пример #17
0
  /**
   * Parses a JSONObject into its appropriate ViewVariable implementation
   *
   * @param obj
   * @return
   */
  private static AbstractViewVariable parseJSONRecursive(JSONObject obj) {

    if (obj == null || obj.isNullObject()) throw new NullArgumentException("obj");

    String type = obj.getString("type");
    if (type == null) throw new IllegalArgumentException("Object missing type " + obj);

    // Parse a SimpleAxis
    if (type.equals(SimpleAxis.TYPE_STRING)) {
      SimpleAxis axis =
          new SimpleAxis(
              attemptGetString(obj, "name"),
              attemptGetString(obj, "dataType"),
              attemptGetString(obj, "units"),
              null,
              null);

      JSONObject dimensionBounds = obj.getJSONObject("dimensionBounds");
      JSONObject valueBounds = obj.getJSONObject("valueBounds");

      if (dimensionBounds != null && !dimensionBounds.isNullObject()) {
        axis.setDimensionBounds(
            new SimpleBounds(dimensionBounds.getDouble("from"), dimensionBounds.getDouble("to")));
      }

      if (valueBounds != null && !valueBounds.isNullObject()) {
        axis.setValueBounds(
            new SimpleBounds(valueBounds.getDouble("from"), valueBounds.getDouble("to")));
      }

      return axis;

      // Parse a SimpleGrid
    } else if (type.equals(SimpleGrid.TYPE_STRING)) {
      JSONArray axes = obj.getJSONArray("axes");
      SimpleGrid grid =
          new SimpleGrid(
              attemptGetString(obj, "name"),
              attemptGetString(obj, "dataType"),
              attemptGetString(obj, "units"),
              null);
      List<AbstractViewVariable> childAxes = new ArrayList<>();

      for (int i = 0; i < axes.size(); i++) {
        AbstractViewVariable var = parseJSONRecursive(axes.getJSONObject(i));
        if (var != null) childAxes.add(var);
      }

      if (childAxes.size() > 0) {
        grid.setAxes(childAxes.toArray(new AbstractViewVariable[childAxes.size()]));
        return grid;
      } else {
        return null;
      }

    } else {
      throw new IllegalArgumentException("Unable to parse type " + type);
    }
  }
  public void removeMappings(JSONObject target, int index) {
    JSONArray mappings = target.getJSONArray("mappings");
    target.remove("warning");

    if (index > -1) {
      mappings.remove(index);
    }
  }
Пример #19
0
 public static String getZipcode(JSONObject data) {
   try {
     JSONArray results = data.getJSONArray("results");
     JSONObject address = results.getJSONObject(0);
     JSONArray address_components = address.getJSONArray("address_components");
     for (int i = 0; i < address_components.size(); i++) {
       JSONObject postal_code = address_components.getJSONObject(i);
       JSONArray types = postal_code.getJSONArray("types");
       if (types.getString(0).equals("postal_code")) {
         return (String) postal_code.get("long_name");
       }
     }
     return "0";
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
Пример #20
0
  @RequestMapping("/updateImageSort")
  public @ResponseBody Map<String, Object> updateImageSort(
      HttpServletRequest req, HttpServletResponse resp, @RequestParam("images") String images) {
    JSONObject jsonObject = JSONObject.fromObject(images);
    JSONArray jsonArray = jsonObject.getJSONArray("datas");
    List<Image> list = (List) JSONArray.toCollection(jsonArray, Image.class);

    return imageBo.updateImageSort(list);
  }
  @Override
  public void syncSharedConnectorSettings(
      final long apiKeyId, final SharedConnector sharedConnector) {
    JSONObject jsonSettings = new JSONObject();
    if (sharedConnector.filterJson != null)
      jsonSettings = JSONObject.fromObject(sharedConnector.filterJson);
    // get calendars, add new configs for new calendars...
    // we use the data in the connector settings, which have either just been synched (see
    // UpdateWorker's syncSettings)
    // or were synched  when the connector was last updated; in either cases, we know that the data
    // is up-to-date
    final GoogleCalendarConnectorSettings connectorSettings =
        (GoogleCalendarConnectorSettings) settingsService.getConnectorSettings(apiKeyId);
    final List<CalendarConfig> calendars = connectorSettings.calendars;

    JSONArray sharingSettingsCalendars = new JSONArray();
    if (jsonSettings.has("calendars"))
      sharingSettingsCalendars = jsonSettings.getJSONArray("calendars");
    there:
    for (CalendarConfig calendarConfig : calendars) {
      for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
        JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      JSONObject sharingConfig = new JSONObject();
      sharingConfig.accumulate("id", calendarConfig.id);
      sharingConfig.accumulate("summary", calendarConfig.summary);
      sharingConfig.accumulate("description", calendarConfig.description);
      sharingConfig.accumulate("shared", false);
      sharingSettingsCalendars.add(sharingConfig);
    }

    // and remove configs for deleted notebooks - leave others untouched
    JSONArray settingsToDelete = new JSONArray();
    there:
    for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
      JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
      for (CalendarConfig calendarConfig : calendars) {
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      settingsToDelete.add(sharingSettingsCalendar);
    }
    for (int i = 0; i < settingsToDelete.size(); i++) {
      JSONObject toDelete = settingsToDelete.getJSONObject(i);
      for (int j = 0; j < sharingSettingsCalendars.size(); j++) {
        if (sharingSettingsCalendars
            .getJSONObject(j)
            .getString("id")
            .equals(toDelete.getString("id"))) {
          sharingSettingsCalendars.remove(j);
        }
      }
    }
    jsonSettings.put("calendars", sharingSettingsCalendars);
    String toPersist = jsonSettings.toString();
    coachingService.setSharedConnectorFilter(sharedConnector.getId(), toPersist);
  }
Пример #22
0
 /**
  * 转化rangejson 去显示 getRangeStr(这里用一句话描述这个方法的作用)
  *
  * @param rangeJson
  * @return @return String @exception
  */
 public String getRangeStr(String rangeJson) {
   // try {
   String rangeStr = "";
   if (rangeJson != null) {
     JSONObject jsonObject = JSONObject.fromObject(rangeJson);
     if (jsonObject != null && jsonObject.get("users") != null) {
       JSONArray userArray = jsonObject.getJSONArray("users");
       for (int i = 0; i < userArray.size(); i++) {
         if (userArray.getJSONObject(i) != null) {
           if (!StringUtils.isEmpty(rangeStr)) rangeStr += ",";
           rangeStr += userArray.getJSONObject(i).getString("cname");
         }
       }
     }
     if (jsonObject != null && jsonObject.get("departments") != null) {
       JSONArray deptArray = jsonObject.getJSONArray("departments");
       for (int i = 0; i < deptArray.size(); i++) {
         if (deptArray.getJSONObject(i) != null) {
           if (!StringUtils.isEmpty(rangeStr)) rangeStr += ",";
           rangeStr += deptArray.getJSONObject(i).getString("deptName");
         }
       }
     }
     if (jsonObject != null && jsonObject.get("jobs") != null) {
       JSONArray jobsArray = jsonObject.getJSONArray("jobs");
       for (int i = 0; i < jobsArray.size(); i++) {
         if (jobsArray.getJSONObject(i) != null) {
           if (!StringUtils.isEmpty(rangeStr)) rangeStr += ",";
           rangeStr += jobsArray.getJSONObject(i).getString("cname");
         }
       }
     }
     if (jsonObject != null && jsonObject.get("roles") != null) {
       JSONArray rolesArray = jsonObject.getJSONArray("roles");
       for (int i = 0; i < rolesArray.size(); i++) {
         if (rolesArray.getJSONObject(i) != null) {
           if (!StringUtils.isEmpty(rangeStr)) rangeStr += ",";
           rangeStr += rolesArray.getJSONObject(i).getString("cname");
         }
       }
     }
   }
   return rangeStr;
 }
 private String getSleepGraph(JSONObject sleepStats) {
   JSONArray sleepGraphArray = sleepStats.getJSONArray("sleepGraph");
   StringBuilder bf = new StringBuilder();
   for (int i = 0; i < sleepGraphArray.size(); i++) {
     String phaseString = sleepGraphArray.getString(i);
     Phase phase = Enum.valueOf(Phase.class, phaseString);
     bf.append(String.valueOf(phase.ordinal()));
   }
   return bf.toString();
 }
  private ArrayList<AbstractFacet> extractStepFacets(final ApiData apiData) {
    ArrayList<AbstractFacet> facets = new ArrayList<AbstractFacet>();
    /* burnJson is a JSONArray that contains a seperate JSONArray and calorie counts for each day
     */
    JSONObject bodymediaResponse = JSONObject.fromObject(apiData.json);
    JSONArray daysArray = bodymediaResponse.getJSONArray("days");
    if (bodymediaResponse.has("lastSync")) {
      DateTime d =
          form.parseDateTime(bodymediaResponse.getJSONObject("lastSync").getString("dateTime"));

      // Get timezone map from UpdateInfo context
      TimezoneMap tzMap = (TimezoneMap) updateInfo.getContext("tzMap");

      // Insert lastSync into the updateInfo context so it's accessible to the updater
      updateInfo.setContext("lastSync", d);

      for (Object o : daysArray) {
        if (o instanceof JSONObject) {
          JSONObject day = (JSONObject) o;
          BodymediaStepsFacet steps = new BodymediaStepsFacet(apiData.updateInfo.apiKey.getId());
          super.extractCommonFacetData(steps, apiData);
          steps.totalSteps = day.getInt("totalSteps");
          steps.date = day.getString("date");
          steps.json = day.getString("hours");
          steps.lastSync = d.getMillis();

          DateTime date = formatter.parseDateTime(day.getString("date"));
          steps.date = dateFormatter.print(date.getMillis());
          if (tzMap != null) {
            // Create a LocalDate object which just captures the date without any
            // timezone assumptions
            LocalDate ld =
                new LocalDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth());
            // Use tzMap to convert date into a datetime with timezone information
            DateTime realDateStart = tzMap.getStartOfDate(ld);
            // Set the start and end times for the facet.  The start time is the leading midnight
            // of date according to BodyMedia's idea of what timezone you were in then.
            // Need to figure out what end should be...
            steps.start = realDateStart.getMillis();
            int minutesLength = 1440;
            steps.end = steps.start + DateTimeConstants.MILLIS_PER_MINUTE * minutesLength;
          } else {
            TimeZone timeZone =
                metadataService.getTimeZone(apiData.updateInfo.getGuestId(), date.getMillis());
            long fromMidnight = TimeUtils.fromMidnight(date.getMillis(), timeZone);
            long toMidnight = TimeUtils.toMidnight(date.getMillis(), timeZone);
            steps.start = fromMidnight;
            steps.end = toMidnight;
          }
          facets.add(steps);
        } else throw new JSONException("Days array is not a proper JSONObject");
      }
    }
    return facets;
  }
  private void clearAllMappings(JSONObject object) {
    JSONArray mappings = object.getJSONArray("mappings");
    mappings.clear();

    if (object.has("attributes")) {
      JSONArray attributes = object.getJSONArray("attributes");
      for (int i = 0; i < attributes.size(); i++) {
        JSONObject a = (JSONObject) attributes.get(i);
        clearAllMappings(a);
      }
    }

    if (object.has("children")) {
      JSONArray children = object.getJSONArray("children");
      for (int i = 0; i < children.size(); i++) {
        JSONObject a = (JSONObject) children.get(i);
        clearAllMappings(a);
      }
    }
  }
Пример #26
0
  public static ArrayList<DirListenerObj> getDirListenerList() throws TalesException {
    load();

    ArrayList<DirListenerObj> list = new ArrayList<DirListenerObj>();

    if (json.has("dirListener")) {
      for (int i = 0; i < json.getJSONArray("dirListener").size(); i++) {

        JSONObject jsonObj = json.getJSONArray("dirListener").getJSONObject(i);

        DirListenerObj obj = new DirListenerObj();
        obj.setDir(jsonObj.getString("dir"));
        obj.setExec(jsonObj.getString("exec"));
        obj.setIgnoreRegex(jsonObj.getString("ignoreRegex"));

        list.add(obj);
      }
    }

    return list;
  }
Пример #27
0
  /**
   * Get the formated address from the JSONObject. If the JSONObject is not the given format, the
   * method would probably throw a NullPointerException.
   *
   * @param data the JSONObject
   * @return the formatted address in the string format, null if the parsing fails.
   */
  public static String getFormattedAddress(JSONObject data) {
    try {
      JSONArray results = data.getJSONArray("results");

      JSONObject address = results.getJSONObject(0);
      String formatted_address = (String) address.get("formatted_address");
      return formatted_address;
    } catch (NullPointerException npe) {
      npe.printStackTrace();
    }
    return null;
  }
Пример #28
0
 /**
  * Private method helps to generate the location of the given JSONObject
  *
  * @param data the JSONObject
  * @return the viewport for parsing the bound, null if the parsing fails.
  */
 private static JSONObject getLocationObj(JSONObject data) {
   try {
     JSONArray results = data.getJSONArray("results");
     JSONObject address = results.getJSONObject(0);
     JSONObject geometry = (JSONObject) address.get("geometry");
     JSONObject location = (JSONObject) geometry.get("location");
     return location;
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
Пример #29
0
 /**
  * Private method helps to generate the viewport of the given JSONObject
  *
  * @param data the JSONObject
  * @return the viewport for parsing the bound, null if the parsing fails.
  */
 private static JSONObject getViewport(JSONObject data) {
   try {
     JSONArray results = data.getJSONArray("results");
     JSONObject address = results.getJSONObject(0);
     JSONObject geometry = (JSONObject) address.get("geometry");
     JSONObject viewport = (JSONObject) geometry.get("viewport");
     return viewport;
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
  public void setEnumerationValueMapping(JSONObject target, String value) {
    JSONArray mappings = target.getJSONArray("mappings");
    JSONObject mapping = null;

    mappings.clear();
    if (value != null && value.length() > 0) {
      mapping = new JSONObject();
      mapping.put("type", "constant");
      mapping.put("value", value);
      mappings.add(mapping);
    }
  }