Ejemplo n.º 1
0
  private void SetChatManager(JsonObject chat, JsonObject log) {
    List<Line> chatMessages = new ArrayList<Line>();
    List<Line> gameHistory = new ArrayList<Line>();
    // Get chat info
    {
      JsonArray lines = chat.getAsJsonArray("lines");
      for (int i = 0; i < lines.size(); i++) {
        JsonObject line = lines.get(i).getAsJsonObject();

        String message = line.getAsJsonPrimitive("message").getAsString();
        String source = line.getAsJsonPrimitive("source").getAsString();
        Line l = new Line(message, source);
        chatMessages.add(l);
      }
    }

    // Get log info
    {
      JsonArray lines = log.getAsJsonArray("lines");
      for (int i = 0; i < lines.size(); i++) {
        JsonObject line = lines.get(i).getAsJsonObject();

        String message = line.getAsJsonPrimitive("message").getAsString();
        String source = line.getAsJsonPrimitive("source").getAsString();
        Line l = new Line(message, source);
        gameHistory.add(l);
      }
    }
    this.chatManager = new ChatManager(chatMessages, gameHistory);
  }
Ejemplo n.º 2
0
  public void load() throws IOException {
    File file = getFile();
    if (file.exists()) {
      JsonObject rootObject = JSON_PARSER.parse(new FileReader(file)).getAsJsonObject();

      for (JsonElement element : rootObject.getAsJsonArray("players")) {
        Player player = new Player(element.getAsJsonObject());
        playerDB.put(player.getName(), player);
      }

      for (JsonElement element : rootObject.getAsJsonArray("groups")) {
        Group group = new Group(element.getAsJsonObject());
        groupDB.put(group.getName(), group);
      }
    } else {
      //noinspection ResultOfMethodCallIgnored
      file.createNewFile();
      JsonObject rootObject = new JsonObject();
      rootObject.add("players", new JsonArray());
      rootObject.add("groups", new JsonArray());
      BufferedWriter bw = new BufferedWriter(new FileWriter(file));
      bw.write(GSON.toJson(rootObject));
      bw.close();
    }
  }
  @Override
  public JsonObject upgrade(
      JsonObject agentUnitConfig,
      Map<File, JsonObject> dbSnapshot,
      Map<String, Map<File, DatabaseEntryDescriptor>> globalDbSnapshots)
      throws CouldNotPerformException {
    if (unitScopeIdMap.isEmpty()) {
      globalDbSnapshots
          .get(DAL_UNIT_CONFIG_DB_ID)
          .values()
          .stream()
          .map((dalUnitConfigDesriptor) -> dalUnitConfigDesriptor.getEntry())
          .filter(
              (dalUnitConfig) -> !(!dalUnitConfig.has(ID_FIELD) || !dalUnitConfig.has(SCOPE_FIELD)))
          .forEach(
              (dalUnitConfig) -> {
                String id = dalUnitConfig.get(ID_FIELD).getAsString();
                JsonObject scope = dalUnitConfig.getAsJsonObject(SCOPE_FIELD);
                if (!(!scope.has(COMPONENT_FIELD))) {
                  JsonArray scopeComponents = scope.getAsJsonArray(COMPONENT_FIELD);
                  String scopeAsString = "/";
                  for (JsonElement component : scopeComponents) {
                    scopeAsString += component.getAsString() + "/";
                  }

                  unitScopeIdMap.put(scopeAsString, id);
                }
              });
    }

    boolean isPowerStateSynchroniserAgent = false;
    boolean isAmbientColorAgent = false;
    if (agentUnitConfig.has(LABEL_FIELD)) {
      String label = agentUnitConfig.get(LABEL_FIELD).getAsString();
      if (label.contains(POWER_STATE_SYNCHRONISER_IDENTIFIER)) {
        isPowerStateSynchroniserAgent = true;
      } else if (label.contains(AMBIENT_COLOR_AGENT_IDE_AGENT_IDENTIFIER)) {
        isAmbientColorAgent = true;
      }
    }

    if (isPowerStateSynchroniserAgent || isAmbientColorAgent) {
      if (agentUnitConfig.has(META_CONFIG_FIELD)) {
        JsonObject metaConfig = agentUnitConfig.getAsJsonObject(META_CONFIG_FIELD);
        if (metaConfig.has(ENTRY_FIELD)) {
          JsonArray metaConfigEntries = metaConfig.getAsJsonArray(ENTRY_FIELD);

          if (isPowerStateSynchroniserAgent) {
            updatePowerStateSynchroniserAgentMetaConfig(
                metaConfigEntries, globalDbSnapshots.get(DAL_UNIT_CONFIG_DB_ID));
          } else if (isAmbientColorAgent) {
            updateAmbientColorAgentMetaConfig(
                metaConfigEntries, globalDbSnapshots.get(DAL_UNIT_CONFIG_DB_ID));
          }
        }
      }
    }

    return agentUnitConfig;
  }
  private static View readView(JsonObject json, TextAnnotation ta) throws Exception {

    String viewClass = readString("viewType", json);

    String viewName = readString("viewName", json);

    String viewGenerator = readString("generator", json);

    double score = 0;
    if (json.has("score")) score = readDouble("score", json);

    View view = createEmptyView(ta, viewClass, viewName, viewGenerator, score);

    List<Constituent> constituents = new ArrayList<>();

    if (json.has("constituents")) {

      JsonArray cJson = json.getAsJsonArray("constituents");

      for (int i = 0; i < cJson.size(); i++) {
        JsonObject cJ = (JsonObject) cJson.get(i);
        Constituent c = readConstituent(cJ, ta, viewName);
        constituents.add(c);
        view.addConstituent(c);
      }
    }

    if (json.has("relations")) {
      JsonArray rJson = json.getAsJsonArray("relations");
      for (int i = 0; i < rJson.size(); i++) {
        JsonObject rJ = (JsonObject) rJson.get(i);

        String name = readString("relationName", rJ);

        double s = 0;
        if (rJ.has("score")) s = readDouble("score", rJ);

        int src = readInt("srcConstituent", rJ);
        int tgt = readInt("targetConstituent", rJ);

        Map<String, Double> labelsToScores = null;
        if (rJ.has(LABEL_SCORE_MAP)) {
          labelsToScores = new HashMap<>();
          readLabelsToScores(labelsToScores, rJ);
        }

        Relation rel = null;

        if (null == labelsToScores)
          rel = new Relation(name, constituents.get(src), constituents.get(tgt), s);
        else rel = new Relation(labelsToScores, constituents.get(src), constituents.get(tgt));

        readAttributes(rel, rJ);

        view.addRelation(rel);
      }
    }
    return view;
  }
Ejemplo n.º 5
0
  /**
   * This function is called in the benchmarking phase which is executed with the -t argument. Get
   * the profile object for a user.
   *
   * @param requesterID Unique identifier for the requester.
   * @param profileOwnerID unique profile owner's identifier.
   * @param result A HashMap with all data returned. These data are different user information
   *     within the profile such as friend count, friend request count, etc.
   * @param insertImage Identifies if the users have images in the database. If set to true the
   *     images for the users will be retrieved.
   * @param testMode If set to true images will be retrieved and stored on the file system. While
   *     running benchmarks this field should be set to false.
   * @return 0 on success a non-zero error code on error. See this class's description for a
   *     discussion of error codes.
   *     <p>The code written for this function retrieves the user's profile details, friendcount
   *     (number of friends for that user) and resourcecount (number of resources inserted on that
   *     user's wall). In addition if the requesterID is equal to the profileOwnerID, the
   *     pendingcount (number of pending friend requests) needs to be returned as well.
   *     <p>If the insertImage is set to true, the image for the profileOwnerID will be rertrieved.
   *     The insertImage should be set to true only if the user entity has an image in the database.
   *     <p>The friendcount, resourcecount, pendingcount should be put into the results HashMap with
   *     the following keys: "friendcount", "resourcecount" and "pendingcount", respectively. Lack
   *     of these attributes or not returning the attribute keys in lower case causes BG to raise
   *     exceptions. In addition, all other attributes of the profile need to be added to the result
   *     hashmap with the attribute names being the keys and the attribute values being the values
   *     in the hashmap.
   *     <p>If images exist for users, they should be converted to bytearrays and added to the
   *     result hashmap.
   */
  @Override
  public int viewProfile(
      int requesterID,
      int profileOwnerID,
      HashMap<String, ByteIterator> result,
      boolean insertImage,
      boolean testMode) {
    JsonObject jsonObject;
    try {
      jsonObject = transactionHelper.readUser(String.valueOf(profileOwnerID));
    } catch (ConnectionException | NotFoundException e) {
      e.printStackTrace();
      return -1;
    }

    /** Dump data to result. */
    jsonObject
        .entrySet()
        .forEach(
            entry -> {
              if (!entry.getKey().equals(PENDING_FRIENDS)
                  && !entry.getKey().equals(CONFIRMED_FRIENDS)
                  && !entry.getKey().equals(RESOURCES)) {
                result.put(entry.getKey(), new StringByteIterator(entry.getValue().getAsString()));
              }
            });

    /** Count friends. */
    int friendCount = 0;
    if (jsonObject.has(CONFIRMED_FRIENDS)) {
      JsonArray jsonArray = jsonObject.getAsJsonArray(CONFIRMED_FRIENDS);
      friendCount = jsonArray.size();
    }
    result.put(FRIEND_COUNT, new ObjectByteIterator(String.valueOf(friendCount).getBytes()));

    /** Count resources. */
    int resourceCount = 0;
    if (jsonObject.has(RESOURCES)) {
      JsonArray jsonArray = jsonObject.getAsJsonArray(RESOURCES);
      resourceCount = jsonArray.size();
    }
    result.put(RESOURCE_COUNT, new ObjectByteIterator(String.valueOf(resourceCount).getBytes()));

    /** Pending friendships. */
    if (requesterID == profileOwnerID) {
      int pendingCount = 0;
      JsonElement jsonElement = jsonObject.get(PENDING_FRIENDS);
      if (jsonElement != null) {
        pendingCount = jsonElement.getAsJsonArray().size();
      }
      result.put(PENDING_COUNT, new ObjectByteIterator(String.valueOf(pendingCount).getBytes()));
    }
    return 0;
  }
Ejemplo n.º 6
0
  protected Vehicle queryVehicle() {

    // get a list of vehicles
    Response response =
        vehiclesTarget
            .request(MediaType.APPLICATION_JSON_TYPE)
            .header("Authorization", "Bearer " + accessToken)
            .get();

    logger.trace("Querying the vehicle : Response : {}", response.getStatusInfo());

    JsonParser parser = new JsonParser();

    JsonObject jsonObject = parser.parse(response.readEntity(String.class)).getAsJsonObject();
    Vehicle[] vehicleArray = gson.fromJson(jsonObject.getAsJsonArray("response"), Vehicle[].class);

    for (int i = 0; i < vehicleArray.length; i++) {
      logger.trace("Querying the vehicle : VIN : {}", vehicleArray[i].vin);
      if (vehicleArray[i].vin.equals(getConfig().get(VIN))) {
        vehicleJSON = gson.toJson(vehicleArray[i]);
        parseAndUpdate("queryVehicle", null, vehicleJSON);
        return vehicleArray[i];
      }
    }

    return null;
  }
 @Override
 public TargetInfo deserialize(
     JsonElement element, Type type, final JsonDeserializationContext context)
     throws JsonParseException {
   final JsonObject object = element.getAsJsonObject();
   final List<String> targets = getStringListField(object, "targets");
   final List<String> libraries = getStringListField(object, "libraries");
   final List<String> excludes = getStringListField(object, "excludes");
   final List<SourceRoot> sourceRoots =
       getFieldAsList(
           object.getAsJsonArray("roots"),
           new Function<JsonElement, SourceRoot>() {
             @Override
             public SourceRoot fun(JsonElement element) {
               return context.deserialize(element, SourceRoot.class);
             }
           });
   final TargetAddressInfo addressInfo = context.deserialize(element, TargetAddressInfo.class);
   return new TargetInfo(
       new HashSet<TargetAddressInfo>(Collections.singleton(addressInfo)),
       new HashSet<String>(targets),
       new HashSet<String>(libraries),
       new HashSet<String>(excludes),
       new HashSet<SourceRoot>(sourceRoots));
 }
Ejemplo n.º 8
0
 /**
  * Queries a view.
  *
  * @param <K> Object type K (key)
  * @param <V> Object type V (value)
  * @param classOfK The class of type K.
  * @param classOfV The class of type V.
  * @param classOfT The class of type T.
  * @return The View result entries.
  */
 public <K, V, T> ViewResult<K, V, T> queryView(
     Class<K> classOfK, Class<V> classOfV, Class<T> classOfT) {
   InputStream instream = null;
   try {
     Reader reader = new InputStreamReader(instream = queryForStream(), Charsets.UTF_8);
     JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
     ViewResult<K, V, T> vr = new ViewResult<K, V, T>();
     vr.setTotalRows(getAsLong(json, "total_rows"));
     vr.setOffset(getAsInt(json, "offset"));
     vr.setUpdateSeq(getAsLong(json, "update_seq"));
     JsonArray jsonArray = json.getAsJsonArray("rows");
     if (jsonArray.size() == 0) { // validate available rows
       throw new NoDocumentException("No result was returned by this view query.");
     }
     for (JsonElement e : jsonArray) {
       ViewResult<K, V, T>.Rows row = vr.new Rows();
       row.setId(JsonToObject(gson, e, "id", String.class));
       row.setKey(JsonToObject(gson, e, "key", classOfK));
       row.setValue(JsonToObject(gson, e, "value", classOfV));
       if (Boolean.TRUE.equals(this.includeDocs)) {
         row.setDoc(JsonToObject(gson, e, "doc", classOfT));
       }
       vr.getRows().add(row);
     }
     return vr;
   } finally {
     close(instream);
   }
 }
Ejemplo n.º 9
0
    @Override
    public HanabiraBoard deserialize(
        JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
      JsonObject boardsJsonObject = json.getAsJsonObject().get("boards").getAsJsonObject();
      Set<Map.Entry<String, JsonElement>> boardsSet = boardsJsonObject.entrySet();
      if (boardsSet.size() > 1) {
        throw new IllegalArgumentException("Few board entries received for a request");
      }
      Map.Entry<String, JsonElement> boardEntry = boardsSet.iterator().next();
      boardKey = boardEntry.getKey();
      JsonObject boardObject = boardEntry.getValue().getAsJsonObject();
      int pages = boardObject.get("pages").getAsInt();

      HanabiraBoard cachedBoard = Hanabira.getStem().findBoardByKey(boardKey);
      if (cachedBoard == null) {
        cachedBoard = new HanabiraBoard(boardKey, pages, null);
        Hanabira.getStem().saveBoard(cachedBoard);
      } else {
        cachedBoard.update(pages, null);
      }

      JsonElement pageElement = boardObject.get("page");
      int page = (pageElement == null) ? 0 : pageElement.getAsInt();

      List<Integer> threadsOnPageIds = new ArrayList<>();
      for (JsonElement threadElement : boardObject.getAsJsonArray("threads")) {
        threadsOnPageIds.add(
            createThreadWithPosts(threadElement.getAsJsonObject(), boardKey).getThreadId());
      }
      cachedBoard.updatePage(page, threadsOnPageIds);

      return cachedBoard;
    }
  @Override
  public JsonObject upgrade(JsonObject unitGroup, Map<File, JsonObject> dbSnapshot)
      throws CouldNotPerformException {
    String newUnitType = unitTypeMap.get(unitGroup.get(UNIT_TYPE_FIELD).getAsString());
    unitGroup.remove(UNIT_TYPE_FIELD);
    unitGroup.addProperty(UNIT_TYPE_FIELD, newUnitType);

    JsonArray serviceTemplates = unitGroup.getAsJsonArray(SERVICE_TEMPLATE_FIELD);
    if (serviceTemplates != null) {
      JsonArray newServiceTemplates = new JsonArray();
      for (JsonElement serviceTemplateElem : serviceTemplates) {
        JsonObject serviceTemplate = serviceTemplateElem.getAsJsonObject();

        String oldServiceType = serviceTemplate.get(SERVICE_TYPE_FIELD).getAsString();
        String newServiceType = serviceTypeMap.get(oldServiceType);
        serviceTemplate.remove(SERVICE_TYPE_FIELD);
        serviceTemplate.addProperty(TYPE_FIELD, newServiceType);
        serviceTemplate.addProperty(PATTERN_FIELD, PROVIDER_PATTERN);
        newServiceTemplates.add(serviceTemplate);

        if (oldServiceType.endsWith("SERVICE")) {
          JsonObject operationServiceTemplate = new JsonObject();
          operationServiceTemplate.addProperty(TYPE_FIELD, newServiceType);
          operationServiceTemplate.addProperty(PATTERN_FIELD, OPERATION_PATTERN);
          operationServiceTemplate.add(META_CONFIG_FIELD, serviceTemplate.get(META_CONFIG_FIELD));
          newServiceTemplates.add(operationServiceTemplate);
        }
      }
      unitGroup.remove(SERVICE_TEMPLATE_FIELD);
      unitGroup.add(SERVICE_TEMPLATE_FIELD, newServiceTemplates);
    }

    return unitGroup;
  }
Ejemplo n.º 11
0
  public void getTelephones() {
    List<Telephone> telephones = new ArrayList<Telephone>();

    String json = "{}";
    try {
      json = readTelephones();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    Gson gson = new Gson();
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
    JsonArray content = jsonObject.getAsJsonArray("util");

    Iterator<JsonElement> it = content.iterator();

    while (it.hasNext()) {
      JsonElement newsJson = it.next();
      Telephone tel = gson.fromJson(newsJson, Telephone.class);
      telephones.add(tel);
    }

    this.telephones = telephones;
  }
  @Override
  public ImageSearchResult deserialize(
      JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {

    ImageSearchResult result = new ImageSearchResult();

    if (json.getAsJsonObject().get("responseStatus").getAsInt() != 200) {
      // TODO handle error
      return result;
    }

    JsonObject jsonObject = json.getAsJsonObject().getAsJsonObject("responseData");
    JsonArray resultsArray = jsonObject.getAsJsonArray("results");

    for (int i = 0; i < resultsArray.size(); i++) {
      Image image = new Image();
      image.setContent(resultsArray.get(i).getAsJsonObject().get("content").getAsString());
      image.setUrl(resultsArray.get(i).getAsJsonObject().get("url").getAsString());
      image.setHeight(resultsArray.get(i).getAsJsonObject().get("height").getAsInt());
      image.setWidth(resultsArray.get(i).getAsJsonObject().get("width").getAsInt());

      image.setThumbnailUrl(resultsArray.get(i).getAsJsonObject().get("tbUrl").getAsString());
      image.setThumbnailHeight(resultsArray.get(i).getAsJsonObject().get("tbHeight").getAsInt());
      image.setThumbnailWidth(resultsArray.get(i).getAsJsonObject().get("tbWidth").getAsInt());
      result.addImage(image);
    }

    return result;
  }
Ejemplo n.º 13
0
  /**
   * Parse through the JSON string received from the server and translate into GameModelJSON object
   *
   * @param json String received from the server API
   * @return The now parsed GameModelJSON object.
   * @throws GeneralPlayerException
   * @throws InvalidTurnStatusException
   * @throws TurnIndexException
   */
  private CatanModel _deserialize(String json)
      throws TurnIndexException, InvalidTurnStatusException, GeneralPlayerException {

    JsonElement jelement = new JsonParser().parse(json);
    JsonObject jobject = jelement.getAsJsonObject();
    JsonObject deck = jobject.getAsJsonObject("deck");
    JsonObject bank = jobject.getAsJsonObject("bank");
    JsonObject chat = jobject.getAsJsonObject("chat");
    JsonObject log = jobject.getAsJsonObject("log");
    JsonObject map = jobject.getAsJsonObject("map");
    JsonArray players = jobject.getAsJsonArray("players");
    JsonObject tradeOffer = jobject.getAsJsonObject("tradeOffer");
    JsonObject turnTracker = jobject.getAsJsonObject("turnTracker");
    int version = jobject.getAsJsonPrimitive("version").getAsInt();
    int winner = jobject.getAsJsonPrimitive("winner").getAsInt();

    SetResourceManager(bank, players, tradeOffer);
    SetDevCardManager(players, deck);
    SetPlayerManager(players, turnTracker);
    SetMapManager(map);
    SetChatManager(chat, log);
    SetTurnManager(turnTracker);

    return catanModel =
        new CatanModel(
            resourceManager, devCardManager, playerManager, mapManager, chatManager, version);
  }
  public PublicKey retrieveJwkKey(String jwkUrl) {
    RSAPublicKey pub = null;

    try {
      String jwkString = restTemplate.getForObject(jwkUrl, String.class);
      JsonObject json = (JsonObject) new JsonParser().parse(jwkString);
      JsonArray getArray = json.getAsJsonArray("keys");
      for (int i = 0; i < getArray.size(); i++) {
        JsonObject object = getArray.get(i).getAsJsonObject();
        String algorithm = object.get("alg").getAsString();

        if (algorithm.equals("RSA")) {
          byte[] modulusByte = Base64.decodeBase64(object.get("mod").getAsString());
          BigInteger modulus = new BigInteger(1, modulusByte);
          byte[] exponentByte = Base64.decodeBase64(object.get("exp").getAsString());
          BigInteger exponent = new BigInteger(1, exponentByte);

          RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
          KeyFactory factory = KeyFactory.getInstance("RSA");
          pub = (RSAPublicKey) factory.generatePublic(spec);
        }
      }

    } catch (HttpClientErrorException e) {
      logger.error("HttpClientErrorException in KeyFetcher.java: ", e);
    } catch (NoSuchAlgorithmException e) {
      logger.error("NoSuchAlgorithmException in KeyFetcher.java: ", e);
    } catch (InvalidKeySpecException e) {
      logger.error("InvalidKeySpecException in KeyFetcher.java: ", e);
    }
    return pub;
  }
Ejemplo n.º 15
0
 public static JsonObject mergeJsonFiles(JsonObject target, String... filenames)
     throws IOException {
   if (target == null) {
     target = new JsonObject();
   }
   for (String filename : filenames) {
     String url = Config.CLOUD_STORAGE_BASE_URL + filename;
     JsonObject obj = fetchJsonFromPublicURL(url);
     if (obj == null) {
       throw new FileNotFoundException(url);
     } else {
       for (Entry<String, JsonElement> entry : obj.entrySet()) {
         if (entry.getValue().isJsonArray()) {
           // tries to merge an array with the existing one, if it's the case:
           JsonArray existing = target.getAsJsonArray(entry.getKey());
           if (existing == null) {
             existing = new JsonArray();
             target.add(entry.getKey(), existing);
           }
           existing.addAll(entry.getValue().getAsJsonArray());
         } else {
           target.add(entry.getKey(), entry.getValue());
         }
       }
     }
   }
   return target;
 }
 @Override
 public Result downloadAndParse() {
   Result result = officeSheetPopulator.downloadAndParse();
   if (result.isSuccess()) result = clientSheetPopulator.downloadAndParse();
   if (result.isSuccess()) result = extrasSheetPopulator.downloadAndParse();
   if (result.isSuccess()) {
     try {
       restClient.createAuthToken();
       content = restClient.get("savingsaccounts?limit=-1");
       Gson gson = new Gson();
       JsonParser parser = new JsonParser();
       JsonObject obj = parser.parse(content).getAsJsonObject();
       JsonArray array = obj.getAsJsonArray("pageItems");
       Iterator<JsonElement> iterator = array.iterator();
       while (iterator.hasNext()) {
         JsonElement json = iterator.next();
         CompactSavingsAccount savingsAccount = gson.fromJson(json, CompactSavingsAccount.class);
         if (savingsAccount.isActive()) savings.add(savingsAccount);
       }
     } catch (Exception e) {
       result.addError(e.getMessage());
       logger.error(e.getMessage());
     }
   }
   return result;
 }
Ejemplo n.º 17
0
  @Override
  public void run() {
    try {
      while (active.get()) {
        SkypePullPacket skypePullPacket = new SkypePullPacket(ezSkype);
        JsonObject responseData = (JsonObject) skypePullPacket.executeSync();
        EzSkype.LOGGER.debug(responseData.toString());
        if (responseData.entrySet().size() != 0) {
          if (responseData.has("eventMessages")) {
            JsonArray messages = responseData.getAsJsonArray("eventMessages");

            for (JsonElement jsonObject : messages) {
              try {
                extractInfo(jsonObject.getAsJsonObject());
              } catch (Exception e) {
                EzSkype.LOGGER.error("Error extracting info from:\n" + jsonObject, e);
              }
            }
          } else {
            EzSkype.LOGGER.error("Bad poll response: " + responseData);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 18
0
 /**
  * This method returns a geonames Id by a country code.
  *
  * @param countryCode
  * @return
  * @throws CannotGetCountryIdException
  * @throws CantConnectWithExternalAPIException
  * @throws CantGetJSonObjectException
  */
 private static int getGeonamesIdByCountryCode(String countryCode)
     throws CannotGetCountryIdException, CantConnectWithExternalAPIException,
         CantGetJSonObjectException {
   int geonamesCountryId;
   // We request the country information to Geonames API
   String queryUrl =
       GeolocationConfiguration.GEONAMES_URL_COUNTRY
           + countryCode
           + "&username="******"The country code " + countryCode + " cannot be found in Geonames API");
 }
Ejemplo n.º 19
0
  public static ArrayList<Meetup> jsonToMeetups(JsonObject json) {
    ArrayList<Meetup> meetups = new ArrayList<>();

    JsonArray events = json.getAsJsonArray("events");

    for (int x = 0; x < events.size(); x++) {
      String orgString;
      String dateString;
      String nameString;

      JsonObject event = events.get(x).getAsJsonObject();

      try {
        JsonObject info = event.getAsJsonObject("info");
        nameString = info.getAsJsonObject().getAsJsonPrimitive("name").getAsString();
        dateString = info.getAsJsonObject().getAsJsonPrimitive("start_date").getAsString();
      } catch (Exception e) {
        nameString = "";
        dateString = "";
      }

      try {
        JsonObject org = event.getAsJsonObject("org");
        orgString = org.getAsJsonObject().getAsJsonPrimitive("name").getAsString();
      } catch (Exception e) {
        orgString = "";
      }

      meetups.add(new Meetup(orgString, nameString, dateString));
    }

    return meetups;
  }
Ejemplo n.º 20
0
  protected void parse(JsonObject nodeObject) {
    this.id = nodeObject.getAsJsonPrimitive(GraphSchema.NODE_ID_TAG).getAsString();
    this.name = nodeObject.getAsJsonPrimitive(GraphSchema.NODE_NAME_TAG).getAsString();

    JsonArray jArray;
    if (nodeObject.get(GraphSchema.NODE_INPUT_PORT_TAG) != null) {
      jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_INPUT_PORT_TAG);
      for (JsonElement jsonElement : jArray) {
        this.inputPortIDs.add(jsonElement.getAsString());
      }
    }

    if (nodeObject.get(GraphSchema.NODE_OUTPUT_PORT_TAG) != null) {
      jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_OUTPUT_PORT_TAG);
      for (JsonElement jsonElement : jArray) {
        this.outputPortIDs.add(jsonElement.getAsString());
      }
    }

    JsonElement jElement = nodeObject.get(GraphSchema.NODE_CONTROL_IN_PORT_TAG);
    if (jElement != null) {
      this.controlInPortID = jElement.getAsString();
    }

    if (nodeObject.get(GraphSchema.NODE_CONTROL_OUT_PORT_TAG) != null) {
      jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_CONTROL_OUT_PORT_TAG);
      for (JsonElement jsonElement : jArray) {
        this.controlOutPortIDs.add(jsonElement.getAsString());
      }
    }

    jElement = nodeObject.get(GraphSchema.NODE_EPR_PORT_TAG);
    if (jElement != null) {
      this.eprPortID = jElement.getAsString();
    }

    this.position.x = nodeObject.get(GraphSchema.NODE_X_LOCATION_TAG).getAsInt();
    this.position.y = nodeObject.get(GraphSchema.NODE_Y_LOCATION_TAG).getAsInt();

    // Parse config element not sure why we used it.
    // Parse component element.
    JsonObject configObject = nodeObject.getAsJsonObject(GraphSchema.NODE_CONFIG_TAG);
    if (configObject != null) {
      parseConfiguration(configObject);
    }
  }
  @NotNull
  public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) {

    JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();

    List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>();

    // prevent adding duplicate version on alias names
    Set<String> aliasBranches = new HashSet<>();

    // get alias version, in most common order
    for (String s : new String[] {"latest", "lts"}) {
      JsonElement asJsonObject = jsonObject.get(s);
      if (asJsonObject == null) {
        continue;
      }

      String asString = asJsonObject.getAsString();
      aliasBranches.add(asString);

      symfonyInstallerVersions.add(
          new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s)));
    }

    List<SymfonyInstallerVersion> branches = new ArrayList<>();
    Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
    for (Map.Entry<String, JsonElement> entry : entries) {
      if (!entry.getKey().matches("^\\d+\\.\\d+$")) {
        continue;
      }

      // "2.8.0-dev", "2.8.0-DEV" is not supported
      String asString = entry.getValue().getAsString();
      if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) {
        continue;
      }

      branches.add(
          new SymfonyInstallerVersion(
              asString, String.format("%s (%s)", entry.getKey(), asString)));
    }

    branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion));

    Collections.reverse(branches);

    symfonyInstallerVersions.addAll(branches);

    // we need reverse order for sorting them on version string
    List<SymfonyInstallerVersion> installableVersions = new ArrayList<>();
    for (JsonElement installable : jsonObject.getAsJsonArray("installable")) {
      installableVersions.add(new SymfonyInstallerVersion(installable.getAsString()));
    }
    Collections.reverse(installableVersions);

    symfonyInstallerVersions.addAll(installableVersions);
    return symfonyInstallerVersions;
  }
Ejemplo n.º 22
0
  private void loadJsonDefaultDictionary(final SQLiteDatabase db) {
    int dictionaryIdNext = 1;
    int vocableIdNext = 1;
    PictureUtil util = PictureUtil.getInstance(context);

    db.beginTransaction();
    try {
      Resources res = context.getResources();

      InputStream in = res.openRawResource(R.raw.default_dictionaries);
      String json = IOUtils.toString(in);
      JsonParser parser = new JsonParser();
      JsonObject root = parser.parse(json).getAsJsonObject();

      JsonArray dictionaries = root.getAsJsonArray("dictionaries");
      for (JsonElement dictionariesElem : dictionaries) {
        JsonObject dictionary = dictionariesElem.getAsJsonObject();

        byte[] dictionaryPicture = util.getResourcePicture(dictionary.get("picture").getAsString());
        String name = dictionary.get("name").getAsString();

        int dictionaryId = dictionaryIdNext++;
        addDictionary(db, dictionaryId, dictionaryPicture, name);

        JsonArray vocables = dictionary.getAsJsonArray("vocables");
        for (JsonElement vocablesElem : vocables) {
          JsonObject vocable = vocablesElem.getAsJsonObject();

          byte[] picture = util.getResourcePicture(vocable.get("picture").getAsString());
          String word = vocable.get("word").getAsString();

          int vocableId = vocableIdNext++;
          addVocable(db, vocableId, dictionaryId, picture, word);
        }
      }

      db.setTransactionSuccessful();
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      db.endTransaction();
    }
  }
    @Override
    public void run() {
      try {
        // Authenticate
        URLConnection connection = new URL(this.postURL).openConnection();

        JsonObject json;
        try (InputStream is = connection.getInputStream()) {
          if (is.available() == 0) {
            this.session.disconnect("Invalid username or session id!");
            return;
          }
          try {
            json = gson.fromJson(new InputStreamReader(is), JsonObject.class);
          } catch (Exception e) {
            LanternGame.log().warn("Username \"" + this.username + "\" failed to authenticate!");
            this.session.disconnect("Failed to verify username!");
            return;
          }
        }

        String name = json.get("name").getAsString();
        String id = json.get("id").getAsString();

        // Parse UUID
        UUID uuid;

        try {
          uuid = UUIDHelper.fromFlatString(id);
        } catch (IllegalArgumentException e) {
          LanternGame.log().error("Returned authentication UUID invalid: " + id, e);
          this.session.disconnect("Invalid UUID.");
          return;
        }

        JsonArray propsArray = json.getAsJsonArray("properties");

        // Parse properties
        Multimap<String, ProfileProperty> properties = LinkedHashMultimap.create();
        for (JsonElement element : propsArray) {
          JsonObject json0 = element.getAsJsonObject();
          String propName = json0.get("name").getAsString();
          String value = json0.get("value").getAsString();
          String signature = json0.has("signature") ? json0.get("signature").getAsString() : null;
          properties.put(propName, new LanternProfileProperty(propName, value, signature));
        }

        LanternGame.log().info("Finished authenticating.");
        this.session.messageReceived(
            new MessageLoginInFinish(new LanternGameProfile(uuid, name, properties)));
      } catch (Exception e) {
        LanternGame.log().error("Error in authentication thread", e);
        this.session.disconnect("Internal error during authentication.", true);
      }
    }
 @Override
 public RPatOpTopType deserialize(
     JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
     throws JsonParseException {
   JsonObject objType = jsonElement.getAsJsonObject();
   JsonArray stuff;
   if ((stuff = objType.getAsJsonArray("RPStar")) != null) { // TODO: Test.
     RPStar rpStar = new RPStar();
     rpStar.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpStar;
   } else if ((stuff = objType.getAsJsonArray("RPStarG")) != null) { // TODO: Test.
     RPStarG rpStarG = new RPStarG();
     rpStarG.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpStarG;
   } else if ((stuff = objType.getAsJsonArray("RPPlus")) != null) { // TODO: Test.
     RPPlus rpPlus = new RPPlus();
     rpPlus.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpPlus;
   } else if ((stuff = objType.getAsJsonArray("RPPlusG")) != null) { // TODO: Test.
     RPPlusG rpPlus = new RPPlusG();
     rpPlus.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpPlus;
   } else if ((stuff = objType.getAsJsonArray("RPOpt")) != null) { // TODO: Test.
     RPOpt rpOpt = new RPOpt();
     rpOpt.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpOpt;
   } else if ((stuff = objType.getAsJsonArray("RPOptG")) != null) { // TODO: Test.
     RPOptG rpOptG = new RPOptG();
     rpOptG.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
     return rpOptG;
   }
   throw new JsonParseException("Unexpected JSON object type: " + objType.toString());
 }
Ejemplo n.º 25
0
  /**
   * Construit un objet Saison à partir d'un objet JSON. Si les champs demandés ne sont pas trouvé
   * dans l'objet JSON, les champs contiendront null.
   *
   * @param seasonObject L'objet JSON contenant les informations de la saison.
   */
  public Season(JsonObject seasonObject) {
    this.episodes = new LinkedList<>();
    title = seasonObject.get("Title").getAsString();
    season = seasonObject.get("Season").getAsString();

    /* On récupère les informations de chaque épisode de la série, s'il sexistent. */
    JsonArray episodes = seasonObject.getAsJsonArray("Episodes");
    if (episodes != null) {
      for (JsonElement episode : episodes) {
        JsonObject episodeObject = episode.getAsJsonObject();
        this.episodes.add(new Episode(episodeObject));
      }
    }
  }
Ejemplo n.º 26
0
 @Override
 public Metadata deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
   JsonObject metadata = json.getAsJsonObject();
   JsonArray items = metadata.getAsJsonArray("items");
   if (items != null) {
     for (JsonElement element : items) {
       JsonObject object = element.getAsJsonObject();
       builder.put(object.get("key").getAsString(), object.get("value").getAsString());
     }
   }
   return new Metadata(builder.build());
 }
Ejemplo n.º 27
0
  private void parseFriends(VKResponse response) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();

    String responseStr = response.responseString;
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(responseStr).getAsJsonObject().getAsJsonObject("response");
    JsonArray items = jsonObject.getAsJsonArray("items");

    for (JsonElement data : items) {
      Friend friend = gson.fromJson(data, Friend.class);
      friendList.add(friend);
    }
  }
Ejemplo n.º 28
0
  private void setBuildStatus(CIBuild ciBuild, CIJob job) throws PhrescoException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setBuildStatus(CIBuild ciBuild)");
    S_LOGGER.debug("setBuildStatus()  url = " + ciBuild.getUrl());
    String buildUrl = ciBuild.getUrl();
    String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
    buildUrl =
        buildUrl.replaceAll(
            "localhost:" + job.getJenkinsPort(),
            jenkinsUrl); // display the jenkins running url in ci list
    String response = getJsonResponse(buildUrl + API_JSON);
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(response);
    JsonObject jsonObject = jsonElement.getAsJsonObject();

    JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT);
    JsonElement idJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_ID);
    JsonElement timeJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_TIME_STAMP);
    JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS);

    if (jsonObject
        .get(FrameworkConstants.CI_JOB_BUILD_RESULT)
        .toString()
        .equals(STRING_NULL)) { // when build is result is not known
      ciBuild.setStatus(INPROGRESS);
    } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG)
        && asJsonArray.size()
            < 1) { // when build is success and zip relative path is not added in json
      ciBuild.setStatus(INPROGRESS);
    } else {
      ciBuild.setStatus(resultJson.getAsString());
      // download path
      for (JsonElement jsonArtElement : asJsonArray) {
        String buildDownloadZip =
            jsonArtElement
                .getAsJsonObject()
                .get(FrameworkConstants.CI_JOB_BUILD_DOWNLOAD_PATH)
                .toString();
        if (buildDownloadZip.endsWith(CI_ZIP)) {
          if (debugEnabled) {
            S_LOGGER.debug("download artifact " + buildDownloadZip);
          }
          ciBuild.setDownload(buildDownloadZip);
        }
      }
    }

    ciBuild.setId(idJson.getAsString());
    String dispFormat = DD_MM_YYYY_HH_MM_SS;
    ciBuild.setTimeStamp(getDate(timeJson.getAsString(), dispFormat));
  }
Ejemplo n.º 29
0
 private void readSoundList(JsonObject element, String field, List<StaticSound> sounds)
     throws IOException {
   if (element.has(field) && element.get(field).isJsonArray()) {
     sounds.clear();
     for (JsonElement item : element.getAsJsonArray(field)) {
       Optional<StaticSound> sound = assetManager.getAsset(item.getAsString(), StaticSound.class);
       if (sound.isPresent()) {
         sounds.add(sound.get());
       } else {
         throw new IOException("Unable to resolve sound '" + item.getAsString() + "'");
       }
     }
   }
 }
 @NotNull
 private List<String> getStringListField(JsonObject object, String memberName) {
   if (!object.has(memberName)) {
     return Collections.emptyList();
   }
   return getFieldAsList(
       object.getAsJsonArray(memberName),
       new Function<JsonElement, String>() {
         @Override
         public String fun(JsonElement element) {
           return element.getAsString();
         }
       });
 }