Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:com.pearson.pdn.learningstudio.eventing.EventingClient.java

License:Apache License

private List<Subscription> parseSubscriptions(String jsonString) throws ParseException {
    JsonParser jsonParser = new JsonParser();
    JsonElement json = jsonParser.parse(jsonString);
    JsonArray jsonSubs = json.getAsJsonObject().get("subscriptions").getAsJsonArray();

    List<Subscription> subs = new ArrayList<Subscription>();
    for (Iterator<JsonElement> iter = jsonSubs.iterator(); iter.hasNext();) {
        JsonObject jsonSub = iter.next().getAsJsonObject().get("subscription").getAsJsonObject();
        subs.add(parseSubscriptionObject(jsonSub));
    }/* w w  w  .j a  v  a2 s .  c  om*/

    return subs;
}

From source file:com.pearson.pdn.learningstudio.eventing.EventingClient.java

License:Apache License

private Subscription parseSubscriptionObject(JsonObject jsonSub) throws ParseException {
    Subscription sub = new Subscription();
    sub.setId(jsonSub.get("id").getAsString());
    sub.setPrincipalId(jsonSub.get("principal_id").getAsString());
    sub.setCreateDate(DATE_FORMAT.parse(jsonSub.get("date_created").getAsString()));
    sub.setCallbackUrl(jsonSub.get("callback_url").getAsString());
    sub.setTags(new HashMap<String, String>());

    JsonArray jsonTags = jsonSub.get("tags").getAsJsonArray();
    for (Iterator<JsonElement> iter = jsonTags.iterator(); iter.hasNext();) {
        JsonObject jsonTag = iter.next().getAsJsonObject().get("tag").getAsJsonObject();
        String tagName = jsonTag.get("type").getAsString();
        String tagValue = jsonTag.get("value").getAsString();

        // map the tags to sub as appropriate
        if ("Client".equals(tagName))
            sub.setClient(tagValue);/*  w w w  .ja  v  a  2s . co  m*/
        else if ("ClientString".equals(tagName))
            sub.setClientString(tagValue);
        else if ("MessageType".equals(tagName))
            sub.setMessageType(tagValue);
        else if ("System".equals(tagName))
            sub.setSystem(tagValue);
        else if ("SubSystem".equals(tagName))
            sub.setSubSystem(tagValue);
        else
            sub.getTags().put(tagName, tagValue);

    }

    return sub;
}

From source file:com.pearson.pdn.learningstudio.exams.ExamService.java

License:Apache License

/**
 * Retrieve all of a user's exams for a course with
 * GET /users/{userId}/courses/{courses}/items
 * using OAuth1 or OAuth2 as a student or teacher
 * /*from  w ww.ja  va2 s  . c  om*/
 * @param userId   ID of the user
 * @param courseId   ID of course
 * @return Response object with details of status and content
 * @throws IOException
 */
public Response getAllExamItems(String userId, String courseId) throws IOException {
    String relativeUrl = String.format(PATH_USERS_COURSES_ITEMS, userId, courseId);
    Response response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
    if (response.isError()) {
        return response;
    }

    String courseItemsJson = response.getContent();
    JsonObject json = this.jsonParser.parse(courseItemsJson).getAsJsonObject();
    JsonArray items = json.get("items").getAsJsonArray();
    JsonArray exams = new JsonArray();

    for (Iterator<JsonElement> itemIter = items.iterator(); itemIter.hasNext();) {
        JsonObject item = itemIter.next().getAsJsonObject();
        JsonArray links = item.get("links").getAsJsonArray();

        for (Iterator<JsonElement> linkIter = links.iterator(); linkIter.hasNext();) {
            JsonObject link = linkIter.next().getAsJsonObject();
            if (RELS_USER_COURSE_EXAM.equals(link.get("rel").getAsString())) {
                exams.add(item);
                break;
            }
        }
    }

    JsonObject examItems = new JsonObject();
    examItems.add("items", exams);

    response.setContent(this.gson.toJson(examItems));
    return response;
}

From source file:com.pearson.pdn.learningstudio.exams.ExamService.java

License:Apache License

/**
 *  Retrieves and filters a user's current attempt of an exam in a course with 
 *  GET /users/{userId}/courses/{courseId}/exams/{examId}/attempts
 *  using OAuth2 as a student/*from  w w  w  .  jav a  2 s .  c om*/
 * 
 * @param userId   ID of the user
 * @param courseId   ID of the course
 * @param examId   ID of the exam
 * @return Response object with details of status and content
 * @throws IOException
 */
public Response getCurrentExamAttempt(String userId, String courseId, String examId) throws IOException {
    Response response = getExamAttempts(userId, courseId, examId);
    if (response.isError()) {
        return response;
    }
    String attemptsJson = response.getContent();
    JsonElement json = jsonParser.parse(attemptsJson);
    JsonArray attempts = json.getAsJsonObject().get("attempts").getAsJsonArray();
    JsonObject currentAttempt = null;

    for (Iterator<JsonElement> attemptsIterator = attempts.iterator(); attemptsIterator.hasNext();) {
        JsonObject attempt = attemptsIterator.next().getAsJsonObject();
        if (!attempt.get("isCompleted").getAsBoolean()) {
            currentAttempt = attempt;
            break;
        }
    }

    if (currentAttempt != null) {
        JsonObject attempt = new JsonObject();
        attempt.add("attempt", currentAttempt);

        response.setContent(gson.toJson(attempt));
    } else {
        response.setStatusCode(ResponseStatus.NOT_FOUND.code());
        response.setContent(null);
    }

    return response;
}

From source file:com.pearson.pdn.learningstudio.exams.ExamService.java

License:Apache License

/**
 * Retrieve details of questions for a section of a user's exam in a course with 
 * GET /users/{userId}/courses/{courseId}/exams/{examId}/sections/{sectionId}/questions
 * and getExamSectionQuestion// w w w . j  a va 2s. c  om
 * using OAuth2 as a student
 * 
 * @param userId   ID of the user
 * @param courseId   ID of the course
 * @param examId   ID of the exam
 * @param sectionId   ID of the section on the exam
 * @return Response object with details of status and content
 * @throws IOException
 */
public Response getExamSectionQuestions(String userId, String courseId, String examId, String sectionId)
        throws IOException {

    String relativeUrl = String.format(PATH_USERS_COURSES_EXAMS_SECTIONS_QUESTIONS, userId, courseId, examId,
            sectionId);
    Response response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
    if (response.isError()) {
        return response;
    }

    String sectionQuestionJson = response.getContent();
    JsonObject json = this.jsonParser.parse(sectionQuestionJson).getAsJsonObject();
    JsonArray questions = json.get("questions").getAsJsonArray();
    JsonArray sectionQuestions = new JsonArray();

    for (Iterator<JsonElement> questionIter = questions.iterator(); questionIter.hasNext();) {
        JsonObject question = questionIter.next().getAsJsonObject();
        String questionType = question.get("type").getAsString();
        String questionId = question.get("id").getAsString();
        Response questionResponse = getExamSectionQuestion(userId, courseId, examId, sectionId, questionType,
                questionId);
        if (questionResponse.isError()) {
            return questionResponse;
        }

        JsonObject sectionQuestion = this.jsonParser.parse(questionResponse.getContent()).getAsJsonObject();
        sectionQuestion.addProperty("id", questionId);
        sectionQuestion.addProperty("type", questionType);
        sectionQuestion.addProperty("pointsPossible", question.get("pointsPossible").getAsString());
        sectionQuestions.add(sectionQuestion);
    }

    JsonObject sectionQuestionsWrapper = new JsonObject();
    sectionQuestionsWrapper.add("questions", sectionQuestions);

    response.setContent(this.gson.toJson(sectionQuestionsWrapper));
    return response;
}

From source file:com.pearson.pdn.learningstudio.grades.GradeService.java

License:Apache License

/**
 * Get a user's grades for a course with
 * GET /users/{userId}/courses/{courseId}/gradebook/userGradebookItems
 * and getGrade(String userId, String courseId, String gradebookItemId, boolean useSourceDomain)
 * using OAuth1 or OAuth2 as a teacher, teaching assistant or administrator
 * //from ww w . j a  v  a 2  s . com
 * @param userId   ID of the user
 * @param courseId   ID of the course
 * @param useSourceDomain   Indicator of whether to include domain in urls
 * @return   Response object with details of status and content
 * @throws IOException
 */
public Response getGrades(String userId, String courseId, boolean useSourceDomain) throws IOException {
    Response response = getCourseGradebookUserItems(userId, courseId);
    if (response.isError()) {
        return response;
    }

    JsonArray grades = new JsonArray();

    JsonElement json = this.jsonParser.parse(response.getContent());
    JsonArray items = json.getAsJsonObject().get("userGradebookItems").getAsJsonArray();
    for (Iterator<JsonElement> itemIter = items.iterator(); itemIter.hasNext();) {
        JsonObject item = itemIter.next().getAsJsonObject();
        String gradebookItemId = item.get("gradebookItem").getAsJsonObject().get("id").getAsString();
        Response gradeResponse = getGrade(userId, courseId, gradebookItemId, useSourceDomain);
        if (gradeResponse.isError()) {
            // grades for all items might not exist. That's ok
            if (gradeResponse.getStatusCode() == ResponseStatus.NOT_FOUND.code()) {
                continue;
            }
            return gradeResponse;
        }
        JsonObject grade = this.jsonParser.parse(gradeResponse.getContent()).getAsJsonObject();
        grade = grade.get("grade").getAsJsonObject();
        grades.add(grade);
    }

    JsonObject gradesWrapper = new JsonObject();
    gradesWrapper.add("grades", grades);

    response.setContent(this.gson.toJson(gradesWrapper));
    return response;
}

From source file:com.pinterest.arcee.metrics.StatsboardMetricSource.java

License:Apache License

@Override
public Collection<MetricDatumBean> getMetrics(String metricName, String start) throws Exception {
    HTTPClient httpClient = new HTTPClient();
    Map<String, String> params = new HashMap<>();
    params.put("target", metricName);
    params.put("start", start);
    HashMap<String, String> headers = new HashMap<>();

    String url = String.format("%s/api/v1/query", readPath);
    String jsonPayload = httpClient.get(url, params, headers, 1);
    LOG.debug(String.format("Get metric data from source: %s", jsonPayload));
    List<MetricDatumBean> dataPoints = new ArrayList<>();
    JsonParser parser = new JsonParser();
    JsonArray array = (JsonArray) parser.parse(jsonPayload);
    if (array.isJsonNull() || array.size() == 0) {
        LOG.info(String.format("Cannot obtain metrics %s from %s", metricName, url));
        return dataPoints;
    }// w w w .j  a  va2 s. c  o m

    JsonObject object = (JsonObject) array.get(0);
    JsonArray data = object.getAsJsonArray("datapoints");
    for (Iterator<JsonElement> elementIterator = data.iterator(); elementIterator.hasNext();) {
        JsonArray metric = (JsonArray) elementIterator.next();
        MetricDatumBean dataPoint = new MetricDatumBean();
        dataPoint.setTimestamp(metric.get(0).getAsLong() * 1000);
        double metricValue = metric.get(1).getAsDouble();
        metricValue = metricValue == Double.MIN_VALUE ? 0 : metricValue;
        dataPoint.setValue(metricValue);
        dataPoints.add(dataPoint);
    }
    return dataPoints;
}

From source file:com.plnyyanks.frcnotebook.background.GetNotesForMatch.java

License:Open Source License

@Override
protected String doInBackground(String... strings) {
    String thisMatchKey, eventKey;
    previousMatchKey = strings[0];//from   ww  w . j a  va 2  s. c  om
    thisMatchKey = strings[1];
    nextMatchKey = strings[2];
    eventKey = strings[3];
    selectedNote = "";

    Match match = StartActivity.db.getMatch(thisMatchKey);
    Event parentEvent = match.getParentEvent();
    TextView matchTitle = (TextView) activity.findViewById(R.id.match_title);
    String titleString = Match.LONG_TYPES.get(match.getMatchType())
            + (match.getMatchType() == Match.MATCH_TYPES.QUAL ? " " : (" " + match.getSetNumber() + " Match "))
            + match.getMatchNumber();
    matchTitle.setText(titleString);
    if (PreferenceHandler.getTimesEnabled() && parentEvent.isHappeningNow()) {
        String matchTime = match.getMatchTime();
        if (matchTime != null && !matchTime.equals("")) {
            TextView timeOffset = (TextView) activity.findViewById(R.id.match_time);
            SimpleDateFormat df = new SimpleDateFormat(TIME_FORMAT);
            Log.d(Constants.LOG_TAG, "Showing match time");
            try {
                Date matchStart = df.parse(matchTime);
                Date currentTime = new Date();
                int hourdif = currentTime.getHours() - matchStart.getHours();
                int mindif = currentTime.getMinutes() - matchStart.getMinutes();
                String timeString = Math.abs(hourdif) + ":" + String.format("%02d", Math.abs(mindif));
                boolean ahead;
                if (hourdif > 0 || (hourdif == 0 && mindif > 0)) {
                    timeString += " behind";
                    ahead = false;
                } else {
                    timeString += " ahead";
                    ahead = true;
                }
                timeOffset.setText(timeString);
                timeOffset.setTextColor(ahead ? Color.GREEN : Color.RED);
                timeOffset.setVisibility(View.VISIBLE);
            } catch (ParseException e) {
                Log.w(Constants.LOG_TAG, "Error parsing match time");
            }
        }
    }

    TextView redHeader = (TextView) activity.findViewById(R.id.red_score);
    if (match.getRedScore() >= 0 && PreferenceHandler.showMatchScores()) {
        redHeader.setText(Integer.toString(match.getRedScore()) + " Points");
    } else {
        redHeader.setVisibility(View.GONE);
    }

    TextView blueHeader = (TextView) activity.findViewById(R.id.blue_score);
    if (match.getBlueScore() >= 0 && PreferenceHandler.showMatchScores()) {
        blueHeader.setText(Integer.toString(match.getBlueScore()) + " Points");
    } else {
        blueHeader.setVisibility(View.GONE);
    }

    JsonArray redTeams = match.getRedAllianceTeams(), blueTeams = match.getBlueAllianceTeams();

    if (redTeams.size() > 0) {
        Iterator<JsonElement> iterator = redTeams.iterator();
        String teamKey;
        for (int i = 0; iterator.hasNext(); i++) {
            teamKey = iterator.next().getAsString();
            ArrayList<Note> notes = new ArrayList<Note>();
            if (PreferenceHandler.showGeneralNotes()) {
                notes.addAll(StartActivity.db.getAllNotes(
                        StartActivity.db.KEY_EVENTKEY + "=? AND " + StartActivity.db.KEY_MATCHKEY + "=?",
                        new String[] { "all", "all" }));
            }
            notes.addAll(StartActivity.db.getAllNotes(teamKey, eventKey, thisMatchKey));
            int size = notes.size();
            ListGroup teamHeader = new ListGroup(
                    teamKey.substring(3) + (size > 0 ? (" (" + notes.size() + ")") : ""));

            for (Note n : notes) {
                teamHeader.children.add(Note.buildMatchNoteTitle(n, false, false, false));
                teamHeader.children_keys.add(Short.toString(n.getId()));
            }

            redGroups.append(i, teamHeader);
        }
    }
    if (blueTeams.size() > 0) {
        Iterator<JsonElement> iterator = blueTeams.iterator();
        String teamKey;
        for (int i = 0; iterator.hasNext(); i++) {
            teamKey = iterator.next().getAsString();
            ArrayList<Note> notes = new ArrayList<Note>();
            if (PreferenceHandler.showGeneralNotes()) {
                notes.addAll(StartActivity.db.getAllNotes(
                        StartActivity.db.KEY_EVENTKEY + "=? AND " + StartActivity.db.KEY_MATCHKEY + "=?",
                        new String[] { "all", "all" }));
            }
            notes.addAll(StartActivity.db.getAllNotes(teamKey, eventKey, thisMatchKey));
            int size = notes.size();
            ListGroup teamHeader = new ListGroup(
                    teamKey.substring(3) + (size > 0 ? (" (" + notes.size() + ")") : ""));

            for (Note n : notes) {
                teamHeader.children.add(Note.buildMatchNoteTitle(n, false, false, false));
                teamHeader.children_keys.add(Short.toString(n.getId()));
            }

            blueGroups.append(i, teamHeader);
        }
    }

    //generic notes go here
    final ArrayList<Note> genericNotes = StartActivity.db.getAllNotes(
            StartActivity.db.KEY_TEAMKEY + "=? AND " + StartActivity.db.KEY_EVENTKEY + "=? AND "
                    + StartActivity.db.KEY_MATCHKEY + "=?",
            new String[] { "all", eventKey, match.getMatchKey() });
    Log.d(Constants.LOG_TAG, "Found " + genericNotes.size() + " generic notes");
    ArrayList<ListItem> genericVals = new ArrayList<ListItem>();
    ArrayList<String> genericKeys = new ArrayList<String>();
    for (Note n : genericNotes) {
        genericVals.add(new ListElement(n.getNote(), Short.toString(n.getId())));
        genericKeys.add(Short.toString(n.getId()));
    }
    genericAdapter = new ListViewArrayAdapter(activity, genericVals, genericKeys);

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (!StartActivity.db.matchExists(nextMatchKey)) {
                ImageView nextButton = (ImageView) activity.findViewById(R.id.next_match);
                nextButton.setVisibility(View.GONE);
            }
            if (!StartActivity.db.matchExists(previousMatchKey)) {
                ImageView prevButton = (ImageView) activity.findViewById(R.id.prev_match);
                prevButton.setVisibility(View.GONE);
            }

            redAlliance = (ExpandableListView) activity.findViewById(R.id.red_teams);
            if (redAlliance == null)
                return;
            redAdaper = new AllianceExpandableListAdapter(activity, redGroups);
            redAlliance.setAdapter(redAdaper);

            blueAlliance = (ExpandableListView) activity.findViewById(R.id.blue_teams);
            if (redAlliance == null)
                return;
            blueAdapter = new AllianceExpandableListAdapter(activity, blueGroups);
            blueAlliance.setAdapter(blueAdapter);

            genericList = (ListView) activity.findViewById(R.id.generic_notes);
            genericList.setAdapter(genericAdapter);
            GenericNoteClick clickListener = new GenericNoteClick();
            genericList.setOnItemClickListener(clickListener);
            genericList.setOnItemLongClickListener(clickListener);
            if (genericNotes.size() > 0) {
                genericList.setVisibility(View.VISIBLE);
            }

            //hide the progress bar
            ProgressBar prog = (ProgressBar) activity.findViewById(R.id.match_loading_progress);
            prog.setVisibility(View.GONE);
        }
    });

    return null;
}

From source file:com.plnyyanks.frcnotebook.database.DatabaseHandler.java

License:Open Source License

public void importEvents(JsonArray events) {
    Iterator<JsonElement> iterator = events.iterator();
    JsonObject e;/*from w  ww  .  j  av  a 2 s. com*/
    Event event;

    while (iterator.hasNext()) {
        e = iterator.next().getAsJsonObject();
        event = new Event();
        event.setEventKey(e.get(KEY_EVENTKEY).getAsString());
        event.setEventName(e.get(KEY_EVENTNAME).getAsString());
        event.setShortName(e.get(KEY_EVENTSHORT).getAsString());
        event.setEventYear(e.get(KEY_EVENTYEAR).getAsInt());
        if (!(e.get(KEY_EVENTLOC) instanceof JsonNull))
            event.setEventLocation(e.get(KEY_EVENTLOC).getAsString());
        event.setEventStart(e.get(KEY_EVENTSTART).getAsString());
        event.setEventEnd(e.get(KEY_EVENTEND).getAsString());
        event.setOfficial(e.get(KEY_EVENTOFFICIAL).getAsBoolean());

        addEvent(event);
    }
}

From source file:com.plnyyanks.frcnotebook.database.DatabaseHandler.java

License:Open Source License

public void importMatches(JsonArray matches) {
    Iterator<JsonElement> iterator = matches.iterator();
    JsonObject m;/*from   w  w w . ja v  a 2 s  .  c om*/
    Match match;

    while (iterator.hasNext()) {
        m = iterator.next().getAsJsonObject();
        match = new Match();
        match.setMatchKey(m.get(KEY_MATCHKEY).getAsString());
        match.setMatchType(m.get(KEY_MATCHTYPE).getAsString());
        match.setMatchNumber(m.get(KEY_MATCHNO).getAsInt());
        match.setSetNumber(m.get(KEY_MATCHSET).getAsInt());
        match.setRedAlliance(m.get(KEY_REDALLIANCE).toString());
        match.setBlueAlliance(m.get(KEY_BLUEALLIANCE).toString());
        match.setRedScore(m.get(KEY_REDSCORE).getAsInt());
        match.setBlueScore(m.get(KEY_BLUESCORE).getAsInt());
        try {
            match.setMatchTime(m.get(KEY_MATCHTIME).getAsString());
        } catch (Exception e) {
            match.setMatchTime("");
        }

        addMatch(match);
    }
}