示例#1
0
 @Override
 protected void onPostExecute(String result) {
   if (result != null) {
     try {
       Gson gson = new Gson();
       Log.i("Game JSON", result);
       gameActivePlayerWrapper = gson.fromJson(result, GameActivePlayerWrapper.class);
       if (gameActivePlayerWrapper.activePlayerId
           == gameActivePlayerWrapper.game.player1.playerId) {
         player = gameActivePlayerWrapper.game.player1;
         firstPLayer = true;
       } else {
         player = gameActivePlayerWrapper.game.player2;
         firstPLayer = false;
       }
       gameStarted = true;
       startGame();
     } catch (JsonParseException e) {
       e.printStackTrace();
     }
   } else {
     Toast.makeText(GameActivity.this, getString(R.string.game_not_found), Toast.LENGTH_SHORT)
         .show();
   }
 }
 @Override
 public void onHttpResponseResultStatus(int type, int result, String value) {
   if (result == HttpConfig.HTTP_SUCCESS) {
     try {
       HttpResponseVo responseVo = new Gson().fromJson(value, HttpResponseVo.class);
       int resultNum = Integer.parseInt(responseVo.getResult());
       if (resultNum == HttpConfig.HTTP_SUCCESS) {
         UserVo userVo = new Gson().fromJson(responseVo.getJsonStr(), UserVo.class);
         if (userVo != null) {
           Toast.makeText(mContext, userVo.getUserName() + "님 회원가입을 축하드립니다!", Toast.LENGTH_SHORT)
               .show();
           mCallbacks.onMembershipResult(userVo);
           dismiss();
         }
       } else {
         Toast.makeText(mContext, "회원가입에 실패하였습니다", Toast.LENGTH_SHORT).show();
       }
     } catch (JsonParseException jpe) {
       jpe.printStackTrace();
     } catch (NumberFormatException nfe) {
       nfe.printStackTrace();
     }
   } else {
     Toast.makeText(mContext, "서버 연결에 실패하였습니다.", Toast.LENGTH_SHORT).show();
   }
 }
  public static WrappedStack createFromJson(String jsonWrappedObject) throws JsonParseException {
    try {
      return jsonSerializer.fromJson(jsonWrappedObject, WrappedStack.class);
    } catch (JsonSyntaxException exception) {
      exception.printStackTrace();
    } catch (JsonParseException exception) {
      exception.printStackTrace();
    }

    return null;
  }
  public static WrappedStack createFromJson(String jsonWrappedObject) throws JsonParseException {
    try {
      return gsonSerializer.fromJson(jsonWrappedObject, WrappedStack.class);
    } catch (JsonSyntaxException exception) {
      LogHelper.severe(exception.getMessage());
    } catch (JsonParseException exception) {
      LogHelper.severe(exception.getMessage());
    }

    return null;
  }
  /**
   * Deserializes an EmcValue object from the given serialized json String
   *
   * @param jsonEnergyValue Json encoded String representing a EmcValue object
   * @return The EmcValue that was encoded as json, or null if a valid EmcValue could not be decoded
   *     from given String
   */
  @SuppressWarnings("unused")
  public static EnergyValue createFromJson(String jsonEnergyValue) {
    try {
      return jsonSerializer.fromJson(jsonEnergyValue, EnergyValue.class);
    } catch (JsonSyntaxException exception) {
      exception.printStackTrace();
    } catch (JsonParseException exception) {
      exception.printStackTrace();
    }

    return null;
  }
示例#6
0
  @Override
  protected StoredDocumentList process(DocumentQuery query) {
    String q = queryConverter.convert(query.getQuery());

    try {
      URI uri =
          new URI(
              "http",
              "www.mendeley.com",
              "/oapi/documents/search/" + q,
              "consumer_key=" + CONSUMER_KEY + "&items=" + MAX_RESULTS,
              null);
      String json = getNet().read(uri, "UTF-8");
      MendeleySearchResult searchResult = gson.fromJson(json, MendeleySearchResult.class);

      if (searchResult != null) {
        Filter filter = new Filter(query);
        StoredDocumentList result = new StoredDocumentList();
        MendeleyDoc[] documents = searchResult.getDocuments();
        if (documents != null) {
          for (MendeleyDoc md : documents) {
            Document document = new TextDocument();
            document.setTitle(md.getTitle());
            document.setYear(md.getYear());
            document.addDetailURL(new URL(md.getMendeleyUrl()));
            document.setFieldValue(Field.DOI, md.getDoi());
            PersonList pl = new PersonList();
            pl.add(new Person(md.getAuthors()));
            document.setAuthorList(pl);

            if (filter.check(document)) {
              StoredDocument stored = new StoredDocument(document);
              stored.addSource(new SourceInfo(SOURCE_ID, md.getUuid()));
              result.add(stored);
            }
          }
        }
        return result;
      } else {
        return null;
      }

    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      return null;
    } catch (JsonParseException e) {
      logger.error(e.getMessage(), e);
      return null;
    } catch (URISyntaxException e) {
      logger.error(e.getMessage(), e);
      return null;
    }
  }
  // ---------------- HTTP REQUEST RESULT ----------------
  @Override
  public void onPopularMoviesJsonReceived(String json) {
    UtilParser movieParser = new UtilParser();

    try {
      movies = movieParser.jsonParserMovies(json);
    } catch (JsonParseException e) {
      e.printStackTrace();
    }

    Log.d(LOG_DEBUG, "DOWNLOADED & PARSED MOVIES");

    updateData();
  }
示例#8
0
 @Override
 protected void onPostExecute(String result) {
   if (result != null) {
     try {
       Gson gson = new Gson();
       RevisionListViewModel revisionListViewModel =
           gson.fromJson(result, RevisionListViewModel.class);
       revisions = revisionListViewModel.revisions;
       gameStarted = true;
       startGame();
     } catch (JsonParseException e) {
       e.printStackTrace();
     }
   }
 }
示例#9
0
 @Override
 public void onResponse(final Response response) throws IOException {
   try {
     final int statusCode = response.code();
     final String responseString = response.body().string();
     T t = parse(responseString);
     sendOnSuccessMessage(statusCode, t);
   } catch (final IOException e) {
     sendOnErrorMessage(response.request(), e);
     e.printStackTrace();
   } catch (final JsonParseException e) {
     sendOnErrorMessage(response.request(), new JsonParseException("parse failure"));
     e.printStackTrace();
   }
 }
示例#10
0
 @Override
 protected void onPostExecute(String result) {
   if (result != null) {
     try {
       Gson gson = new Gson();
       spaceCrackMap = gson.fromJson(result, SpaceCrackMap.class);
       for (Planet planet : spaceCrackMap.planets) {
         planets.put(planet.name, planet);
       }
       mapLoaded = true;
       startGame();
     } catch (JsonParseException e) {
       e.printStackTrace();
     }
   }
 }
 public static Object deserialize(String json, String containerType, Class cls)
     throws ApiException {
   try {
     if ("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
       return JsonUtil.deserializeToList(json, cls);
     } else if (String.class.equals(cls)) {
       if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
         return json.substring(1, json.length() - 1);
       else return json;
     } else {
       return JsonUtil.deserializeToObject(json, cls);
     }
   } catch (JsonParseException e) {
     throw new ApiException(500, e.getMessage());
   }
 }
  @Override
  public void onMovieDetailsReceived(String[] jsons) {
    try {
      mSelectedMovieReviews = new UtilParser().jsonParserReviews(jsons[0]);
      mSelectedMovieTrailers = new UtilParser().jsonParserTrailers(jsons[1]);
    } catch (JsonParseException e) {
      e.printStackTrace();
    }

    Log.d(LOG_DEBUG, "DOWNLOADED & PARSED MOVIES REVIEWS & TRAILERS");
    if (!mTwoPane) {
      Intent detailIntent = new Intent(this, ActivityDetail.class);
      detailIntent.putExtra(Utilities.INTENT_MOVIE_KEY, selectedMovie);
      startActivity(detailIntent);
    } else updateMovieDetails();
  }
示例#13
0
 private CIJob getJob(ApplicationInfo appInfo) throws PhrescoException {
   Gson gson = new Gson();
   try {
     BufferedReader br = new BufferedReader(new FileReader(getCIJobPath(appInfo)));
     CIJob job = gson.fromJson(br, CIJob.class);
     br.close();
     return job;
   } catch (FileNotFoundException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   } catch (com.google.gson.JsonParseException e) {
     S_LOGGER.debug("it is already adpted project !!!!! " + e.getLocalizedMessage());
     return null;
   } catch (IOException e) {
     S_LOGGER.debug(e.getLocalizedMessage());
     return null;
   }
 }
示例#14
0
 public static <R> R parseJson(okhttp3.Response response, Type bodyType)
     throws HasuraJsonException {
   int code = response.code();
   try {
     String rawBody = response.body().string();
     System.out.println(rawBody);
     return gson.fromJson(rawBody, bodyType);
   } catch (JsonSyntaxException e) {
     String msg =
         "FATAL : JSON strucutre not as expected. Schema changed maybe? : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (JsonParseException e) {
     String msg = "FATAL : Server didn't return vaild JSON : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (IOException e) {
     String msg = "FATAL : Decoding response body failed : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   }
 }
示例#15
0
  @Override
  public void askDetails(StoredDocumentList incomplete) {
    for (StoredDocument stored : incomplete) {
      String id = getDetailInfo(stored);
      if (id != null) {
        try {
          URI uri =
              new URI(
                  "http",
                  "www.mendeley.com",
                  "/oapi/documents/details/" + id,
                  "consumer_key=" + CONSUMER_KEY,
                  null);

          String json = getNet().read(uri, "UTF-8");
          json = json.replace("\"abstract\":", "\"abstrakt\":");
          MendeleyDocDetails docDetails = gson.fromJson(json, MendeleyDocDetails.class);

          if (docDetails != null) {
            Document document = stored.getDocument();
            String abstrakt = docDetails.getAbstrakt();
            if (abstrakt != null) {
              document.setFieldValue(Field.ABSTRACT, abstrakt);
            }
            String pages = docDetails.getPages();
            if (pages != null) {
              document.setFieldValue(Field.PAGES, pages);
            }
            String volume = docDetails.getVolume();
            if (volume != null) {
              document.setFieldValue(Field.VOLUME, volume);
            }
          }

          setDetailTimestampToCurrent(stored);
        } catch (JsonParseException e) {
          logger.error(e.getMessage(), e);
        } catch (URISyntaxException e) {
          logger.error(e.getMessage(), e);
        }
      }
    }
  }
示例#16
0
 @Override
 public JsonElement next() throws JsonParseException {
   if (!this.hasNext()) {
     throw new NoSuchElementException();
   }
   try {
     JsonElement jsonElement = Streams.parse(this.parser);
     return jsonElement;
   } catch (StackOverflowError var1_2) {
     throw new JsonParseException("Failed parsing JSON source to Json", var1_2);
   } catch (OutOfMemoryError var1_3) {
     throw new JsonParseException("Failed parsing JSON source to Json", var1_3);
   } catch (JsonParseException var2_5) {
     RuntimeException runtimeException = var2_5;
     if (var2_5.getCause() instanceof EOFException) {
       runtimeException = new NoSuchElementException();
     }
     throw runtimeException;
   }
 }
  /**
   * Retrieves the AuthorizationInfo for the given principals (the CAS previously authenticated user
   * : id + attributes).
   *
   * @param principals the primary identifying principals of the AuthorizationInfo that should be
   *     retrieved.
   * @return the AuthorizationInfo associated with this principals.
   */
  @Override
  @SuppressWarnings("unchecked")
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // retrieve user information
    SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
    List<Object> listPrincipals = principalCollection.asList();
    Map<String, String> attributes = (Map<String, String>) listPrincipals.get(1);
    String authorityStr = attributes.get("authority");
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    try {
      String username = URLDecoder.decode(attributes.get("username"), "UTF-8");
      if ("admin".equals(username)) {
        simpleAuthorizationInfo.addRole("admin");
      }
      if (authorityStr != null) {
        ObjectMapper objectMapper = new ObjectMapper();
        authorityStr = java.net.URLDecoder.decode(authorityStr, "UTF-8").replace("&#034;", "\"");
        List<Map<String, Object>> authorityList = objectMapper.readValue(authorityStr, List.class);
        for (Map<String, Object> auth : authorityList) {
          String appCode = auth.get("appCode").toString();
          if (simpleAuthorizationInfo.getRoles() == null) {
            simpleAuthorizationInfo.addRole(appCode);
          } else if (!simpleAuthorizationInfo.getRoles().contains(appCode)) {
            simpleAuthorizationInfo.addRole(appCode);
          }

          simpleAuthorizationInfo.addStringPermission(appCode + ":" + auth.get("url").toString());
          //						simpleAuthorizationInfo.addRole(auth.get("role").toString());
        }
      }
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return simpleAuthorizationInfo;
  }
示例#18
0
 private OAuthAccessToken parseJsonToken(HttpMessage response) {
   com.google.gson.JsonObject root = new com.google.gson.JsonObject();
   com.google.gson.JsonParseException pe = null;
   try {
     root =
         (com.google.gson.JsonObject) new com.google.gson.JsonParser().parse(response.getBody());
   } catch (com.google.gson.JsonParseException error) {
     pe = error;
   }
   boolean ok = root != null;
   if (!ok) {
     logger.error(
         new StringWriter().append("parseJsonToken(): ").append(pe.toString()).toString());
     throw new OAuthProcess.TokenError(WString.tr("Wt.Auth.OAuthService.badjson"));
   } else {
     if (response.getStatus() == 200) {
       try {
         String accessToken = root.get("access_token").getAsString();
         int secs = JsonUtils.orIfNullInt(root.get("expires_in"), -1);
         WDate expires = null;
         if (secs > 0) {
           expires = new WDate(new Date()).addSeconds(secs);
         }
         String refreshToken = JsonUtils.orIfNullString(root.get("refreshToken"), "");
         return new OAuthAccessToken(accessToken, expires, refreshToken);
       } catch (RuntimeException e) {
         logger.error(
             new StringWriter().append("token response error: ").append(e.toString()).toString());
         throw new OAuthProcess.TokenError(WString.tr("Wt.Auth.OAuthService.badresponse"));
       }
     } else {
       throw new OAuthProcess.TokenError(
           WString.tr(
               "Wt.Auth.OAuthService."
                   + JsonUtils.orIfNullString(root.get("error"), "missing error")));
     }
   }
 }
 /**
  * Create exception from {@link JsonParseException}
  *
  * @param cause
  */
 public JsonException(final JsonParseException cause) {
   super(cause.getMessage());
   initCause(cause);
 }