Java Code Examples for com.eclipsesource.json.JsonValue#asObject()

The following examples show how to use com.eclipsesource.json.JsonValue#asObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FullClient.java    From Skype4J with Apache License 2.0 6 votes vote down vote up
@Override
public void loadAllContacts() throws ConnectionException {
    JsonObject object = Endpoints.GET_ALL_CONTACTS
            .open(this, getUsername(), "default")
            .as(JsonObject.class)
            .expect(200, "While loading contacts")
            .get();
    for (JsonValue value : object.get("contacts").asArray()) {
        JsonObject obj = value.asObject();
        if (obj.get("suggested") == null || !obj.get("suggested").asBoolean()) {
            if (!allContacts.containsKey(obj.get("id").asString())) {
                this.allContacts.put(obj.get("id").asString(), new ContactImpl(this, obj));
            }
        }
    }
}
 
Example 2
Source File: Wiki.java    From dungeon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initializes the Wiki. Build a map with all the See Also references until all the articles have been loaded, so it
 * is possible to check that these references are valid.
 */
private static void initialize() {
  // The field cannot be initialized in the field declaration as a comparison to null is used to determine whether or
  // not it has already been initialized.
  articleList = new ArrayList<>();
  Map<Article, Collection<String>> seeAlsoMap = new HashMap<>();
  String filename = ResourceNameResolver.resolveName(DungeonResource.WIKI);
  JsonObject wikiJsonObject = JsonObjectFactory.makeJsonObject(filename);
  for (JsonValue jsonValue : wikiJsonObject.get("articles").asArray()) {
    JsonObject jsonObject = jsonValue.asObject();
    Article article = new Article(jsonObject.get("title").asString(), jsonObject.get("content").asString());
    if (jsonObject.get("seeAlso") != null) {
      seeAlsoMap.put(article, new ArrayList<String>());
      for (JsonValue referenceJsonValue : jsonObject.get("seeAlso").asArray()) {
        seeAlsoMap.get(article).add(referenceJsonValue.asString());
      }
    }
    articleList.add(article);
  }
  // Validate the references and add them.
  addReferences(seeAlsoMap);
}
 
Example 3
Source File: BoxTask.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Gets any assignments for this task.
 * @return a list of assignments for this task.
 */
public List<BoxTaskAssignment.Info> getAssignments() {
    URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
    BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    int totalCount = responseJSON.get("total_count").asInt();
    List<BoxTaskAssignment.Info> assignments = new ArrayList<BoxTaskAssignment.Info>(totalCount);
    JsonArray entries = responseJSON.get("entries").asArray();
    for (JsonValue value : entries) {
        JsonObject assignmentJSON = value.asObject();
        BoxTaskAssignment assignment = new BoxTaskAssignment(this.getAPI(), assignmentJSON.get("id").asString());
        BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON);
        assignments.add(info);
    }

    return assignments;
}
 
Example 4
Source File: BoxSearch.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Searches all descendant folders using a given query and query parameters.
 * @param  offset is the starting position.
 * @param  limit the maximum number of items to return. The default is 30 and the maximum is 200.
 * @param  bsp containing query and advanced search capabilities.
 * @return a PartialCollection containing the search results.
 */
public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) {
    QueryStringBuilder builder = bsp.getQueryParameters()
            .appendParam("limit", limit)
            .appendParam("offset", offset);
    URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString());
    BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
    String totalCountString = responseJSON.get("total_count").toString();
    long fullSize = Double.valueOf(totalCountString).longValue();
    PartialCollection<BoxItem.Info> results = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);
    JsonArray jsonArray = responseJSON.get("entries").asArray();
    for (JsonValue value : jsonArray) {
        JsonObject jsonObject = value.asObject();
        BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);
        if (parsedItemInfo != null) {
            results.add(parsedItemInfo);
        }
    }
    return results;
}
 
Example 5
Source File: BoxWebHook.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals(JSON_KEY_TARGET)) {
            String targetType = value.asObject().get(JSON_KEY_TARGET_TYPE).asString();
            String targetId = value.asObject().get(JSON_KEY_TARGET_ID).asString();
            this.target = new Target(targetType, targetId);
        } else if (memberName.equals(JSON_KEY_TRIGGERS)) {
            this.triggers = new HashSet<Trigger>(
                    CollectionUtils.map(value.asArray().values(), JSON_VALUE_TO_TRIGGER)
            );
        } else if (memberName.equals(JSON_KEY_ADDRESS)) {
            this.address = new URL(value.asString());
        } else if (memberName.equals(JSON_KEY_CREATED_BY)) {
            JsonObject userJSON = value.asObject();
            if (this.createdBy == null) {
                String userID = userJSON.get(JSON_KEY_ID).asString();
                BoxUser user = new BoxUser(getAPI(), userID);
                this.createdBy = user.new Info(userJSON);
            } else {
                this.createdBy.update(userJSON);
            }
        } else if (memberName.equals("created_at")) {
            this.createdAt = BoxDateFormat.parse(value.asString());
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 6
Source File: BoxMetadataCascadePolicy.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
protected void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("owner_enterprise")) {
            JsonObject jsonObject = value.asObject();
            this.ownerEnterprise = new BoxEnterprise(jsonObject);
        } else if (memberName.equals("parent")) {
            JsonObject parentJSON = value.asObject();
            if (this.parent == null) {
                String parentID = parentJSON.get("id").asString();
                BoxFolder folder = new BoxFolder(getAPI(), parentID);
                this.parent = folder.new Info(parentJSON);
            } else {
                this.parent.update(parentJSON);
            }
        } else if (memberName.equals("scope")) {
            this.scope = value.asString();
        } else if (memberName.equals("templateKey")) {
            this.templateKey = value.asString();
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 7
Source File: OverviewTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
	JsonObject overview = client.getOverview();
	assertNotNull(overview.get("rtldongle"));
	JsonValue rtltestStatus = overview.get("rtltest");
	assertNotNull(rtltestStatus);
	JsonObject testStatus = rtltestStatus.asObject();
	assertNotNull("SUCCESS", testStatus.get("status"));
}
 
Example 8
Source File: Parsers.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Parse representations from a file object response.
 * @param jsonObject representations json object in get response for /files/file-id?fields=representations
 * @return list of representations
 */
public static List<Representation> parseRepresentations(JsonObject jsonObject) {
    List<Representation> representations = new ArrayList<Representation>();
    for (JsonValue representationJson : jsonObject.get("entries").asArray()) {
        Representation representation = new Representation(representationJson.asObject());
        representations.add(representation);
    }
    return representations;
}
 
Example 9
Source File: BoxCollaborationWhitelist.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
protected void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);

    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("domain")) {
            this.domain = value.asString();

        } else if (memberName.equals("type")) {
            this.type = value.asString();

        } else if (memberName.equals("direction")) {
            this.direction = WhitelistDirection.fromDirection(value.asString());

        } else if (memberName.equals("enterprise")) {
            JsonObject jsonObject = value.asObject();
            this.enterprise = new BoxEnterprise(jsonObject);

        } else if (memberName.equals("created_at")) {
            this.createdAt = BoxDateFormat.parse(value.asString());

        } else if (memberName.equals("modified_at")) {
            this.modifiedAt = BoxDateFormat.parse(value.asString());

        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 10
Source File: Settings.java    From java-disassembler with GNU General Public License v3.0 5 votes vote down vote up
private static JsonObject getNode(JsonObject parent, String nodeId) {
    final JsonValue nodeValue = parent.get(nodeId);
    if (nodeValue != null)
        return nodeValue.asObject();
    final JsonObject node = new JsonObject();
    parent.add(nodeId, node);
    return node;
}
 
Example 11
Source File: BoxComment.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
private void parseItem(JsonValue value) {
    JsonObject itemJSON = value.asObject();
    String itemType = itemJSON.get("type").asString();
    if (itemType.equals("file")) {
        this.updateItemAsFile(itemJSON);
    } else if (itemType.equals("comment")) {
        this.updateItemAsComment(itemJSON);
    }
}
 
Example 12
Source File: BoxLegalHoldAssignment.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("legal_hold_policy")) {
            JsonObject policyJSON = value.asObject();
            if (this.legalHold == null) {
                String policyID = policyJSON.get("id").asString();
                BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(getAPI(), policyID);
                this.legalHold = policy.new Info(policyJSON);
            } else {
                this.legalHold.update(policyJSON);
            }
        } else if (memberName.equals("assigned_to")) {
            JsonObject assignmentJSON = value.asObject();
            this.assignedToType = assignmentJSON.get("type").asString();
            this.assignedToID = assignmentJSON.get("id").asString();
        } else if (memberName.equals("assigned_by")) {
            JsonObject userJSON = value.asObject();
            if (this.assignedBy == null) {
                String userID = userJSON.get("id").asString();
                BoxUser user = new BoxUser(getAPI(), userID);
                this.assignedBy = user.new Info(userJSON);
            } else {
                this.assignedBy.update(userJSON);
            }
        } else if (memberName.equals("assigned_at")) {
            this.assignedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("deleted_at")) {
            this.deletedAt = BoxDateFormat.parse(value.asString());
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 13
Source File: BoxRetentionPolicyAssignment.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("retention_policy")) {
            JsonObject policyJSON = value.asObject();
            if (this.retentionPolicy == null) {
                String policyID = policyJSON.get("id").asString();
                BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID);
                this.retentionPolicy = policy.new Info(policyJSON);
            } else {
                this.retentionPolicy.update(policyJSON);
            }
        } else if (memberName.equals("assigned_to")) {
            JsonObject assignmentJSON = value.asObject();
            this.assignedToType = assignmentJSON.get("type").asString();
            if (this.assignedToType.equals(TYPE_ENTERPRISE)) {
                this.assignedToID = null;
            } else {
                this.assignedToID = assignmentJSON.get("id").asString();
            }
        } else if (memberName.equals("assigned_by")) {
            JsonObject userJSON = value.asObject();
            if (this.assignedBy == null) {
                String userID = userJSON.get("id").asString();
                BoxUser user = new BoxUser(getAPI(), userID);
                this.assignedBy = user.new Info(userJSON);
            } else {
                this.assignedBy.update(userJSON);
            }
        } else if (memberName.equals("assigned_at")) {
            this.assignedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("filter_fields")) {
            JsonArray jsonFilters = value.asArray();
            List<MetadataFieldFilter> filterFields = new ArrayList<MetadataFieldFilter>();
            for (int i = 0; i < jsonFilters.size(); i++) {
                filterFields.add(new MetadataFieldFilter(jsonFilters.get(i).asObject()));
            }
            this.filterFields = filterFields;
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 14
Source File: LocationPresetStore.java    From dungeon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void loadLocationPresets() {
  String filename = ResourceNameResolver.resolveName(DungeonResource.LOCATIONS);
  JsonObject jsonObject = JsonObjectFactory.makeJsonObject(filename);
  for (JsonValue jsonValue : jsonObject.get("locations").asArray()) {
    JsonObject presetObject = jsonValue.asObject();
    Id id = new Id(presetObject.get("id").asString());
    Type type = Type.valueOf(presetObject.get("type").asString());
    Name name = NameFactory.fromJsonObject(presetObject.get("name").asObject());
    LocationPreset preset = new LocationPreset(id, type, name);
    char symbol = presetObject.get("symbol").asString().charAt(0);
    preset.setDescription(new LocationDescription(symbol, colorFromJsonArray(presetObject.get("color").asArray())));
    preset.getDescription().setInfo(presetObject.get("info").asString());
    preset.setBlobSize(presetObject.get("blobSize").asInt());
    preset.setLightPermittivity(presetObject.get("lightPermittivity").asDouble());
    preset.setTagSet(new TagSetParser<>(Location.Tag.class, presetObject.get("tags")).parse());
    if (presetObject.get("spawners") != null) {
      for (JsonValue spawnerValue : presetObject.get("spawners").asArray()) {
        JsonObject spawner = spawnerValue.asObject();
        String spawnerId = spawner.get("id").asString();
        JsonObject population = spawner.get("population").asObject();
        int minimumPopulation = population.get("minimum").asInt();
        int maximumPopulation = population.get("maximum").asInt();
        int delay = spawner.get("delay").asInt();
        preset.addSpawner(new SpawnerPreset(spawnerId, minimumPopulation, maximumPopulation, delay));
      }
    }
    if (presetObject.get("items") != null) {
      for (JsonValue itemValue : presetObject.get("items").asArray()) {
        JsonObject item = itemValue.asObject();
        String itemId = item.get("id").asString();
        double probability = item.get("probability").asDouble();
        preset.addItem(itemId, probability);
      }
    }
    if (presetObject.get("blockedEntrances") != null) {
      for (JsonValue abbreviation : presetObject.get("blockedEntrances").asArray()) {
        preset.block(Direction.fromAbbreviation(abbreviation.asString()));
      }
    }
    addLocationPreset(preset);
  }
  DungeonLogger.info("Loaded " + getSize() + " location presets.");
}
 
Example 15
Source File: BoxLegalHoldPolicy.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);
    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("policy_name")) {
            this.policyName = value.asString();
        } else if (memberName.equals("description")) {
            this.description = value.asString();
        } else if (memberName.equals("status")) {
            this.status = value.asString();
        } else if (memberName.equals("release_notes")) {
            this.releaseNotes = value.asString();
        } else if (memberName.equals("assignment_counts")) {
            JsonObject countsJSON = value.asObject();
            this.assignmentCountUser = countsJSON.get("user").asInt();
            this.assignmentCountFolder = countsJSON.get("folder").asInt();
            this.assignmentCountFile = countsJSON.get("file").asInt();
            this.assignmentCountFileVersion = countsJSON.get("file_version").asInt();
        } else if (memberName.equals("created_by")) {
            JsonObject userJSON = value.asObject();
            if (this.createdBy == null) {
                String userID = userJSON.get("id").asString();
                BoxUser user = new BoxUser(getAPI(), userID);
                this.createdBy = user.new Info(userJSON);
            } else {
                this.createdBy.update(userJSON);
            }
        } else if (memberName.equals("created_at")) {
            this.createdAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("modified_at")) {
            this.modifiedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("deleted_at")) {
            this.deletedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("filter_started_at")) {
            this.filterStartedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("filter_ended_at")) {
            this.filterEndedAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("is_ongoing")) {
            this.isOngoing = value.asBoolean();
        }
    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example 16
Source File: BlockJson.java    From Cubes with MIT License 4 votes vote down vote up
@Override
public String[] parse(JsonValue prop) {
  String[] textures = new String[6];
  if (prop.isString()) {
    Arrays.fill(textures, prop.asString());
  } else {
    JsonObject texture = prop.asObject();
    for (JsonObject.Member member : texture) {
      String value = member.getValue().asString();
      switch (member.getName()) {
        case "posX":
          textures[BlockFace.posX.index] = value;
          break;
        case "negX":
          textures[BlockFace.negX.index] = value;
          break;
        case "posY":
        case "top":
          textures[BlockFace.posY.index] = value;
          break;
        case "negY":
        case "bottom":
          textures[BlockFace.negY.index] = value;
          break;
        case "posZ":
          textures[BlockFace.posZ.index] = value;
          break;
        case "negZ":
          textures[BlockFace.negZ.index] = value;
          break;
        case "side":
          textures[BlockFace.posX.index] = value;
          textures[BlockFace.negX.index] = value;
          textures[BlockFace.posZ.index] = value;
          textures[BlockFace.negZ.index] = value;
          break;
        case "other":
          for (int i = 0; i < textures.length; i++) {
            if (textures[i] == null) textures[i] = value;
          }
          break;
        default:
          throw new JsonException("Unexpected block texture member \"" + member.getName() + "\"");
      }
    }
  }
  return textures;
}
 
Example 17
Source File: AchievementStoreFactory.java    From dungeon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Loads all provided achievements into the provided AchievementStore.
 *
 * <p>Throws an IllegalStateException if the AchievementStore is not empty when this method is called
 */
private static void loadAchievements(AchievementStore store) {
  if (!store.getAchievements().isEmpty()) {
    throw new IllegalStateException("called loadAchievements on a not empty AchievementStore");
  }
  String filename = ResourceNameResolver.resolveName(DungeonResource.ACHIEVEMENTS);
  JsonObject jsonObject = JsonObjectFactory.makeJsonObject(filename);
  for (JsonValue achievementValue : jsonObject.get("achievements").asArray()) {
    JsonObject achievementObject = achievementValue.asObject();
    AchievementBuilder builder = new AchievementBuilder();
    builder.setId(achievementObject.get("id").asString());
    builder.setName(achievementObject.get("name").asString());
    builder.setInfo(achievementObject.get("info").asString());
    builder.setText(achievementObject.get("text").asString());
    JsonValue battleRequirements = achievementObject.get("battleRequirements");
    if (battleRequirements != null) {
      for (JsonValue requirementValue : battleRequirements.asArray()) {
        JsonObject requirementObject = requirementValue.asObject();
        JsonObject queryObject = requirementObject.get("query").asObject();
        BattleStatisticsQuery query = new BattleStatisticsQuery();
        JsonValue idValue = queryObject.get("id");
        if (idValue != null) {
          query.setId(new Id(idValue.asString()));
        }
        JsonValue typeValue = queryObject.get("type");
        if (typeValue != null) {
          query.setType(typeValue.asString());
        }
        JsonValue causeOfDeathValue = queryObject.get("causeOfDeath");
        if (causeOfDeathValue != null) {
          JsonObject causeOfDeathObject = causeOfDeathValue.asObject();
          TypeOfCauseOfDeath type = TypeOfCauseOfDeath.valueOf(causeOfDeathObject.get("type").asString());
          Id id = new Id(causeOfDeathObject.get("id").asString());
          query.setCauseOfDeath(new CauseOfDeath(type, id));
        }
        JsonValue partOfDayValue = queryObject.get("partOfDay");
        if (partOfDayValue != null) {
          query.setPartOfDay(PartOfDay.valueOf(partOfDayValue.asString()));
        }
        int count = requirementObject.get("count").asInt();
        BattleStatisticsRequirement requirement = new BattleStatisticsRequirement(query, count);
        builder.addBattleStatisticsRequirement(requirement);
      }
    }
    JsonValue explorationRequirements = achievementObject.get("explorationRequirements");
    if (explorationRequirements != null) {
      JsonValue killsByLocationId = explorationRequirements.asObject().get("killsByLocationID");
      if (killsByLocationId != null) {
        builder.setKillsByLocationId(idCounterMapFromJsonObject(killsByLocationId.asObject()));
      }
      JsonValue maximumNumberOfVisits = explorationRequirements.asObject().get("maximumNumberOfVisits");
      if (maximumNumberOfVisits != null) {
        builder.setMaximumNumberOfVisits(idCounterMapFromJsonObject(maximumNumberOfVisits.asObject()));
      }
      JsonValue visitedLocations = explorationRequirements.asObject().get("visitedLocations");
      if (visitedLocations != null) {
        builder.setVisitedLocations(idCounterMapFromJsonObject(visitedLocations.asObject()));
      }
      JsonValue discovery = explorationRequirements.asObject().get("discovery");
      if (discovery != null) {
        for (JsonValue value : discovery.asObject().get("parts").asArray()) {
          builder.addPartOfDayOfDiscovery(PartOfDay.valueOf(value.asString()));
        }
        builder.setDiscoveryCount(discovery.asObject().get("count").asInt());
      }
    }
    store.addAchievement(builder.createAchievement());
  }
  DungeonLogger.info("Loaded " + store.getAchievements().size() + " achievements.");
}
 
Example 18
Source File: ChatImpl.java    From Skype4J with Apache License 2.0 4 votes vote down vote up
@Override
public List<ChatMessage> loadMoreMessages(int amount) throws ConnectionException {
    JsonObject data;
    if (backwardLink == null) {
        if (syncState == null) {
            data = Endpoints.LOAD_MESSAGES
                    .open(getClient(), getIdentity(), amount)
                    .as(JsonObject.class)
                    .expect(200, "While loading messages")
                    .get();
        } else {
            return Collections.emptyList();
        }
    } else {
        Matcher matcher = SkypeImpl.PAGE_SIZE_PATTERN.matcher(this.backwardLink);
        //Matcher find appears to be doing nothing.
        matcher.find();
        String url = matcher.replaceAll("pageSize=" + amount);
        data =  Endpoints
                .custom(url, getClient())
                .header("RegistrationToken", getClient().getRegistrationToken())
                .as(JsonObject.class)
                .expect(200, "While loading messages")
                .get();
    }
    List<ChatMessage> messages = new ArrayList<>();

    for (JsonValue value : data.get("messages").asArray()) {
        try {
            JsonObject msg = value.asObject();
            if (msg.get("messagetype").asString().equals("RichText") || msg.get("messagetype").asString().equals("Text")) {
                UserImpl u = (UserImpl) MessageType.getUser(msg.get("from").asString(), this);
                Message message = Message.fromHtml(MessageType.stripMetadata(msg.get("content").asString()));
                if (msg.get("clientmessageid") != null) {
                    ChatMessage m = Factory.createMessage(this, u, msg.get("id").asString(),
                            msg.get("clientmessageid").asString(),
                            formatter.parse(msg.get("originalarrivaltime").asString()).getTime(), message
                            ,getClient());
                    this.messages.add(0, m);
                    u.insertMessage(m, 0);
                    messages.add(m);
                } else {
                    ChatMessageImpl chatMessage = (ChatMessageImpl) u.getMessageById(msg.get("skypeeditedid").asString());
                    if (chatMessage != null) {
                        chatMessage.edit0(message);
                    }
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    JsonObject metadata = data.get("_metadata").asObject();
    if (metadata.get("backwardLink") != null) {
        this.backwardLink = metadata.get("backwardLink").asString();
    } else {
        this.backwardLink = null;
    }
    this.syncState = metadata.get("syncState").asString();
    return messages;
}
 
Example 19
Source File: WeatherService.java    From whirlpool with Apache License 2.0 4 votes vote down vote up
@Override
protected void collectData(Gson gson, String user, List<String> subscriptions) {
    Map<String, String> subscriptionData = new HashMap<>();

    for (String cityState : subscriptions) {
        try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) {
            String url = WEATHER_URL_START;
            url += URLEncoder.encode(cityState, "UTF-8");
            url += WEATHER_URL_END;

            HttpUriRequest query = RequestBuilder.get()
                    .setUri(url)
                    .build();
            try (CloseableHttpResponse queryResponse = httpClient.execute(query)) {
                HttpEntity entity = queryResponse.getEntity();
                if (entity != null) {
                    String data = EntityUtils.toString(entity);
                    JsonObject jsonObject = JsonObject.readFrom(data);
                    if (jsonObject != null) {
                        JsonValue jsonValue = jsonObject.get("query");
                        if (!jsonValue.isNull()) {
                            jsonObject = jsonValue.asObject();
                            jsonValue  = jsonObject.get("results");
                            if (!jsonValue.isNull()) {
                                jsonObject = jsonValue.asObject();
                                jsonObject = jsonObject.get("channel").asObject();
                                jsonObject = jsonObject.get("item").asObject();
                                jsonObject = jsonObject.get("condition").asObject();
                                String weatherData = jsonObject.toString();
                                weatherData = weatherData.replaceAll("\\\\\"", "\"");
                                subscriptionData.put(cityState, weatherData);
                            } else {
                                subscriptionData.put(cityState, "{\"result\":\"notfound\"}");
                            }
                        }
                    } else {
                        subscriptionData.put(cityState, "{\"result\":\"notfound\"}");
                    }
                }
            }
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
        }
    }

    DataResponse response = new DataResponse();
    response.setType("WeatherResponse");
    response.setId(user);
    response.setResult(MessageConstants.SUCCESS);
    response.setSubscriptionData(subscriptionData);
    responseQueue.add(gson.toJson(response));
}
 
Example 20
Source File: ChatGroup.java    From Skype4J with Apache License 2.0 4 votes vote down vote up
public void load() throws ConnectionException, ChatNotFoundException {
    JsonObject object = Endpoints.CHAT_INFO_URL
            .open(getClient(), getIdentity())
            .as(JsonObject.class)
            .on(404, (connection) -> {
                throw new ChatNotFoundException();
            })
            .expect(200, "While loading users")
            .get();

    JsonObject props = object.get("properties").asObject();
    for (Option option : GroupChat.Option.values()) {
        if (props.get(option.getId()) != null && props.get(option.getId()).asString().equals("true")) {
            this.enabledOptions.add(option);
        }
    }
    if (props.get("topic") != null) {
        this.topic = props.get("topic").asString();
    } else {
        this.topic = "";
    }
    if (props.get("picture") != null) {
        this.pictureUrl = props.get("picture").asString().substring(4);
    }
    JsonArray members = object.get("members").asArray();
    for (JsonValue element : members) {
        String id = element.asObject().get("id").asString();
        String role = element.asObject().get("role").asString();
        ParticipantImpl user = Factory.createParticipant(getClient(), this, id);
        users.put(id.toLowerCase(), user);
        if (role.equalsIgnoreCase("admin")) {
            user.updateRole(Participant.Role.ADMIN);
        } else {
            user.updateRole(Participant.Role.USER);
        }
    }

    Map<String, UserImpl> toLoad = new HashMap<>();

    for (ParticipantImpl participant : this.users.values()) {
        if (participant instanceof UserImpl) {
            if (getClient().getContact(participant.getId()) != null) {
                ((UserImpl) participant).setInfo(getClient().getContact(participant.getId()));
            } else {
                toLoad.put(((UserImpl) participant).getUsername(), (UserImpl) participant);
            }
        } else if (participant instanceof BotImpl) {
            ((BotImpl) participant).setInfo(getClient().getOrLoadBotInfo(participant.getId()));
        }
    }

    while (!toLoad.isEmpty()) {
        Map<String, UserImpl> localToLoad = new HashMap<>();
        Iterator<Map.Entry<String, UserImpl>> it = toLoad.entrySet().iterator();
        while (localToLoad.size() < 100 && !toLoad.isEmpty()) {
            Map.Entry<String, UserImpl> ent = it.next();
            localToLoad.put(ent.getKey(), ent.getValue());
            it.remove();
        }

        JsonArray usernames = new JsonArray();
        localToLoad.keySet().forEach(usernames::add);

        JsonArray info = Endpoints.PROFILE_INFO
                .open(getClient())
                .expect(200, "While getting contact info")
                .as(JsonArray.class)
                .post(new JsonObject()
                        .add("usernames", usernames)
                );

        for (JsonValue jsonValue : info) {
            JsonObject data = jsonValue.asObject();

            UserImpl matching = localToLoad.get(data.get("username").asString());
            if (matching != null) {
                matching.setInfo(ContactImpl.createContact(getClient(), matching.getUsername(), data));
            }
        }
    }
}