Package external.JSON

Examples of external.JSON.JSONObject


      zone = RemoteResourceLoader.loadRaw("http://metadata/computeMetadata/v1/instance/zone", 1, metadataRequestProperties);
    } catch (IOException e1) {
      // If we can't acquire the request farm zone, just silently drop it.
    }

        JSONObject thePing = new JSONObject();
        try {
          if (zone != null) thePing.put("zone", zone);
            thePing.put("lastTimeBlock", (System.currentTimeMillis() / 3600000));
            thePing.put("nextTimeBlock", (System.currentTimeMillis() / 3600000)+1);
            SignableJSON.signJSON(thePing, theBackendKeys.thePublicKey, theBackendKeys.thePrivateKey);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return thePing.toString();
    }
View Full Code Here


        } else if (event instanceof ServerCompletedMatchEvent) {
              System.out.println("State[" + nState[0] + "] Full (Terminal): " + oldContents);
              System.out.println("Match information: " + theMatch);
              System.out.println("Goals: " + ((ServerCompletedMatchEvent)event).getGoals());
              try {
                System.out.println("Match information cryptographically signed? " + SignableJSON.isSignedJSON(new JSONObject(theMatch.toJSON())));
                System.out.println("Match information cryptographic signature valid? " + SignableJSON.verifySignedJSON(new JSONObject(theMatch.toJSON())));
              } catch (JSONException je) {
                je.printStackTrace();
              }
              System.out.println("Game over.");
        }
View Full Code Here

      int targetPort, timeoutClock;
      boolean fastReturn;
      JSONObject myResponse;

      public RunSingleRequestThread(JSONObject theJSON) throws JSONException {
        myResponse = new JSONObject();
        myResponse.put("originalRequest", theJSON);
            targetPort = theJSON.getInt("targetPort");
            targetHost = theJSON.getString("targetHost");
            timeoutClock = theJSON.getInt("timeoutClock");
            forPlayerName = theJSON.getString("forPlayerName");
View Full Code Here

                    activeRequests.add(line);
                  }
                  this.activeRequests = activeRequests;
                }

                JSONObject theBatchJSON = new JSONObject(line);
                JSONArray theRequests = theBatchJSON.getJSONArray("requests");
                theRequestThreads = new HashSet<RunSingleRequestThread>();
                for (int i = 0; i < theRequests.length(); i++) {
                  JSONObject aRequest = theRequests.getJSONObject(i);
                  RunSingleRequestThread aRequestThread = new RunSingleRequestThread(aRequest);
                  theRequestThreads.add(aRequestThread);
                }
                callbackURL = theBatchJSON.getString("callbackURL");
View Full Code Here

            for (RunSingleRequestThread aRequestThread : theRequestThreads) {
              aRequestThread.start();
            }

            // Wait for all of the requests to finish; aggregate them into a batch response.
            JSONObject responseJSON = new JSONObject();
            JSONArray responses = new JSONArray();
            for (RunSingleRequestThread aRequestThread : theRequestThreads) {
              try {
          aRequestThread.join();
          responses.put(aRequestThread.getResponse());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
            }
            try {
                responseJSON.put("responses", responses);
                if (!testMode) {
                  SignableJSON.signJSON(responseJSON, theBackendKeys.thePublicKey, theBackendKeys.thePrivateKey);
                }
            } catch (JSONException je) {
              je.printStackTrace();
              synchronized (requestCountLock) {
                abandonedBatches++;
                activeBatches--;
                printBatchStats();
              }
                synchronized (activeRequests) {
                  activeRequests.remove(originalRequest);
                }
              return;
            }

            // Send the batch response back to the callback URL.
          synchronized (requestCountLock) {
            returningRequests++;
            printBatchStats();
          }
            int nPostAttempts = 0;
            while (true) {
              try {
                RemoteResourceLoader.postRawWithTimeout(callbackURL, responseJSON.toString(), Integer.MAX_VALUE);
                break;
              } catch (IOException ie) {
                nPostAttempts++;
                try {
            Thread.sleep(nPostAttempts < 10 ? 1000 : 15000);
View Full Code Here

public class RemoteResourceLoader {
  public static JSONObject loadJSON(String theURL) throws JSONException, IOException {
    return loadJSON(theURL, 1);
  }
    public static JSONObject loadJSON(String theURL, int nMaxAttempts) throws JSONException, IOException {
    return new JSONObject(loadRaw(theURL, nMaxAttempts));
    }
View Full Code Here

    String line;
    int nCount = 0;
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(ARCHIVE_FILE), Charset.forName("UTF-8")));
    while ((line = br.readLine()) != null) {
      JSONObject entryJSON = new JSONObject(line);
      String url = entryJSON.getString("url");
      JSONObject matchJSON = entryJSON.getJSONObject("data");
      processMatch(url, matchJSON, data);
      nCount++;
      if (nCount % 1000 == 0) {
        System.out.println("Processed " + nCount + " matches.");
      }
View Full Code Here

    };

    /* Helper function to generate canonical strings for JSON strings */
    static String getCanonicalForm(String x, CanonicalizationStrategy s) {
        try {
            return getCanonicalForm(new JSONObject(x), s);
        } catch (JSONException e) {
            return null;
        }
    }
View Full Code Here

    /* This should be identical to the standard code to render the JSON object,
     * except it forces the keys for maps to be listed in sorted order. */
    static String renderSimpleCanonicalJSON(Object x) {
        try {
            if (x instanceof JSONObject) {
                JSONObject theObject = (JSONObject)x;

                // Sort the keys
                TreeSet<String> t = new TreeSet<String>();
                Iterator<?> i = theObject.keys();
                while (i.hasNext()) t.add(i.next().toString());
                Iterator<String> keys = t.iterator();

                StringBuffer sb = new StringBuffer("{");
                while (keys.hasNext()) {
                    if (sb.length() > 1) {
                        sb.append(',');
                    }
                    Object o = keys.next();
                    sb.append(JSONObject.quote(o.toString()));
                    sb.append(':');
                    sb.append(renderSimpleCanonicalJSON(theObject.get(o.toString())));
                }
                sb.append('}');
                return sb.toString();
            } else if (x instanceof JSONArray) {
                JSONArray theArray = (JSONArray)x;
                StringBuffer sb = new StringBuffer();
                sb.append("[");
                int len = theArray.length();
                for (int i = 0; i < len; i += 1) {
                    if (i > 0) {
                        sb.append(",");
                    }
                    sb.append(renderSimpleCanonicalJSON(theArray.get(i)));
                }
                sb.append("]");
                return sb.toString();
            } else {
                if (x == null || x.equals(null)) {
                    return "null";
                }
                if (x instanceof JSONString) {
                    Object object;
                    try {
                        object = ((JSONString)x).toJSONString();
                    } catch (Exception e) {
                        throw new JSONException(e);
                    }
                    if (object instanceof String) {
                        return (String)object;
                    }
                    throw new JSONException("Bad value from toJSONString: " + object);
                }
                if (x instanceof Number) {
                    return JSONObject.numberToString((Number)x);
                }
                if (x instanceof Boolean || x instanceof JSONObject ||
                        x instanceof JSONArray) {
                    return x.toString();
                }
                if (x instanceof Map) {
                    return renderSimpleCanonicalJSON(new JSONObject((Map<?,?>)x)).toString();
                }
                if (x instanceof Collection) {
                    return renderSimpleCanonicalJSON(new JSONArray((Collection<?>)x)).toString();
                }
                if (x.getClass().isArray()) {
View Full Code Here

    this.goalValues = new ArrayList<Integer>();
  }

  public Match(String theJSON, Game theGame, String authToken) throws JSONException, SymbolFormatException, GdlFormatException {
        JSONObject theMatchObject = new JSONObject(theJSON);

        this.matchId = theMatchObject.getString("matchId");
        this.startClock = theMatchObject.getInt("startClock");
        this.playClock = theMatchObject.getInt("playClock");
        if (theGame == null) {
            this.theGame = RemoteGameRepository.loadSingleGame(theMatchObject.getString("gameMetaURL"));
            if (this.theGame == null) {
                throw new RuntimeException("Could not find metadata for game referenced in Match object: " + theMatchObject.getString("gameMetaURL"));
            }
        } else {
            this.theGame = theGame;
        }

        if (theMatchObject.has("previewClock")) {
          this.previewClock = theMatchObject.getInt("previewClock");
        } else {
          this.previewClock = -1;
        }

        this.startTime = new Date(theMatchObject.getLong("startTime"));
        this.randomToken = theMatchObject.getString("randomToken");
        this.spectatorAuthToken = authToken;
        this.isCompleted = theMatchObject.getBoolean("isCompleted");
        if (theMatchObject.has("isAborted")) {
          this.isAborted = theMatchObject.getBoolean("isAborted");
        } else {
          this.isAborted = false;
        }

        this.numRoles = Role.computeRoles(this.theGame.getRules()).size();

        this.moveHistory = new ArrayList<List<GdlTerm>>();
        this.stateHistory = new ArrayList<Set<GdlSentence>>();
        this.stateTimeHistory = new ArrayList<Date>();
        this.errorHistory = new ArrayList<List<String>>();

        JSONArray theMoves = theMatchObject.getJSONArray("moves");
        for (int i = 0; i < theMoves.length(); i++) {
            List<GdlTerm> theMove = new ArrayList<GdlTerm>();
            JSONArray moveElements = theMoves.getJSONArray(i);
            for (int j = 0; j < moveElements.length(); j++) {
                theMove.add(GdlFactory.createTerm(moveElements.getString(j)));
            }
            moveHistory.add(theMove);
        }
        JSONArray theStates = theMatchObject.getJSONArray("states");
        for (int i = 0; i < theStates.length(); i++) {
            Set<GdlSentence> theState = new HashSet<GdlSentence>();
            SymbolList stateElements = (SymbolList) SymbolFactory.create(theStates.getString(i));
            for (int j = 0; j < stateElements.size(); j++)
            {
                theState.add((GdlSentence)GdlFactory.create("( true " + stateElements.get(j).toString() + " )"));
            }
            stateHistory.add(theState);
        }
        JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes");
        for (int i = 0; i < theStateTimes.length(); i++) {
            this.stateTimeHistory.add(new Date(theStateTimes.getLong(i)));
        }
        if (theMatchObject.has("errors")) {
            JSONArray theErrors = theMatchObject.getJSONArray("errors");
            for (int i = 0; i < theErrors.length(); i++) {
                List<String> theMoveErrors = new ArrayList<String>();
                JSONArray errorElements = theErrors.getJSONArray(i);
                for (int j = 0; j < errorElements.length(); j++)
                {
                    theMoveErrors.add(errorElements.getString(j));
                }
                errorHistory.add(theMoveErrors);
            }
        }

        this.goalValues = new ArrayList<Integer>();
        try {
            JSONArray theGoalValues = theMatchObject.getJSONArray("goalValues");
            for (int i = 0; i < theGoalValues.length(); i++) {
                this.goalValues.add(theGoalValues.getInt(i));
            }
        } catch (JSONException e) {}

        // TODO: Add a way to recover cryptographic public keys and signatures.
        // Or, perhaps loading a match into memory for editing should strip those?

        if (theMatchObject.has("playerNamesFromHost")) {
            thePlayerNamesFromHost = new ArrayList<String>();
            JSONArray thePlayerNames = theMatchObject.getJSONArray("playerNamesFromHost");
            for (int i = 0; i < thePlayerNames.length(); i++) {
                thePlayerNamesFromHost.add(thePlayerNames.getString(i));
            }
        }
        if (theMatchObject.has("isPlayerHuman")) {
          isPlayerHuman = new ArrayList<Boolean>();
            JSONArray isPlayerHumanArray = theMatchObject.getJSONArray("isPlayerHuman");
            for (int i = 0; i < isPlayerHumanArray.length(); i++) {
              isPlayerHuman.add(isPlayerHumanArray.getBoolean(i));
            }
        }
  }
View Full Code Here

TOP

Related Classes of external.JSON.JSONObject

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.