Example #1
0
 private String unPack(String json, String key) {
   try {
     JSONParser jsonParser = new JSONParser();
     JSONObject jsonObject = (JSONObject) jsonParser.parse(json);
     String command = (String) jsonObject.get(key);
     return command;
   } catch (ParseException e) {
     System.err.println("Blad PARSOWANIA!" + e.getMessage());
   }
   return "error";
 }
Example #2
0
 /**
  * レスポンスボディをJSONで取得.
  *
  * @return JSONオブジェクト
  */
 public JSONObject bodyAsJson() {
   String res = null;
   res = this.bodyWriter.toString();
   JSONObject jsonobject = null;
   try {
     jsonobject = (JSONObject) new JSONParser().parse(res);
   } catch (ParseException e) {
     fail(e.getMessage());
   }
   return jsonobject;
 }
Example #3
0
 /**
  * Checks whether or not the message has been parsed to JSON and if the JSON is invalid.
  *
  * <p>
  *
  * <p>This is mainly used for the send methods to check whether to send a JSON message or regular
  * message.
  *
  * <p>
  *
  * <p>If there is a JSON message but it's invalid an error will be sent to the console! It will
  * fallback to regular messages when the JSON fails for display methods.
  *
  * @return True when there is a valid JSON message and false if not.
  */
 public boolean isValidJSON() {
   if (json == null || json.isEmpty()) {
     toJSON();
   }
   try {
     JSONParser parser = new JSONParser();
     parser.parse(json);
     return true;
   } catch (ParseException e) {
     HelpBot.get()
         .error("Invalid JSON found for the message '" + original + "'! Error: " + e.getMessage());
   } catch (Exception e) {
   }
   return false;
 }
  @Override
  protected void onPostExecute(String result) {
    super.onPostExecute(result);
    System.out.println("############### " + result);
    JSONObject jsonObject = null;
    if (result != null && !result.trim().equals("")) {

      try {
        jsonObject = (JSONObject) new JSONParser().parse(result);
      } catch (ParseException e) {

        throw new RuntimeException(e.getMessage());
      }
    }
    listener.onExecutionComplete(jsonObject);
  }
  private void restoreFromFile() throws IOException {
    JSONParser parser = new JSONParser();
    try {
      json = (JSONObject) parser.parse(new FileReader(JSON_FILE));
      restoreDispatchers();
      restoreLocations();
      restoreVehicleTypes();
      restoreIncidentTypes();
      restoreReporters();
      restoreVehicles();
      restoreIncidents();

    } catch (ParseException e) {
      throw new IOException(e.getMessage(), e);
    }
  }
 public void TryFinderClass(String str, String matchKey) {
   // String jsonText = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\":
   // 123}], \"third\": 789, \"id\": null}";
   String jsonText = str;
   JSONParser parser = new JSONParser();
   KeyFinder finder = new KeyFinder();
   // finder.setMatchKey("id");
   finder.setMatchKey(matchKey);
   try {
     while (!finder.isEnd()) {
       parser.parse(jsonText, finder, true);
       if (finder.isFound()) {
         finder.setFound(false);
         System.out.println(matchKey + " found:");
         System.out.println(finder.getValue());
       }
     }
   } catch (ParseException pe) {
     System.out.println(pe.getMessage());
   }
 }
Example #7
0
 /**
  * Add id and revision to the content of a given request
  *
  * @param request the given request
  * @param id the id to add
  * @param revision the revision to add
  * @return the modified request
  */
 public static Request addIdAndRevisionToContent(Request request, String id, String revision) {
   JSONParser parser = new JSONParser();
   try {
     JSONObject jsonObject = (JSONObject) parser.parse((String) request.getContent());
     jsonObject.put("_id", id);
     jsonObject.put("_rev", revision);
     String jsonString = jsonObject.toJSONString();
     log.info("Updated Request content with id and rev: " + jsonString);
     return new Request.Builder(
             request.getProtocolType(),
             request.getRequestType(),
             request.getUrl(),
             request.getHost(),
             request.getPort())
         .contentType(request.getContentType())
         .content(jsonString)
         .build();
   } catch (ParseException e) {
     throw new DatastoreException("Error parsing JSON to add revision: " + e.getMessage());
   }
 }
Example #8
0
  /**
   * Allows to send a POST request, with parameters using JSON format
   *
   * @param path path to be used for the POST request
   * @param data paremeters to be used (JSON format) as a string
   */
  @SuppressWarnings("unchecked")
  public void sendPost(final String path, final String data) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;

    log.info("Sending POST request to " + fullpath);
    final PostMethod method = new PostMethod(fullpath);
    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
      method.setRequestHeader(header.getKey(), header.getValue());
    if (data != null) {
      JSONObject jsonObject = null;
      try {
        jsonObject = JSONHelper.toJSONObject(data);
        for (final Iterator<String> iterator = jsonObject.keySet().iterator();
            iterator.hasNext(); ) {
          final String param = iterator.next();
          method.setParameter(
              param, (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
        }
      } catch (final ParseException e) {
        log.error("Sorry, parameters are not proper JSON...", e);
        throw new IOException(e.getMessage(), e);
      }
    }
    try {
      final int statusCode = httpClient.executeMethod(method);
      response =
          new ResponseWrapper(
              method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode);
    } catch (final IOException e) {
      log.error(e.getMessage(), e);
      throw new IOException(e.getMessage(), e);
    } finally {
      method.releaseConnection();
    }
  }
  /** JSON */
  public void readJSON(String message) {
    /* création des objets JSONObject et JSONParser */
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = null;
    try {
      jsonObject = (JSONObject) parser.parse(message);

      /* Creation d'une nouvelle areas */
      //	    	this.areas = new HashMap<String, Areas>();
      //	        for (JSONObject o: (ArrayList<JSONObject>) jsonObject.get("areas")){
      //	        	this.areas.put((String)o.get("name"), new Areas());
      //	        }

      /* création d'une liste d'objet JSON contenant les paramètres de la trame JSON ("areas") */
      JSONArray areas = (JSONArray) jsonObject.get("areas");
      Iterator ite_areas = areas.iterator();

      /* Name */
      while (ite_areas.hasNext()) {
        JSONObject obj1 = (JSONObject) ite_areas.next();
        /* Map */
        JSONObject map = (JSONObject) obj1.get("map");
        System.out.println(map);
        /* Weight */
        JSONObject weight = (JSONObject) map.get("weight");

        /* Obtient les valeurs de w et h */
        Collection col_weight = weight.values();
        Iterator i = col_weight.iterator();
        System.out.println(i.next());

        //                for( Object obj: col_weight) {
        //                    /* création d'une liste d'objets JSON contenant les objets de la
        // collection */
        //                    ArrayList<JSONObject> keyl = (ArrayList<JSONObject>) obj;
        ////                    System.out.println(keyl.get(0));
        //                }
        /* Vertices */
        JSONArray vertices = (JSONArray) map.get("vertices");
        //                System.out.println(vertices);
        //                Iterator ite_vertices = vertices.iterator();
        //                JSONObject obj2 = (JSONObject) ite_vertices.next();
        //
        //                /* recupere le X et le Y des differents points */
        //                for(int i=0 ;i<vertices.size() ;i++){
        //                	for(int j=0; j<vertices.size();j++){
        //                		tab[i][j] = (double) obj2.get("x");
        //                		j++;
        //                		tab[i][j] = (double) obj2.get("y");
        //                	}
        //                }

        /* Streets */
        //                JSONArray streets = (JSONArray) jsonObject.get("streets");
        //                Iterator ite_streets = streets.iterator();
        //                /* Bridges */
        //                JSONArray bridges = (JSONArray) jsonObject.get("bridges");
        //                Iterator ite_bridges = bridges.iterator();

        /* Weight, Vertices, Streets and Bridges */
        //              Iterator ite_map = map.iterator();
        //              while (ite_map.hasNext()){
        //              	JSONObject Obj2 = (JSONObject) ite_map.next();
        //                  JSONArray weight = (JSONArray) Obj2.get("weight");
        //                  JSONArray vertices = (JSONArray) Obj2.get("vertices");
        //                  JSONArray streets = (JSONArray) Obj2.get("streets");
        //                  JSONArray bridges = (JSONArray) Obj2.get("bridges");

      }

      /** *************VERSION FONCTIONNELLE******************* */
      //		    for(JSONObject a: liste){
      //	            /* on "isole" le contenu des objets dans une collection */
      //	          	Collection names = a.values();
      //			    System.out.println("names: " + names + "\n");
      //			    // get an array from the JSON object
      //
      //	        }
      //            System.out.println("liste: " + liste + "\n");
      //            for(JSONObject a: liste){
      //                /* on "isole" le contenu des objets dans une collection */
      //            	Collection names = a.values();
      //                System.out.println("names: " + names + "\n");
      //                /* pour tous les objets de la collection */
      //                for(Object obj: names) {
      //                	Iterator itNames = names.iterator();
      //                }
      //            }
      /** ***************************************************** */
    } catch (org.json.simple.parser.ParseException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
    }
  }
Example #10
0
  void guess(String m) {
    try {
      String ownerGuessedCard = unPack(m, "ownerGuessedCard");
      int[] playerTriedGuess = {-1, -1};
      JSONParser jsonParser = new JSONParser();
      JSONObject jsonObject = (JSONObject) jsonParser.parse(m);
      JSONArray arr = (JSONArray) jsonObject.get("playerTriedGuess");
      playerTriedGuess[0] = Integer.parseInt(arr.get(0).toString());
      if (arr.get(1) != null) playerTriedGuess[1] = Integer.parseInt(arr.get(1).toString());
      // System.out.println(playerTriedGuess[0] + "  --  " + playerTriedGuess[1]);
      Integer cardName = Integer.parseInt(unPack(m, "cardName"));
      String myName = unPack(m, "myName");
      String state = unPack(m, "state");
      int cardOlder = whichThisCardIs(ownerGuessedCard, cardName);
      int numberOfVisible = gamers.get(whoIs(ownerGuessedCard)).numberOfVisible;
      System.out.println("numberOfVisible " + numberOfVisible);
      int pointsForYou = 3;
      if (numberOfVisible == 9) pointsForYou = 2;
      if (numberOfVisible == 10) pointsForYou = 1;
      Boolean isVisible = false;
      if (state.equals("ONE_TRY_FAIL_ANS")) {
        pointsForYou = 0;
        isVisible = false;
        feedback(
            "Gracz_"
                + myName
                + "_�le_typowa�_karte_"
                + cardOlder
                + "_gracza_"
                + ownerGuessedCard
                + "_jako_karte_"
                + playerTriedGuess[0]);
      }
      if (state.equals("TWO_TRY_FAIL_ANS")) {
        if (playerTriedGuess[1] == -1) {
          whoseTourn += 4;
          whoseTourn %= 3;
          return;
        }
        pointsForYou = -1;
        isVisible = false;
        feedback(
            "Gracz_"
                + myName
                + "_�le_typowa�_karte_"
                + cardOlder
                + "_gracza_"
                + ownerGuessedCard
                + "_jako_karty_"
                + playerTriedGuess[0]
                + "_i_"
                + playerTriedGuess[1]);
      }
      if (state.equals("ONE_TRY_GOOD_ANS")) {
        gamers.get(whoIs(ownerGuessedCard)).numberOfVisible++;
        isVisible = true;
        feedback(
            "Gracz_"
                + myName
                + "_poprawnie_zgad�_karte_"
                + cardOlder
                + "_gracza_"
                + ownerGuessedCard
                + "_kt�ra_mia�a_warto��_"
                + playerTriedGuess[0]);
      }
      if (state.equals("TWO_TRY_GOOD_ANS")) {
        gamers.get(whoIs(ownerGuessedCard)).numberOfVisible++;
        pointsForYou -= 1;
        isVisible = true;
        feedback(
            "Gracz_"
                + myName
                + "_�le_typowa�_karte_"
                + cardOlder
                + "_gracza_"
                + ownerGuessedCard
                + "_jako_karte_"
                + playerTriedGuess[0]
                + "_ale_poprawi�_odpowiedz_na_"
                + playerTriedGuess[1]);
      }
      getHimPoints(myName, pointsForYou);
      JSONObject json = new JSONObject();
      json.put("type", "cardGuess");
      json.put("WhoTryGuess", myName);
      json.put("isVisible", isVisible);
      Integer i = pointsForYou;
      json.put("addPointForPlayer", i.toString());
      json.put("cardName", cardName.toString());
      broadcast(json.toJSONString());

    } catch (ParseException pe) {
      System.err.println("Blad PARSOWANIA!" + pe.getMessage());
    }
  }
Example #11
0
  @Override
  public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

    KeyManagerConfiguration config =
        KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(OAuthTwoConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(OAuthTwoConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(OAuthTwoConstants.INTROSPECTION_CS);
    String encodedSecret =
        Base64.encode(
            new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
      URIBuilder uriBuilder = new URIBuilder(introspectionURL);
      uriBuilder.addParameter("access_token", accessToken);
      uriBuilder.build();

      HttpGet httpGet = new HttpGet(uriBuilder.build());
      HttpClient client = new DefaultHttpClient();

      httpGet.setHeader("Authorization", "Basic " + encodedSecret);
      HttpResponse response = client.execute(httpGet);
      int responseCode = response.getStatusLine().getStatusCode();

      LOGGER.log(Level.INFO, "HTTP Response code : " + responseCode);

      // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
      // "attributes":{}},"expires_in":1433059160531}
      HttpEntity entity = response.getEntity();
      JSONObject parsedObject;
      String errorMessage = null;
      reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

      if (HttpStatus.SC_OK == responseCode) {
        // pass bufferReader object and get read it and retrieve the
        // parsedJson object
        parsedObject = getParsedObjectByReader(reader);
        if (parsedObject != null) {

          Map valueMap = parsedObject;
          Object principal = valueMap.get("principal");

          if (principal == null) {
            tokenInfo.setTokenValid(false);
            return tokenInfo;
          }
          Map principalMap = (Map) principal;
          String clientId = (String) principalMap.get("clientId");
          Long expiryTimeString = (Long) valueMap.get("expires_in");
          String endUserName = (String) principalMap.get("name");

          LOGGER.log(
              Level.INFO,
              "OAuthTwoClient - clientId:" + clientId + " expires_in:" + expiryTimeString);

          // Returning false if mandatory attributes are missing.
          if (clientId == null || expiryTimeString == null) {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
            return tokenInfo;
          }

          long currentTime = System.currentTimeMillis();
          long expiryTime = expiryTimeString;
          if (expiryTime > currentTime) {
            tokenInfo.setTokenValid(true);
            tokenInfo.setConsumerKey(clientId);
            tokenInfo.setValidityPeriod(expiryTime - currentTime);
            // Considering Current Time as the issued time.
            tokenInfo.setIssuedTime(currentTime);
            tokenInfo.setEndUserName(endUserName);
            tokenInfo.setAccessToken(accessToken);
            //			tokenInfo.

            JSONArray scopesArray = (JSONArray) valueMap.get("scopes");

            if (scopesArray != null && !scopesArray.isEmpty()) {

              String[] scopes = new String[scopesArray.size()];
              for (int i = 0; i < scopes.length; i++) {
                scopes[i] = (String) scopesArray.get(i);
              }
              tokenInfo.setScope(scopes);
            }
          } else {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
          }

        } else {
          LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
          tokenInfo.setTokenValid(false);
          tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
          return tokenInfo;
        }
      } // for other HTTP error codes we just pass generic message.
      else {
        LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
        tokenInfo.setTokenValid(false);
        tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
        return tokenInfo;
      }

    } catch (UnsupportedEncodingException e) {
      handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
      handleException(
          "HTTP request error has occurred while sending request  to OAuth Provider. "
              + e.getMessage(),
          e);
    } catch (IOException e) {
      handleException(
          "Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
      handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
      handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(reader);
    }
    LOGGER.log(
        Level.INFO,
        "OAuthTwoClient - getTokenMetada - return SUCCESSFULY" + tokenInfo.getJSONString());

    return tokenInfo;
  }