public List<Team> loadUserTeams(List<YahooLeague> ylList) {

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> userData;
    Map<String, Object> results;
    List<Map<String, Object>> teamList;
    Map<String, Object> query;
    List<Team> teamListResults = new LinkedList<Team>();
    for (YahooLeague yl : ylList) {
      String yql =
          "select * from fantasysports.teams where league_key = '" + yl.getLeague_key() + "'";
      String response = yqlUitl.queryYQL(yql);
      try {
        userData = mapper.readValue(response, Map.class);
        query = (Map<String, Object>) userData.get("query"); // query details
        results = (Map<String, Object>) query.get("results"); // result details
        teamList = (List<Map<String, Object>>) results.get("team"); // result details
        for (Map map : teamList) {
          Team tempTeam = mapper.readValue(JacksonPojoMapper.toJson(map, false), Team.class);
          teamListResults.add(tempTeam);
        }

      } catch (Exception e) {
        Logger.getLogger(TeamService.class.getName()).log(Level.SEVERE, null, e);
      }
    }
    return teamListResults;
  }
  public Roster getRoster2(String teamKey, int week) {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> userData;
    Map<String, Object> results;
    Map<String, Object> team;
    Map<String, Object> query;
    Roster rosterResults = null;
    String yql =
        "select * from fantasysports.teams.roster where team_key='"
            + teamKey
            + "' and week='"
            + week
            + "'";
    String response = yqlUitl.queryYQL(yql);
    try {
      userData = mapper.readValue(response, Map.class);
      query = (Map<String, Object>) userData.get("query"); // query details
      results = (Map<String, Object>) query.get("results"); // result details
      team = (Map<String, Object>) results.get("team"); // result details
      Roster roster =
          mapper.readValue(JacksonPojoMapper.toJson((Map) team.get("roster"), false), Roster.class);
      rosterResults = roster;
    } catch (Exception e) {
      Logger.getLogger(TeamService.class.getName()).log(Level.SEVERE, null, e);
    }

    return rosterResults;
  }
Exemplo n.º 3
0
 // both reads and writes - need to be synchronized for consistent data to be written
 public static void deleteWorkflowJob(String workflowJobId) throws IOException {
   String workflowJobPath =
       LoaderServerConfiguration.instance().getJobFSConfig().getWorkflowJobPath(workflowJobId);
   File file = new File(workflowJobPath);
   if (!file.exists())
     throw new RuntimeException("WorkflowJobId " + workflowJobId + " not found.");
   File statusFile =
       new File(
           LoaderServerConfiguration.instance()
               .getJobFSConfig()
               .getWorkflowJobStatusPath(workflowJobId));
   ScheduledWorkFlowJob workflow = objectMapper.readValue(statusFile, ScheduledWorkFlowJob.class);
   FileHelper.deleteRecursively(file);
   File workflowJobsFile =
       new File(
           LoaderServerConfiguration.instance()
               .getJobFSConfig()
               .getScheduledWorkflowJobsFile(workflow.getWorkflowName()));
   synchronized (ScheduledWorkFlowJob.class) {
     ArrayList<String> allWorkflowJobIds =
         objectMapper.readValue(workflowJobsFile, ArrayList.class);
     allWorkflowJobIds.remove(workflowJobId);
     objectMapper.writerWithDefaultPrettyPrinter().writeValue(workflowJobsFile, allWorkflowJobIds);
   }
 }
Exemplo n.º 4
0
    @Override
    protected Integer doInBackground(Void... params) {
      ObjectMapper mapper = new ObjectMapper();
      beans = new ArrayList<TopicsContentBean>();
      try {
        String ncontent =
            NetHttpConnection.httpGet("http://180.168.69.121:8089/webroot" + path, null);
        ncontent = ncontent.replaceAll("\n", "").replaceAll(" ", "");
        TopicsListBean listbean = mapper.readValue(ncontent, TopicsListBean.class);
        for (int i = 0; i < listbean.getData().length; i++) {
          String ncontents =
              NetHttpConnection.httpGet(
                  "http://180.168.69.121:8089/webroot" + listbean.getData()[i].getPath(), null);
          System.out.println("当前内容" + i + ":::" + ncontents.replaceAll("\n", ""));
          ncontents = ncontents.replaceAll("\n", "");
          ncontents = ncontents.replaceAll("\t", "");
          ncontents = ncontents.replaceAll(" ", "");
          TopicsContentBean bean = mapper.readValue(ncontents, TopicsContentBean.class);
          beans.add(bean);
          System.out.println("专题内容页" + i + "::" + ncontents.replaceAll("\n", ""));
        }

        // TopicsBean topbean =
        // mapper.readValue(ncontents.replaceAll("\n", ""),
        // TopicsBean.class);

      } catch (Exception e) {
        e.printStackTrace();
      }

      return 100;
    }
Exemplo n.º 5
0
    private SessionUpdate getSessionUpdateFrom(String message) {
      try {
        switch (connection.getApiLevel()) {
          case v1:
            mapper.configure(Feature.UNWRAP_ROOT_VALUE, false);
            Update update = mapper.readValue(message, Update.class);
            if (update.getType().equals("playing") && update.getChildren().size() > 0) {
              return update.getChildren().get(0);
            }
            break;
          case v2:
            mapper.configure(Feature.UNWRAP_ROOT_VALUE, true);
            NotificationContainer notificationContainer =
                mapper.readValue(message, NotificationContainer.class);
            if (notificationContainer.getStateNotifications().size() > 0) {
              return notificationContainer.getStateNotifications().get(0);
            }
            break;
        }
      } catch (JsonParseException e) {
        logger.error("Error parsing JSON", e);
      } catch (JsonMappingException e) {
        logger.error("Error mapping JSON", e);
      } catch (IOException e) {
        logger.error("An I/O error occured while decoding JSON", e);
      }

      return null;
    }
  @Test
  public void testTemplatePushPayloadSerializer() throws Exception {

    TemplateSelector mergeData =
        TemplateSelector.newBuilder()
            .setTemplateId("id123")
            .addSubstitution("FIRST_NAME", "Prince")
            .addSubstitution("LAST_NAME", "")
            .build();

    TemplatePushPayload payload =
        TemplatePushPayload.newBuilder()
            .setAudience(Selectors.all())
            .setDeviceTypes(DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID))
            .setMergeData(mergeData)
            .build();

    String templatePushPayloadSerialized = MAPPER.writeValueAsString(payload);
    String templatePushPayloadString =
        "{"
            + "\"audience\":\"ALL\","
            + "\"device_types\":[\"ios\",\"android\"],"
            + "\"merge_data\":{"
            + "\"template_id\":\"id123\","
            + "\"substitutions\":{"
            + "\"FIRST_NAME\":\"Prince\","
            + "\"LAST_NAME\":\"\""
            + "}"
            + "}"
            + "}";

    Map<String, Object> expectedMap = MAPPER.readValue(templatePushPayloadString, Map.class);
    Map<String, Object> actualMap = MAPPER.readValue(templatePushPayloadSerialized, Map.class);
    assertEquals(expectedMap, actualMap);
  }
  @Test
  public void testRoom() throws Exception {
    // create room
    WebRequest request =
        new PostMethodWebRequest(
            getCreateUrl(),
            new ByteArrayInputStream(objectMapper.writeValueAsString(baseRoom).getBytes()),
            MediaType.APPLICATION_JSON_VALUE);
    WebResponse response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    Room room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertTrue(room.getId() != 0);
    assertTrue(compare(baseRoom, room, "id"));

    // update room
    baseRoom = room;
    baseRoom.setName("New name");
    request =
        new PutMethodWebRequest(
            getUpdateUrl(),
            new ByteArrayInputStream(objectMapper.writeValueAsString(baseRoom).getBytes()),
            MediaType.APPLICATION_JSON_VALUE);
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertEquals(room, baseRoom);

    // get room
    request = new GetMethodWebRequest(getViewUrl(baseRoom.getId()));
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertEquals(room, baseRoom);

    // remove room
    request =
        new WebRequest(getDeleteUrl(baseRoom.getId())) {

          @Override
          public String getMethod() {
            return RequestMethod.DELETE.toString();
          }
        };
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // check removed
    URL url = new URL(getViewUrl(baseRoom.getId()));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, connection.getResponseCode());
  }
Exemplo n.º 8
0
 /**
  * Retrieve an OAuth 2.0 access token from the RODL response.
  *
  * @param pageParameters page params
  * @param service RODL OAuth service instance
  * @return the access token
  * @throws URISyntaxException the response details contain invalid URIs
  */
 @SuppressWarnings("unused")
 private Token retrieveDlibraAccessToken(PageParameters pageParameters, OAuthService service)
     throws URISyntaxException {
   Token accessToken = null;
   // TODO in the OAuth 2.0 implicit grant flow the access token is sent
   // in URL fragment - how to retrieve it in Wicket?
   if (!pageParameters.get("access_token").isEmpty()
       && !pageParameters.get("token_type").isEmpty()) {
     if (pageParameters.get("token_type").equals("bearer")) {
       accessToken = new Token(pageParameters.get("access_token").toString(), null);
     } else {
       error("Unsupported token type: " + pageParameters.get("token_type").toString());
     }
   } else if (!pageParameters.get("code").isEmpty()) {
     URI uri =
         new URI(
             new DlibraApi().getAccessTokenEndpoint()
                 + "?grant_type=authorization_code&code="
                 + pageParameters.get("code").toString());
     ObjectMapper mapper = new ObjectMapper();
     String body = null;
     try {
       Response response;
       try {
         response = OAuthHelpService.sendRequest(service, Verb.GET, uri);
         body = response.getBody();
         @SuppressWarnings("unchecked")
         Map<String, String> responseData = mapper.readValue(body, Map.class);
         if (responseData.containsKey("access_token") && responseData.containsKey("token_type")) {
           if (responseData.get("token_type").equalsIgnoreCase("bearer")) {
             accessToken = new Token(responseData.get("access_token"), null);
           } else {
             error("Unsupported access token type: " + responseData.get("token_type"));
           }
         } else {
           error("Missing keys from access token endpoint response");
         }
       } catch (OAuthException e) {
         body = e.getResponse().getBody();
         @SuppressWarnings("unchecked")
         Map<String, String> responseData = mapper.readValue(body, Map.class);
         error(
             String.format(
                 "Access token endpoint returned error %s (%s)",
                 responseData.get("error"), responseData.get("error_description")));
       }
     } catch (JsonParseException e) {
       error("Error in parsing access token endpoint response: " + body);
     } catch (JsonMappingException e) {
       error("Error in parsing access token endpoint response: " + body);
     } catch (IOException e) {
       error("Error in parsing access token endpoint response: " + body);
     }
   }
   return accessToken;
 }
Exemplo n.º 9
0
  public static JsonNode enrich(ContentType contentType, ContentNode contentNode)
      throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ObjectNode root = mapper.readValue(contentType.jsonSchema, ObjectNode.class);

    Map<String, Object> values = mapper.readValue(contentNode.getJsonContent(), Map.class);

    enrichFormWithValues(root, 0, values);
    return root;
  }
  public List<Team> loadLeaugeTeams(String leaugeid) {
    List<Team> result = null;
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> userData;
    Map<String, Object> params;
    Map<String, Object> league;
    int curr = 0;

    String response2 =
        conn.requestData(
            "http://fantasysports.yahooapis.com/fantasy/v2/league/"
                + leaugeid
                + "/teams/standings?format=json",
            Verb.GET);
    try {

      userData = mapper.readValue(response2, Map.class);
      params = (Map<String, Object>) userData.get("fantasy_content");
      league =
          ((List<Map<String, Map<String, Object>>>) (params.get("league"))).get(1).get("teams");
      int count;
      count = (Integer) league.get("count");
      while (curr < count) {
        List<Object> lmpTeams =
            (List<Object>)
                (((Map<String, List<Object>>) league.get((new Integer(curr)).toString()))
                    .get("team")
                    .get(0));
        Team tempTeam = convertToTeam(lmpTeams);
        if (result == null) {
          result = new LinkedList<Team>();
        }
        // tempTeam = loadTeamStandings(tempTeam);
        Map<String, Map> ts =
            (Map<String, Map>)
                ((Map<String, List<Object>>) league.get((new Integer(curr)).toString()))
                    .get("team")
                    .get(1);
        TeamStandings tempStand =
            mapper.readValue(
                JacksonPojoMapper.toJson(ts.get("team_standings"), false), TeamStandings.class);
        tempTeam.setStandings(tempStand);
        result.add(tempTeam);
        curr++;
      }

    } catch (IOException ex) {
      Logger.getLogger(TeamService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
  }
Exemplo n.º 11
0
  private Project getProject(JsonNode root) {
    if (root == null) return null;
    Project project = null;
    try {
      project = new Project();

      JsonNode attribute = root.get(SESSIONSSIZE);
      project.setSessionsSize(attribute.getValueAsInt());

      attribute = root.get(SURVEYSSIZE);
      project.setSurveysSize(attribute.getValueAsInt());

      attribute = root.get(SESSIONS);
      Map<String, JsonNode> map =
          mapper.readValue(attribute, new TypeReference<Map<String, JsonNode>>() {});

      JsonSession jsonSession = new JsonSession(mapper);
      Map<String, Session> sessions = new HashMap<String, Session>(map.size());
      for (Entry<String, JsonNode> entry : map.entrySet()) {
        sessions.put(entry.getKey(), jsonSession.toSession(entry.getValue()));
      }
      project.setSessions(sessions);

      if (project.getSurveysSize() > 0) {
        attribute = root.get(SURVEYS);
        map = mapper.readValue(attribute, new TypeReference<Map<String, JsonNode>>() {});

        JsonSurvey jsonSurvey = new JsonSurvey(mapper);
        Map<String, Survey> surveys = new HashMap<String, Survey>(map.size());
        for (Entry<String, JsonNode> entry : map.entrySet()) {
          surveys.put(entry.getKey(), jsonSurvey.toSurvey(entry.getValue()));
        }
        project.setSurveys(surveys);
      } else {
        project.setSurveys(new HashMap<String, Survey>());
      }

    } catch (JsonParseException e) {
      Log.e(getClass().getName(), "Parsing JSON file failed", e);
      return null;
    } catch (JsonMappingException e) {
      Log.e(getClass().getName(), "Mapping JSON file failed", e);
      return null;
    } catch (IOException e) {
      Log.e(getClass().getName(), "Reading JSON file failed", e);
      return null;
    }
    return project;
  }
  public List<LeagueTransaction> getLeagueTransactions(String leagueId) {
    String yql =
        "select * from fantasysports.leagues.transactions where league_key='" + leagueId + "'";
    List<LeagueTransaction> result = new LinkedList<LeagueTransaction>();
    try {
      ObjectMapper mapper = new ObjectMapper();
      Map<String, Object> results = performYQLQuery(yql); // result details
      Map leagueMap = (Map<String, Object>) results.get("league"); // result details
      Map standingsMap =
          (Map<String, Object>) leagueMap.get("transactions"); // transactions yahoo object

      List<Map<String, Object>> transactions =
          (List<Map<String, Object>>) standingsMap.get("transaction"); // teams yahoo list
      for (Map<String, Object> transactionMap : transactions) {
        LeagueTransaction transaction =
            mapper.readValue(
                JacksonPojoMapper.toJson(transactionMap, false), LeagueTransaction.class);
        List<TransactionPlayer> transactionPlayers = new LinkedList<TransactionPlayer>();
        TransactionPlayersList playersList = transaction.getPlayers();
        if (playersList != null) {
          if (Integer.parseInt(playersList.getCount()) > 1) {
            Map<String, Object> playersMap = (Map<String, Object>) transactionMap.get("players");
            List<Map<String, Object>> playerObjectList =
                (List<Map<String, Object>>) playersMap.get("player");
            for (Map<String, Object> playerObject : playerObjectList) {
              TransactionPlayer tmpPlayer =
                  mapper.readValue(
                      JacksonPojoMapper.toJson(playerObject, false), TransactionPlayer.class);
              transactionPlayers.add(tmpPlayer);
            }
          } else {
            Map<String, Object> playersMap = (Map<String, Object>) transactionMap.get("players");
            Map<String, Object> playerObject = (Map<String, Object>) playersMap.get("player");
            TransactionPlayer tmpPlayer =
                mapper.readValue(
                    JacksonPojoMapper.toJson(playerObject, false), TransactionPlayer.class);
            transactionPlayers.add(tmpPlayer);
          }
          playersList.setPlayer(transactionPlayers);
        }
        result.add(transaction);
      }
      // return result;
    } catch (Exception e) {
      Logger.getLogger(LeagueService.class.getName()).log(Level.SEVERE, null, e);
    }

    return result;
  }
Exemplo n.º 13
0
  private T parseFirstRow(JsonParser jp, ParseState state)
      throws JsonParseException, IOException, JsonProcessingException, JsonMappingException {

    skipToField(jp, VALUE_FIELD_NAME, state);
    firstId = state.lastId;
    firstKey = state.lastKey;
    JsonNode value = null;
    if (atObjectStart(jp)) {
      value = jp.readValueAsTree();
      jp.nextToken();
      if (isEndOfRow(jp)) {
        state.docFieldName = VALUE_FIELD_NAME;
        T doc = mapper.readValue(value, type);
        endRow(jp, state);
        return doc;
      }
    }
    skipToField(jp, INCLUDED_DOC_FIELD_NAME, state);
    if (atObjectStart(jp)) {
      state.docFieldName = INCLUDED_DOC_FIELD_NAME;
      T doc = jp.readValueAs(type);
      endRow(jp, state);
      return doc;
    }
    return null;
  }
Exemplo n.º 14
0
 /** 将json数据填充至对象中。 */
 public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) {
   try {
     return m.readValue(jsonAsString, pojoClass);
   } catch (Exception e) {
     return null;
   }
 }
Exemplo n.º 15
0
  public void processPackets() throws IOException {
    byte[] _receiveData = new byte[UDP_PACKET_BUFFER_SIZE];
    while (true) {
      DatagramPacket receivePacket = new DatagramPacket(_receiveData, _receiveData.length);
      serverSocket.receive(receivePacket);
      String data = new String(receivePacket.getData());
      System.out.println(data);
      ObjectMapper mapper = new ObjectMapper();
      JsonNode reqJSON = mapper.readValue(data, JsonNode.class);

      String action = reqJSON.get("action").getTextValue();
      if ("MOUSE_CLICK".equals(action)) {
        mc.leftClick();
      } else if ("ACCELEROMETER".equals(action)) {

      } else if ("MOUSE_MOVE".equals(action)) {
        JsonNode value = reqJSON.get("value");
        System.out.println(value);
        mc.scaleAndMove(value);
      }
      System.out.println("RECEIVED: " + data);
      for (int i = 0; i < UDP_PACKET_BUFFER_SIZE; i++) {
        _receiveData[i] = (byte) (0);
      }
    }
  }
  @Test
  public void testWithConversion() throws IOException {

    DateTime today = new DateTime();

    Map<String, Object> resultMap =
        (Map<String, Object>)
            ControllerUtil.sendAndReceive(
                controller,
                "remoteProviderSimple",
                "method14",
                a(
                    ISODateTimeFormat.dateTime().print(today),
                    "normalParameter",
                    ISODateTimeFormat.date().print(today),
                    "99.9%"),
                Map.class);

    assertThat(resultMap.get("endDate")).isEqualTo(today.getMillis());
    ObjectMapper mapper = new ObjectMapper();

    List<Object> expectedValue =
        mapper.readValue(mapper.writeValueAsString(today.toLocalDate()), List.class);
    Object actualValue = resultMap.get("jodaLocalDate");

    assertThat((List<Object>) resultMap.get("jodaLocalDate")).isEqualTo(expectedValue);
    assertThat(resultMap.get("percent")).isEqualTo(0.999);
    assertThat(resultMap.get("normalParameter")).isEqualTo("normalParameter");
    assertThat(resultMap.get("remoteAddr")).isEqualTo("127.0.0.1");
  }
Exemplo n.º 17
0
 @Override
 public List<Map<String, String>> getExistedFile(String fileName) throws Exception {
   String path = ResourceUtil.getTablesDataSourceDirectoryPath();
   System.out.println(fileName);
   if (fileName != null && fileName.length() > 0) {
     this.getJsonString(fileName);
   }
   Set<File> set = FileUtil.getAllFiles(path);
   List<Map<String, String>> fileNames = new ArrayList<Map<String, String>>();
   for (File file : set) {
     if (file.getName().endsWith(".json")) {
       Map<String, String> map = new HashMap<String, String>();
       String fName = file.getName();
       map.put("id", fName);
       map.put("text", fName.substring(0, fName.lastIndexOf(".json")));
       String fileString = "";
       ObjectMapper mapper = new ObjectMapper();
       Map<String, String> attrMap;
       try {
         fileString = this.readFile(file.getAbsolutePath());
         Map<String, Object> filemap = mapper.readValue(fileString, Map.class);
         attrMap = (Map<String, String>) filemap.get("attribute");
       } catch (Exception e) {
         e.printStackTrace();
         continue;
       }
       map.put("attribute", mapper.writeValueAsString(attrMap));
       fileNames.add(map);
     }
   }
   return fileNames;
 }
Exemplo n.º 18
0
  @Override
  public Map<String, String> saveOrUpdataReturnCasecadeID(
      String objectType, HttpServletRequest request) throws Exception {

    Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request);
    Object targetObject = Class.forName(objectType).newInstance();
    String jsonString = map.get(this.getType(objectType).getSimpleName());
    String cascadeTypes = map.get("cascadeType");

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Class<?> clazz = this.getType(objectType);
    targetObject = mapper.readValue(jsonString, clazz);
    Serializable id = this.commDao.saveOrUpdata(objectType, targetObject);

    Object target = this.findById(objectType, id.toString());

    Map<String, String> returenIDs = new HashMap<String, String>();
    returenIDs.put("id", id.toString());

    if (cascadeTypes != null) {
      String[] s = cascadeTypes.split(",");
      for (int i = 0; i < s.length; i++) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, s[i]);
        Method method = pd.getReadMethod();
        Object childTarget = method.invoke(target);
        PropertyDescriptor pdID = BeanUtils.getPropertyDescriptor(pd.getPropertyType(), "id");
        String childTargetID = pdID.getReadMethod().invoke(childTarget).toString();
        returenIDs.put(s[i], childTargetID);
      }
    }

    return returenIDs;
  }
Exemplo n.º 19
0
 /**
  * Transforms from JSON to the type specified.
  *
  * @param json the json to be transformed.
  * @param type the Java type that the JSON should be transformed to.
  * @return T an instance of the type populated with data from the json message.
  */
 public static <T> T fromJson(final String json, final Class<T> type) {
   try {
     return om.readValue(json, type);
   } catch (final Exception e) {
     throw new RuntimeException("error trying to parse json [" + json + "]", e);
   }
 }
Exemplo n.º 20
0
  @SuppressWarnings("rawtypes")
  public List<String> evaluateArray(String jsonString, String pathString)
      throws JsonParseException, JsonMappingException, IOException {
    List<String> list = new ArrayList<String>();
    if (jsonString == null || jsonString == "" || pathString == null || pathString == "") {
      return null;
    }

    List result = MAPPER.readValue(jsonString, new TypeReference<List>() {});
    String[] arr = pathString.split(",", -1);
    for (Object o : result) {
      if (o instanceof LinkedHashMap) {
        LinkedHashMap m = (LinkedHashMap) o;
        if (arr.length == 1) list.add(m.get(pathString).toString());
        else if (arr.length > 1) {
          StringBuilder sb = new StringBuilder();
          for (String path : arr) {
            sb.append(m.get(path).toString() + ",");
          }
          if (sb.length() > 0) sb.setLength(sb.length() - 1);
          list.add(sb.toString());
        }
      } else if (o instanceof String) {
        String str = (String) o;
        str = str.replaceAll(Const.ROWKEY_DEFAULT_SEPARATOR, ",");
        list.add(str);
      }
    }
    return list;
  }
  private static List<SchloettQueryFormat> parseQueryiesFile(
      List<File> files, SchloettQueryExtraction extraction)
      throws JsonSyntaxException, IOException {
    FileReader freader;
    List<SchloettQueryFormat> queries = new ArrayList<SchloettQueryFormat>();

    for (File file : files) {
      try {
        freader = new FileReader(file);
        BufferedReader br = new BufferedReader(freader);

        ObjectMapper mapper = new ObjectMapper();
        HashMap format = mapper.readValue(file, new HashMap<String, SchloettQuery>().getClass());

        queries.add(new SchloettQueryFormat(format));
        br.close();
        freader.close();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return queries;
  }
Exemplo n.º 22
0
 protected JsonType(String jsonString, ObjectMapper objectMapper, Class type)
     throws IOException {
   this.jsonString = jsonString;
   this.objectMapper = objectMapper;
   this.type = type;
   this.master = objectMapper.readValue(new FastStringReader(jsonString), type);
 }
Exemplo n.º 23
0
 @SuppressWarnings("unchecked")
 private <T> T parseContent(InputStream content, String string) throws IOException {
   // create parser manually to lower Jackson requirements
   JsonParser jsonParser = mapper.getJsonFactory().createJsonParser(content);
   Map<String, Object> map = mapper.readValue(jsonParser, Map.class);
   return (T) (string != null ? map.get(string) : map);
 }
  public Map<String, TeamStandings> getLeagueStandings(String leagueId) {
    String yql =
        "select * from fantasysports.leagues.standings where league_key='" + leagueId + "'";
    Map<String, TeamStandings> result = new HashMap<String, TeamStandings>();
    try {
      ObjectMapper mapper = new ObjectMapper();
      Map<String, Object> results = performYQLQuery(yql); // result details
      Map leagueMap = (Map<String, Object>) results.get("league"); // result details
      Map standingsMap = (Map<String, Object>) leagueMap.get("standings"); // standings yahoo object
      Map teamsMap = (Map<String, Object>) standingsMap.get("teams"); // teams yahoo Object
      List<Map<String, Object>> teamList =
          (List<Map<String, Object>>) teamsMap.get("team"); // teams yahoo list
      for (Map<String, Object> team : teamList) {
        String teamKey = ((String) team.get("team_key"));
        Map resultMap = (Map<String, Object>) team.get("team_standings");
        TeamStandings standings =
            mapper.readValue(JacksonPojoMapper.toJson(resultMap, false), TeamStandings.class);
        result.put(teamKey, standings);
      }
      // return result;
    } catch (Exception e) {
      Logger.getLogger(LeagueService.class.getName()).log(Level.SEVERE, null, e);
    }

    return result;
  }
Exemplo n.º 25
0
 public static <T> T getObject(String s, Class<T> clazz) throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   // 跳过未知(无对应)的属性
   mapper.getDeserializationConfig().disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES);
   T obj = mapper.readValue(s, clazz);
   return obj;
 }
Exemplo n.º 26
0
 void runRead(int cycles) throws IOException {
   readStopWatch.start();
   for (int i = 0; i < cycles; i++) {
     objectMapper.readValue(new FastStringReader(jsonString), type);
   }
   readStopWatch.stop();
 }
Exemplo n.º 27
0
 @Override
 public String process(
     HttpServletRequest request,
     HttpServletResponse response,
     String data,
     ObjectMapper mapper,
     String pathInfo) {
   LOG.debug("Start process Query :" + pathInfo);
   String result = "";
   try {
     LoginData loginData = mapper.readValue(data, LoginData.class);
     loginData = loginService.login(loginData);
     String x = mapper.writeValueAsString(loginData);
     result = MessageUtils.handleSuccess(x, mapper);
   } catch (ParkingEngineException e) {
     LOG.error("ParkingEngineException when processing " + pathInfo, e);
     result = MessageUtils.handleException(e, "", mapper);
   } catch (Exception e) {
     LOG.error("Unexpected exception when processing " + pathInfo, e);
     result =
         MessageUtils.handleException(
             e, "Unexpected exception when processing " + e.getMessage(), mapper);
   }
   return result;
 }
Exemplo n.º 28
0
    @Override
    protected Integer doInBackground(String... params) {
      TysxOA oa = new TysxOA(NewLoginAct.this);
      ObjectMapper mapper = new ObjectMapper();
      String logincontent =
          oa.login(
              TianyiContent.token,
              TianyiContent.devid,
              TianyiContent.appid,
              TianyiContent.appSecret,
              params[0],
              params[1]);

      System.out.println("登陆信息:" + logincontent);
      // if (user != null&&user.getResult()==0) {
      try {
        bean = mapper.readValue(logincontent, LoginBean.class);
        if (bean.getCode() == 0) {
          TianyiContent.user = bean.getInfo().getNickName();
          return 2;
        } else {
          return 1;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return 2;
      // }else
      // {
      //	return 1;
      // }

    }
Exemplo n.º 29
0
 public <T> T deserialize(String string, Class<T> type) {
   try {
     return objectMapper.readValue(string, type);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 30
0
  @SuppressWarnings("rawtypes")
  public static void main(String[] args) throws JsonParseException, IOException {
    String json = "{'channel':'14','videoid':'5815053'}";

    json =
        "[{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"剧情\",\"counter\":2,\"time\":2,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"动作\",\"counter\":36,\"time\":36,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"剧情\",\"counter\":10,\"time\":10,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"剧情\",\"counter\":22,\"time\":22,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"战争\",\"counter\":8,\"time\":8,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"惊悚\",\"counter\":35,\"time\":35,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"剧情\",\"counter\":5,\"time\":5,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"爱情\",\"counter\":18,\"time\":18,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"动作\",\"counter\":124,\"time\":124,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"喜剧\",\"counter\":21,\"time\":21,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"科幻\",\"counter\":34,\"time\":34,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"喜剧\",\"counter\":1,\"time\":1,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"古装\",\"counter\":7,\"time\":7,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"都市\",\"counter\":47,\"time\":47,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"爱情\",\"counter\":3,\"time\":3,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"爱情\",\"counter\":13,\"time\":13,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"喜剧\",\"counter\":16,\"time\":16,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"爱情\",\"counter\":23,\"time\":23,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"犯罪\",\"counter\":135,\"time\":135,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"喜剧\",\"counter\":281,\"time\":281,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"韩国\",\"category\":\"剧情\",\"counter\":358,\"time\":358,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"动作\",\"counter\":4,\"time\":4,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"犯罪\",\"counter\":33,\"time\":33,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"校园\",\"counter\":43,\"time\":43,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"警匪\",\"counter\":9,\"time\":9,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"热血\",\"counter\":42,\"time\":42,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"悬疑\",\"counter\":55,\"time\":55,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"家庭\",\"counter\":58,\"time\":58,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"都市\",\"counter\":70,\"time\":70,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"战争\",\"counter\":119,\"time\":119,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"娱乐\",\"counter\":284,\"time\":284,\"type\":\"综艺\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"警匪\",\"counter\":363,\"time\":363,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"韩国\",\"category\":\"爱情\",\"counter\":449,\"time\":449,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"港台\",\"category\":\"惊悚\",\"counter\":32,\"time\":32,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"悬疑\",\"counter\":61,\"time\":61,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"悬疑\",\"counter\":226,\"time\":226,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"悬疑\",\"counter\":11,\"time\":11,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"伦理\",\"counter\":29,\"time\":29,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"励志\",\"counter\":44,\"time\":44,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"韩国\",\"category\":\"浪漫\",\"counter\":69,\"time\":69,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"校园\",\"counter\":71,\"time\":71,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"冒险\",\"counter\":77,\"time\":77,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"犯罪\",\"counter\":161,\"time\":161,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"伦理\",\"counter\":162,\"time\":162,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"魔幻\",\"counter\":245,\"time\":245,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"武侠\",\"counter\":20,\"time\":20,\"type\":\"电视\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"恶搞\",\"counter\":45,\"time\":45,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"日本\",\"category\":\"魔幻\",\"counter\":46,\"time\":46,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"萌系\",\"counter\":92,\"time\":92,\"type\":\"动漫\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"警匪\",\"counter\":134,\"time\":134,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"内地\",\"category\":\"武侠\",\"counter\":6,\"time\":6,\"type\":\"电影\",\"uid\":\"\"},{\"ID\":\"\",\"area\":\"欧美\",\"category\":\"推理\",\"counter\":51,\"time\":51,\"type\":\"动漫\",\"uid\":\"\"}]";
    // JsonFactory f = new JsonFactory();
    // JsonParser jp = f.createJsonParser(json);

    // BufferedReader br = new BufferedReader(new InputStreamReader(
    // new FileInputStream("/root/test.txt")));
    // String line = null;
    // while (null != (line = br.readLine())) {
    // json = line;
    // }
    System.out.println(json);
    List result = MAPPER.readValue(json, new TypeReference<List>() {});
    System.out.println(result);
    for (Object o : result) {
      LinkedHashMap m = (LinkedHashMap) o;
      System.out.println((String) m.get("area") + "\t" + m.get("category") + "\t" + m.get("type"));
    }
    JsonUtil u = new JsonUtil();
    List<String> list = u.evaluateArray(json, "area,category,type");
    for (String s : list) {
      System.out.println(s);
    }
  }