Esempio n. 1
0
 /**
  * 格式化是否赞
  *
  * @param userId
  * @param gds
  * @throws XueWenServiceException
  */
 public JSONArray formateGroupDynamic(String userId, JSONArray gds) throws XueWenServiceException {
   List<String> ss = new ArrayList<String>();
   for (int i = 0; i < gds.size(); i++) {
     JSONObject gd = gds.getJSONObject(i);
     String sourceId = gd.getString("sourceId");
     ss.add(sourceId);
   }
   List<String> ps = praiseService.findBySourseListAndUserIdRspSourceId(ss, userId);
   if (ps != null && ps.size() > 0) {
     for (int i = 0; i < gds.size(); i++) {
       JSONObject gd = gds.getJSONObject(i);
       String sourceId = gd.getString("sourceId");
       if (ps.contains(sourceId)) {
         gd.put("islike", true);
       } else {
         gd.put("islike", false);
       }
     }
   } else {
     for (int i = 0; i < gds.size(); i++) {
       JSONObject gd = gds.getJSONObject(i);
       gd.put("islike", false);
     }
   }
   return gds;
 }
Esempio n. 2
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;
 }
Esempio n. 3
0
  /** 首页管理:插入或更新 */
  public void commit() {
    // Object[] arr = super.toJavaArr(info, FpageEvent.class);
    // FpageEvent[] events = castToFpageEvent(arr);

    JSONArray jsonArray = new JSONArray();
    jsonArray = jsonArray.fromObject(info);
    FpageEvent[] events = new FpageEvent[jsonArray.size()];
    if (jsonArray.size() > 0) {
      for (int i = 0; i < jsonArray.size(); i++) {
        events[i] = new FpageEvent();
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        events[i].setId(Long.parseLong(jsonObject.getString("id")));
        events[i].setWeight(jsonObject.getInt("weight"));
        events[i].setTitle(jsonObject.getString("title"));
        events[i].setDescription(jsonObject.getString("description"));
        events[i].setPublicationId(jsonObject.getLong("publicationId"));
        events[i].setIssueId(jsonObject.getLong("issueId"));
        events[i].setPageNo(jsonObject.getInt("pageNo"));
        events[i].setEndPageNo(jsonObject.getInt("endPageNo"));
        events[i].setImgFile(jsonObject.getString("imgFile"));
        events[i].setWidth(Float.parseFloat(jsonObject.getString("width")));
        events[i].setHeight(Float.parseFloat(jsonObject.getString("height")));
        events[i].setStatus(jsonObject.getInt("status"));
        events[i].setIsPubCover(jsonObject.getInt("isPubCover"));
        events[i].setIsRecommend(jsonObject.getInt("isRecommend"));
        events[i].setIsSuitMobile(jsonObject.getInt("isSuitMobile"));
      }
      this.fpageEventService.commit(events);
    }
  }
Esempio n. 4
0
 private List<Profile> newProfileList(JSONArray jsonArray) {
   List<Profile> profiles = new ArrayList<Profile>(jsonArray.size());
   for (int i = 0; i < jsonArray.size(); i++) {
     profiles.add(new Profile(jsonArray.getJSONObject(i)));
   }
   return profiles;
 }
Esempio n. 5
0
 private List<Cloud> newCloudList(JSONArray jsonArray) {
   List<Cloud> clouds = new ArrayList<Cloud>(jsonArray.size());
   for (int i = 0; i < jsonArray.size(); i++) {
     clouds.add(new Cloud(jsonArray.getJSONObject(i)));
   }
   return clouds;
 }
Esempio n. 6
0
 private List<Encoding> newEncodingList(JSONArray jsonArray) {
   List<Encoding> encodings = new ArrayList<Encoding>(jsonArray.size());
   for (int i = 0; i < jsonArray.size(); i++) {
     encodings.add(new Encoding(jsonArray.getJSONObject(i)));
   }
   return encodings;
 }
Esempio n. 7
0
 private List<Video> newVideoList(JSONArray jsonArray) {
   List<Video> videos = new ArrayList<Video>(jsonArray.size());
   for (int i = 0; i < jsonArray.size(); i++) {
     videos.add(new Video(jsonArray.getJSONObject(i)));
   }
   return videos;
 }
Esempio n. 8
0
 @SuppressWarnings("unchecked")
 public static String formXML(JSONArray array, boolean success) {
   StringBuilder sb = new StringBuilder();
   sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
   sb.append("<results>\n");
   sb.append("<success>" + success + "</success>\n");
   sb.append("<total>" + array.size() + "</total>\n");
   sb.append("<rows>");
   JSONObject object = null;
   for (int i = 0; i < array.size(); i++) {
     object = array.getJSONObject(i);
     Iterator<String> o = object.keys();
     sb.append("<unit>\n");
     for (; o.hasNext(); ) {
       String temp = o.next();
       sb.append("<" + temp + ">");
       sb.append(object.getString(temp));
       sb.append("</" + temp + ">\n");
     }
     sb.append("</unit>\n");
   }
   sb.append("</rows>\n");
   sb.append("</results>");
   if (object != null) {
     object.clear();
     object = null;
   }
   return sb.toString();
 }
Esempio n. 9
0
 public static String[] json2StringArray(String jsonString) {
   JSONArray jsonArray = JSONArray.fromObject(jsonString);
   String[] stringArray = new String[jsonArray.size()];
   for (int i = 0; i < jsonArray.size(); i++) {
     stringArray[i] = jsonArray.getString(i);
   }
   return stringArray;
 }
Esempio n. 10
0
 public static Double[] json2DoubleArray(String jsonString) {
   JSONArray jsonArray = JSONArray.fromObject(jsonString);
   Double[] doubleArray = new Double[jsonArray.size()];
   for (int i = 0; i < jsonArray.size(); i++) {
     doubleArray[i] = jsonArray.getDouble(i);
   }
   return doubleArray;
 }
Esempio n. 11
0
 public static Long[] json2LongArray(String jsonString) {
   JSONArray jsonArray = JSONArray.fromObject(jsonString);
   Long[] longArray = new Long[jsonArray.size()];
   for (int i = 0; i < jsonArray.size(); i++) {
     longArray[i] = jsonArray.getLong(i);
   }
   return longArray;
 }
Esempio n. 12
0
 public static Integer[] json2IntegerArray(String jsonString) {
   JSONArray jsonArray = JSONArray.fromObject(jsonString);
   Integer[] integerArray = new Integer[jsonArray.size()];
   for (int i = 0; i < jsonArray.size(); i++) {
     integerArray[i] = jsonArray.getInt(i);
   }
   return integerArray;
 }
Esempio n. 13
0
  /**
   * 将微博内容放到数据库
   *
   * @param response
   * @param ac
   * @return
   */
  private WeiboHandleResult weiboSaveDb(String response, SocialUserAccount ac, Integer weiboType) {
    WeiboHandleResult result = new WeiboHandleResult();
    JSONArray infoList = null;
    String ownerUserId = ac.getOwnUser();
    Object responseJsonObject = TencentSociaTool.getJsonDataObject(response);
    if (judgeNull(responseJsonObject) || ((JSONObject) responseJsonObject).get("info") == null) {
      result.setSuccess(false);
      return result;
    }
    infoList = ((JSONObject) responseJsonObject).getJSONArray("info");
    boolean sign = false;
    for (int i = 0; i < infoList.size(); i++) { // 没一条的微博
      JSONObject infoObj = infoList.getJSONObject(i);
      SocialUserWeibo dbWeibo = handlerNewSocialUserWeibo(ownerUserId, ac, infoObj, weiboType);
      logger.info(
          i
              + "+++timestamp:"
              + infoObj.getString("timestamp")
              + "++++++++++++++++"
              + "id:"
              + infoObj.getString("id"));
      if (i == 0) { //
        result.setPagetime(infoObj.getString("timestamp"));
        result.setLastid(infoObj.getString("id"));
      }
      String type = infoObj.getString("type");
      SocialUserWeibo soruceWeibo = null;
      JSONObject source = infoObj.getJSONObject("source");
      if (source != null && !(source.toString().equals("null"))) { // 有原帖内容
        soruceWeibo = handlerNewSocialUserWeibo(ownerUserId, ac, source, weiboType);
        soruceWeibo.setWeiboHandleType(1); // 表明为原始贴
        if (saveWeiboUserEntity(soruceWeibo)) { // 插入原帖id
          dbWeibo.setRetweetedId(soruceWeibo.getId());
        } else {
          SocialUserWeibo queryWeibo =
              socialUserWeiboService.queryByAccountAndWeiboId(
                  soruceWeibo.getUserAccountId(), soruceWeibo.getWeiboId());
          dbWeibo.setRetweetedId(queryWeibo.getId());
        }
      }

      if (type.equals("7")) { // 7-评论
        dbWeibo.setWeiboHandleType(2); // 表明为品论贴
        SocialUserWeiboComment comment = tranlateWeiboToComment(dbWeibo, soruceWeibo, weiboType);
        initWeiboCommentByAccount(comment, ac);
        socialUserWeiboCommentService.createSocialUserWeiboComment(comment);
      }

      // 插进本帖
      saveWeiboUserEntity(dbWeibo);
    }
    if (infoList != null) { // 记录数
      result.setInfoSize(infoList.size());
    }
    result.setSuccess(true);
    return result;
  }
  @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);
  }
Esempio n. 15
0
  public void executeQuery(String query, int pageSize, String index, String docType, int docLimit) {

    Search search =
        new Search.Builder(query)
            .addIndex(index)
            .addType(docType)
            .setParameter(Parameters.SEARCH_TYPE, SearchType.SCAN)
            .setParameter(Parameters.SIZE, pageSize)
            .setParameter(Parameters.SCROLL, SCROLL)
            .build();
    System.out.println(query + "$$$$");

    try {

      JestResult searchResult = client.execute(search);
      // System.out.println(searchResult.getJsonString());
      String scrollId = searchResult.getJsonObject().get("_scroll_id").getAsString();

      int currentResultSize = 0;
      int numDocs = 0;

      do {
        JSONArray jArrayResult = new JSONArray();

        SearchScroll scrollRequest =
            new SearchScroll.Builder(scrollId, SCROLL)
                .setParameter(Parameters.SIZE, pageSize)
                .build();

        JestResult scrollResult = client.execute(scrollRequest);
        scrollId = scrollResult.getJsonObject().get("_scroll_id").getAsString();

        JSONObject jObj = (JSONObject) JSONSerializer.toJSON(scrollResult.getJsonString());

        JSONArray jArrayHits = jObj.getJSONObject("hits").getJSONArray("hits");

        for (int i = 0; i < jArrayHits.size(); i++) {

          jArrayResult.add(extractTika(jArrayHits.getString(i)).toString());
        }
        writeToFile(jArrayResult);
        // Note: Current result size will be Page Size * number of shards
        currentResultSize = jArrayHits.size();
        numDocs += currentResultSize;
        System.out.println("num docs:" + String.valueOf(numDocs));
        if (docLimit != -1 && numDocs >= docLimit) {
          break;
        }
      } while (currentResultSize != 0);

    } catch (IOException e) {
      LOG.error("Error retrieving from Elasticsearch", e);
    }
  }
Esempio n. 16
0
  /**
   * 从json数组中解析出java Date 型对象数组,使用本方法必须保�?
   *
   * @param jsonString
   * @return
   * @throws ParseException
   */
  public static Date[] getDateArray4Json(String jsonString, String dataFormat)
      throws ParseException {

    JSONArray jsonArray = JSONArray.fromObject(jsonString);
    Date[] dateArray = new Date[jsonArray.size()];
    String dateString;
    Date date;

    for (int i = 0; i < jsonArray.size(); i++) {
      dateString = jsonArray.getString(i);
      date = FormatUtil.stringToDate(dateString, dataFormat);
      dateArray[i] = date;
    }
    return dateArray;
  }
Esempio n. 17
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;
    }
  }
Esempio n. 18
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;
    }
  }
Esempio n. 19
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);
        }
    }
 /**
  * Queries gerrit for the files included in this patch set.
  *
  * @param gerritQueryHandler the query handler, responsible for the queries to gerrit.
  * @return a list of files that are part of this patch set.
  */
 public List<String> getFiles(GerritQueryHandler gerritQueryHandler) {
   if (files == null) {
     files = new LinkedList<String>();
     try {
       List<JSONObject> jsonList = gerritQueryHandler.queryFiles("change:" + getChange().getId());
       for (JSONObject json : jsonList) {
         if (json.has("type") && "stats".equalsIgnoreCase(json.getString("type"))) {
           continue;
         }
         if (json.has("currentPatchSet")) {
           JSONObject currentPatchSet = json.getJSONObject("currentPatchSet");
           if (currentPatchSet.has("files")) {
             JSONArray changedFiles = currentPatchSet.optJSONArray("files");
             for (int i = 0; i < changedFiles.size(); i++) {
               JSONObject file = changedFiles.getJSONObject(i);
               files.add(file.getString("file"));
             }
           }
         }
       }
     } catch (IOException e) {
       logger.error("IOException occured. ", e);
     } catch (GerritQueryException e) {
       logger.error("Bad query. ", e);
     }
   }
   return files;
 }
Esempio n. 21
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    int userId =
        request.getParameter("userId") == null
            ? MyConst.USERID_DEFAULT
            : Integer.parseInt(request.getParameter("userId"));
    int projectId =
        request.getParameter("scenerySpotId") == null
            ? 1
            : Integer.parseInt(request.getParameter("scenerySpotId"));
    SignatureDao dao = new SignatureDao();
    List<Project> list = new ArrayList<Project>();
    list = dao.getMySignedProjects(userId, projectId);
    JSONArray array = JSONArray.fromObject(list);
    for (Project p : list) {
      System.out.print(p.getProjectId() + " ");
    }
    if (array.size() != 0) {
      out.print(array);
    }
    out.flush();
    out.close();
  }
  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();
  }
Esempio n. 23
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;
  }
  private static JSONArray[] getJSONArrayCache(
      JSONConvert jsonConvert,
      HttpServletRequest req,
      FindListHandler handler,
      List jsonAwareList) {
    int start = ServletRequestUtils.getIntParameter(req, "start", 0);
    int limit = ServletRequestUtils.getIntParameter(req, "limit", NUM_PER_PAGE);

    String sessionName = getPrefixPrivate();
    JSONArray jsonArray = null;
    if (start > 0) {
      jsonArray = (JSONArray) req.getSession().getAttribute(sessionName);
    }
    if (jsonArray == null) {
      log.info("取数据库数据"); // ////////////////
      jsonArray = jsonConvert.modelCollect2JSONArray(handler.findList(), jsonAwareList);
      req.getSession().setAttribute(sessionName, jsonArray);
    } else {
      log.info("命中缓存"); // ////////////////
    }

    if (start < 0) {
      start = 0;
    }
    JSONArray pageJSONArray = new JSONArray();
    for (int i = start; i <= start + limit - 1 && i < jsonArray.size(); i++) {
      pageJSONArray.add(jsonArray.get(i));
    }
    return new JSONArray[] {jsonArray, pageJSONArray};
  }
  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;
  }
Esempio n. 26
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);
    }
  }
Esempio n. 27
0
 public static Status derByJSONLib_intern(JSONArray arr) {
   Status ret = null;
   try {
     if (arr.size() >= 1) {
       ret = new Status(arr.getJSONObject(0));
       if (arr.size() == 2) {
         Status rt = new Status(arr.getJSONObject(1));
         ret.setRetweetedStatus(rt);
       }
     }
   } catch (JSONException | WeiboException e) {
     e.printStackTrace();
   } catch (weibo4j.WeiboException e) {
     e.printStackTrace();
   }
   return ret;
 }
Esempio n. 28
0
 public static Date[] json2DateArray(String jsonString, String DataFormat) {
   JSONArray jsonArray = JSONArray.fromObject(jsonString);
   Date[] dateArray = new Date[jsonArray.size()];
   String dateString;
   Date date = null;
   SimpleDateFormat sdf = new SimpleDateFormat(DataFormat);
   for (int i = 0; i < jsonArray.size(); i++) {
     dateString = jsonArray.getString(i);
     try {
       date = sdf.parse(dateString);
     } catch (ParseException e) {
       e.printStackTrace();
     }
     dateArray[i] = date;
   }
   return dateArray;
 }
Esempio n. 29
0
 @WebMethod
 public ModelAndView login(User user, String _site) {
   ModelAndView mv = new ModelAndView();
   String pwd = SecurityHelper.Md5(user.pwd);
   User po =
       dao.getUniqueByParams(
           User.class,
           new String[] {"account", "pwd", "_site"},
           new Object[] {user.account, pwd, _site});
   if (po == null) {
     throw new GException(PlatformExceptionType.BusinessException, "用户名或密码不正确。");
   }
   po.lasttime = new Date();
   dao.saveOrUpdate(po);
   ThreadSession.getHttpSession().setAttribute(MakesiteConstant.Session_Attr_User, po);
   List<Map> result =
       dao.listAsMap(
           "select ra.authId as authId from UserRole ur ,RoleAuth ra where ur.roleId=ra.roleId and ur.uid=?",
           po.id);
   StringBuilder authList = new StringBuilder("");
   for (Map map : result) {
     authList.append(map.get("authId").toString());
   }
   ThreadSession.getHttpSession()
       .setAttribute(MakesiteConstant.Session_Auth_List, authList.toString());
   String serverName = DataHelper.getServerName(ThreadSession.HttpServletRequest.get());
   if (!onlineUserCountMap.containsKey(serverName)) {
     onlineUserCountMap.put(serverName, 1);
   } else {
     onlineUserCountMap.put(serverName, onlineUserCountMap.get(serverName) + 1);
   }
   String text;
   try {
     text =
         FileUtils.readFileToString(
             new File(
                 ThreadSession.HttpServletRequest.get().getServletContext().getRealPath("/")
                     + File.separator
                     + "auths.json"),
             "utf8");
     JSONArray jarr = JSONArray.fromObject(text);
     List<String> urlList = new ArrayList<String>();
     for (int i = 0; i < jarr.size(); i++) {
       JSONObject jobj = jarr.getJSONObject(i);
       if (authList.toString().contains(jobj.getString("id"))) {
         continue;
       }
       String urls = jobj.getString("urls");
       for (String url : urls.split(",")) {
         urlList.add(url);
       }
     }
     ThreadSession.getHttpSession().setAttribute(MakesiteConstant.Session_Auth_Urls, urlList);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return mv;
 }
Esempio n. 30
0
  private Page<WeiboUser> getPagedWeiboUser(
      String url, OAuthTokenPair accessTokenPair, int page, int pageSize) {
    Map<String, String> additionalParams = new HashMap<String, String>();
    additionalParams.put("format", "json");
    additionalParams.put("reqnum", pageSize + "");
    additionalParams.put("startindex", (page - 1) * pageSize + "");

    WeiboResponse response = this.protocal.get(url, additionalParams, accessTokenPair);
    if (response.isStatusOK()) {
      try {
        JSONObject obj = JSONObject.fromObject(response.getHttpResponseText());
        JSONObject data = obj.getJSONObject("data");
        // 列表为空
        if (data != null && data.isNullObject() == false) {
          JSONArray arr = data.getJSONArray("info");
          Page<WeiboUser> pageUser = new Page<WeiboUser>(page, pageSize);
          List<WeiboUser> users = new ArrayList<WeiboUser>(arr.size());
          pageUser.setContent(users);

          for (int i = 0; i < arr.size(); i++) {
            JSONObject friend = arr.getJSONObject(i);

            WeiboUser weiboFriend = new WeiboUser(null);
            weiboFriend.setNickName(friend.getString("nick"));
            weiboFriend.setImgUrl(friend.getString("head") + "/180"); // 修正腾讯微博头像url无法访问
            weiboFriend.setUid(friend.getString("openid"));

            String name = friend.getString("name");
            weiboFriend.setProfileUrl("http://t.qq.com/" + name + "?preview");

            users.add(weiboFriend);
          }

          return pageUser;
        }
      } catch (Exception e) {
        response.setLocalError(e);
      }
    }

    if (response.isStatusOK() == false)
      log.error("error to fetch paged weibo user, resp: " + response);

    return null;
  }