Example usage for com.google.gson JsonArray addAll

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

Introduction

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

Prototype

public void addAll(JsonArray array) 

Source Link

Document

Adds all the elements of the specified array to self.

Usage

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject listUsers(UserListMode listMode) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;//  w  w  w  . ja v  a  2  s. c om

    try {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");

        String filterArgument = "";
        if (listMode == UserListMode.ENABLED_ONLY)
            filterArgument = "?status=enabled";
        else if (listMode == UserListMode.DISABLED_ONLY)
            filterArgument = "?status=disabled";

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/users" + filterArgument);
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null, headers);
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");

        JsonArray userList = new JsonArray();

        BufferedReader reader = new BufferedReader(inputStreamReader);
        for (String line; (line = reader.readLine()) != null;) {
            if (line.startsWith("[")) {
                JsonArray aUserlist = new JsonParser().parse(line).getAsJsonArray();
                userList.addAll(aUserlist);
            }
        }

        result = new JsonObject();
        result.add("userlist", userList);

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return result;
}

From source file:com.google.iosched.input.fetcher.RemoteJsonHelper.java

License:Open Source License

public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException {
    if (target == null) {
        target = new JsonObject();
    }/*from  www  .j  a v  a  2s . com*/
    for (String filename : filenames) {
        String url = Config.CLOUD_STORAGE_BASE_URL + filename;
        JsonObject obj = fetchJsonFromPublicURL(url);
        if (obj == null) {
            throw new FileNotFoundException(url);
        } else {
            for (Entry<String, JsonElement> entry : obj.entrySet()) {
                if (entry.getValue().isJsonArray()) {
                    // tries to merge an array with the existing one, if it's the case:
                    JsonArray existing = target.getAsJsonArray(entry.getKey());
                    if (existing == null) {
                        existing = new JsonArray();
                        target.add(entry.getKey(), existing);
                    }
                    existing.addAll(entry.getValue().getAsJsonArray());
                } else {
                    target.add(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return target;
}

From source file:com.google.iosched.model.DataCheck.java

License:Open Source License

private JsonObject clone(JsonObject source) {
    JsonObject dest = new JsonObject();
    for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
        JsonArray values = entry.getValue().getAsJsonArray();
        JsonArray cloned = new JsonArray();
        cloned.addAll(values);
        dest.add(entry.getKey(), cloned);
    }//from   w  ww .j ava  2s .co  m
    return dest;
}

From source file:com.google.jstestdriver.requesthandlers.DefaultGatewayConfigurationFilter.java

License:Apache License

public JsonArray filter(JsonArray gatewayConfig) {
    if (destination == null) {
        return gatewayConfig;
    } else {/*from  w  ww  .  j a  v a  2s  .  c  o m*/
        final JsonArray newGatewayConfig = new JsonArray();
        newGatewayConfig.addAll(gatewayConfig);
        final JsonObject entry = new JsonObject();
        entry.addProperty("matcher", "*");
        entry.addProperty("server", destination.getDestinationAddress());
        newGatewayConfig.add(entry);
        return newGatewayConfig;
    }
}

From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java

License:Open Source License

public JsonArray fetchArray(InputJsonKeys.VendorAPISource.MainTypes entityType, int page) throws IOException {

    HashMap<String, String> params = null;

    if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)
            || entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.speakers)) {
        params = new HashMap<String, String>();

        // Topics and speakers require param "includeinfo=true" to bring extra data
        params.put("includeinfo", "true");

        if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)) {
            if (extractUnpublished) {
                params.put("minpublishstatus", "0");
            }/*from   www .j  ava2s.co m*/
        }
    }

    if (page == 0) {
        page = 1;
    } else if (page > 1) {
        if (params == null) {
            params = new HashMap<String, String>();
        }
        params.put("page", Integer.toString(page));
    }

    JsonElement element = getFetcher().fetch(entityType, params);

    if (element.isJsonArray()) {
        return element.getAsJsonArray();
    } else if (element.isJsonObject()) {
        // check if there are extra pages requiring further fetching
        JsonObject obj = element.getAsJsonObject();
        checkPagingConsistency(entityType, page, obj);

        int pageSize = obj.get("pagesize").getAsInt();
        int totalEntities = obj.get("total").getAsInt();
        JsonArray elements = getEntities(obj);
        if (page * pageSize < totalEntities) {
            // fetch the next page
            elements.addAll(fetchArray(entityType, page + 1));
        }
        return elements;
    } else {
        throw new JsonParseException("Invalid response from Vendor API. Request should return "
                + "either a JsonArray or a JsonObject, but returned " + element.getClass().getName()
                + ". Entity fetcher is " + getFetcher());
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.OperatorGenerator.java

License:Open Source License

private void paramClause(JsonObject graphConfig, JsonObject op, StringBuilder sb) {

    // VMArgs only apply to Java SPL operators.
    boolean isJavaOp = OpProperties.LANGUAGE_JAVA.equals(jstring(op, OpProperties.LANGUAGE));

    JsonArray vmArgs = null;//from w ww  .jav a 2s  .com
    if (isJavaOp && graphConfig.has(ContextProperties.VMARGS))
        vmArgs = GsonUtilities.array(graphConfig, ContextProperties.VMARGS);

    // determine if we need to inject submission param names and values
    // info.
    boolean addSPInfo = false;
    ParamsInfo stvOpParamInfo = stvHelper.getSplInfo();
    if (stvOpParamInfo != null) {
        Map<String, JsonObject> functionalOps = stvHelper.getFunctionalOps();
        if (functionalOps.containsKey(op.get("name").getAsString()))
            addSPInfo = true;
    }

    JsonObject params = jobject(op, "parameters");
    if (vmArgs == null && GsonUtilities.jisEmpty(params) && !addSPInfo) {
        return;
    }

    sb.append("    param\n");

    for (Entry<String, JsonElement> on : params.entrySet()) {
        String name = on.getKey();
        JsonObject param = on.getValue().getAsJsonObject();
        if ("vmArg".equals(name)) {
            JsonArray fullVmArgs = new JsonArray();
            fullVmArgs.addAll(GsonUtilities.array(param, "value"));
            if (vmArgs != null)
                fullVmArgs.addAll(vmArgs);
            // stringArray(param, "value", v -> fullVmArgs.);
            // objectArray(graphConfig, ContextProperties.VMARGS, v ->
            // fullVmArgs.add(v));
            vmArgs = fullVmArgs;
            continue;
        }
        sb.append("      ");
        sb.append(name);
        sb.append(": ");
        splValueSupportingSubmission(param, sb);
        sb.append(";\n");
    }

    if (vmArgs != null) {
        JsonObject tmpVMArgParam = new JsonObject();
        tmpVMArgParam.add("value", vmArgs);
        sb.append("      ");
        sb.append("vmArg");
        sb.append(": ");

        splValueSupportingSubmission(tmpVMArgParam, sb);
        sb.append(";\n");
    }

    if (addSPInfo) {
        sb.append("      ");
        sb.append(FunctionalOpProperties.NAME_SUBMISSION_PARAM_NAMES);
        sb.append(": ");
        sb.append(stvOpParamInfo.names);
        sb.append(";\n");

        sb.append("      ");
        sb.append(FunctionalOpProperties.NAME_SUBMISSION_PARAM_VALUES);
        sb.append(": ");
        sb.append(stvOpParamInfo.values);
        sb.append(";\n");
    }
}

From source file:com.mweagle.tereus.commands.utils.EmbeddingUtils.java

License:Open Source License

protected static JsonArray parseResource(final String resourceData) throws Exception {
    JsonArray parsedContent = new JsonArray();
    Arrays.stream(resourceData.split("\\r?\\n")).forEach(eachLine -> parsedContent.addAll(parseLine(eachLine)));
    // Get the last element of parsed content.  If it's a JsonPrimitive with some non-empty
    // content then remove the final newline delimiter
    final JsonElement finalElement = parsedContent.get(parsedContent.size() - 1);
    if (finalElement instanceof JsonPrimitive) {
        JsonPrimitive finalPrimitive = (JsonPrimitive) finalElement;
        final String primitiveContent = finalPrimitive.getAsString();
        if (RE_TRAILING_NEWLINE.matcher(primitiveContent).matches()) {
            final JsonPrimitive trimmedPrimitive = new JsonPrimitive(
                    primitiveContent.substring(0, primitiveContent.length() - 1));
            parsedContent.set(parsedContent.size() - 1, trimmedPrimitive);
        }/*from w ww  .  ja va2s .  co  m*/

    }
    return parsedContent;
}

From source file:com.plnyyanks.frcnotebook.dialogs.AddNoteDialog.java

License:Open Source License

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    activity = this.getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.add_note_title);
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(activity.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.fragment_add_note, null);

    ImageView camIcon = (ImageView) layout.findViewById(R.id.add_note_picture);
    camIcon.setOnClickListener(new AddPictureListener());
    if (PreferenceHandler.getTheme() == R.style.theme_dark) {
        camIcon.setBackgroundResource(R.drawable.ic_action_camera_dark);
    }/*from   ww w  . java 2  s.  c  o  m*/

    //if match is set, get the teams for this match
    final JsonArray redAlliance, blueAlliance;
    JsonArray teams;
    String[] team_choices;
    if (match != null) {
        redAlliance = match.getRedAllianceTeams();
        blueAlliance = match.getBlueAllianceTeams();
        teams = new JsonArray();
        teams.addAll(redAlliance);
        teams.addAll(blueAlliance);

        team_choices = new String[teams.size() + 1];
        team_choices[0] = getResources().getString(R.string.all_teams);
        for (int i = 1; i < team_choices.length; i++) {
            team_choices[i] = teams.get(i - 1).getAsString().substring(3);
        }
    } else {
        if (GetNotesForTeam.getTeamKey().equals("all")) {
            ArrayList<Team> all_teams = StartActivity.db.getAllTeamAtEvent(GetNotesForTeam.getEventKey());
            team_choices = new String[all_teams.size() + 1];
            team_choices[0] = activity.getString(R.string.all_teams);
            for (int i = 1; i < all_teams.size(); i++) {
                team_choices[i] = Integer.toString(all_teams.get(i - 1).getTeamNumber());
            }
        } else {
            //we're on the team page, so only allow this team
            team_choices = new String[1];
            team_choices[0] = GetNotesForTeam.getTeamNumber();
        }

        //keep the compiler happy
        redAlliance = new JsonArray();
        blueAlliance = new JsonArray();
    }

    //get predefined notes
    HashMap<Short, String> allPredefNotes = StartActivity.db.getAllDefNotes();
    final String[] note_choice = new String[allPredefNotes.size() + 1];
    final short[] note_choice_ids = new short[allPredefNotes.size() + 1];
    note_choice[0] = "Custom Note";
    note_choice_ids[0] = -1;
    Iterator<Short> iterator = allPredefNotes.keySet().iterator();
    Short key;
    for (int i = 1; i < note_choice.length && iterator.hasNext(); i++) {
        key = iterator.next();
        note_choice_ids[i] = key;
        note_choice[i] = allPredefNotes.get(key);
    }

    //get all the matches at this event
    final String[] match_choices;
    final String[] match_keys;
    if (match != null) {
        match_choices = new String[1];
        match_choices[0] = match.getTitle();

        match_keys = new String[1];
        match_keys[0] = match.getMatchKey();
    } else {
        ArrayList<Match> matches = new ArrayList<Match>();
        if (eventKey.equals("all")) {
            matches = StartActivity.db.getAllMatchesForTeam(GetNotesForTeam.getTeamKey());
        } else {
            matches = StartActivity.db.getAllMatches(eventKey, GetNotesForTeam.getTeamKey());
        }
        match_choices = new String[matches.size() + 1];
        match_keys = new String[matches.size() + 1];
        match_choices[0] = getString(R.string.generic_note);
        match_keys[0] = "all";
        for (int i = 1; i < match_choices.length; i++) {
            match_choices[i] = matches.get(i - 1).getTitle(eventKey.equals("all"));
            match_keys[i] = matches.get(i - 1).getMatchKey();
        }
    }

    final Spinner teamSpinner = (Spinner) layout.findViewById(R.id.team_selector);
    final Spinner noteSpinner = (Spinner) layout.findViewById(R.id.predef_note_selector);
    final Spinner matchSpinner = (Spinner) layout.findViewById(R.id.match_selector);
    final EditText e = (EditText) layout.findViewById(R.id.note_contents);
    noteSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == 0) {
                e.setVisibility(View.VISIBLE);
            } else {
                e.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    final ArrayAdapter teamAdapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item,
            team_choices);
    teamAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    teamSpinner.setAdapter(teamAdapter);
    teamSpinner.setEnabled(match != null || GetNotesForTeam.getTeamKey().equals("all"));

    ArrayAdapter noteAdapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, note_choice);
    noteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    noteSpinner.setAdapter(noteAdapter);

    ArrayAdapter matchAdapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, match_choices);
    matchAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    matchSpinner.setAdapter(matchAdapter);
    matchSpinner.setEnabled(match == null);

    builder.setView(layout);

    // Add the buttons
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

            if (noteSpinner.getSelectedItemPosition() == 0 && e.getText().toString().isEmpty()) {
                dialog.cancel();
                return;
            }
            if (match != null) {
                Note newNote = new Note();
                newNote.setMatchKey(match_keys[matchSpinner.getSelectedItemPosition()]);
                newNote.setEventKey(match.getParentEvent().getEventKey());
                newNote.setParent(note_choice_ids[noteSpinner.getSelectedItemPosition()]);

                if (noteSpinner.getSelectedItemPosition() == 0) {
                    newNote.setNote(e.getText().toString());
                } else {
                    newNote.setNote(note_choice[noteSpinner.getSelectedItemPosition()]);
                }

                if (teamSpinner.getSelectedItem()
                        .equals(activity.getResources().getString(R.string.all_teams))) {
                    //add note for all teams
                    newNote.setTeamKey("all");
                    short newId = StartActivity.db.addNote(newNote);
                    if (newId == -1) {
                        dialog.cancel();
                        return;
                    }
                    if (GetNotesForMatch.getGenericAdapter().keys.size() == 0) {
                        ListView list = (ListView) activity.findViewById(R.id.generic_notes);
                        list.setVisibility(View.VISIBLE);
                    }
                    newNote = StartActivity.db.getNote(newId);
                    genericAdapter.addNote(newNote);

                } else {
                    //generate team key
                    String team = "frc" + (String) teamSpinner.getSelectedItem();
                    Iterator iterator = redAlliance.iterator();
                    String testTeam;
                    newNote.setTeamKey(team);
                    Log.d(Constants.LOG_TAG, "team key: " + newNote.getTeamKey());
                    while (iterator.hasNext()) {
                        testTeam = iterator.next().toString();
                        if (testTeam.equals("\"" + team + "\"")) {
                            short newId = StartActivity.db.addNote(newNote);
                            newNote = StartActivity.db.getNote(newId);
                            Log.d(Constants.LOG_TAG, "id: " + newId + " team: " + newNote.getTeamKey());
                            redAdapter.addNote(newNote);
                            dialog.cancel();
                            return;
                        }
                    }
                    iterator = blueAlliance.iterator();
                    while (iterator.hasNext()) {
                        testTeam = iterator.next().toString();
                        if (testTeam.equals("\"" + team + "\"")) {
                            short newId = StartActivity.db.addNote(newNote);
                            blueAdapter.addNote(StartActivity.db.getNote(newId));
                            ;
                            dialog.cancel();
                            return;
                        }
                    }
                }
            } else {
                //add the note on the team view activity
                Note newNote = new Note();
                newNote.setMatchKey(match_keys[matchSpinner.getSelectedItemPosition()]);
                if (newNote.getMatchKey().equals("all")) {
                    newNote.setEventKey(eventKey);
                } else {
                    newNote.setEventKey(newNote.getMatchKey().split("_")[0]);
                }
                newNote.setParent(note_choice_ids[noteSpinner.getSelectedItemPosition()]);
                String team = "frc" + (String) teamSpinner.getSelectedItem();
                newNote.setTeamKey(team.equals(activity.getString(R.string.all_teams)) ? "all" : team);

                if (noteSpinner.getSelectedItemPosition() == 0) {
                    //set note to custom text
                    newNote.setNote(e.getText().toString());
                } else {
                    //set note to a predefined note
                    newNote.setNote(note_choice[noteSpinner.getSelectedItemPosition()]);
                }

                short newId = StartActivity.db.addNote(newNote);
                if (newId == -1) {
                    dialog.cancel();
                    return;
                }
                newNote = StartActivity.db.getNote(newId);
                teamViewAdapter.addNote(newNote);
            }
        }
    });
    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // User cancelled the dialog
            dialog.dismiss();
        }
    });

    Dialog out = builder.create();
    out.getWindow().clearFlags(
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    out.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    return out;
}

From source file:com.shinwootns.common.infoblox.InfobloxWAPIHandler.java

public JsonArray getNetworkInfo() {

    if (restClient == null)
        return null;

    JsonArray arrayIPv4 = null;//  w  ww .j av a 2 s  .  c  o m
    JsonArray arrayIPv6 = null;

    // IPv4
    {
        StringBuilder sb = new StringBuilder();
        sb.append("/wapi/v1.0/network");
        sb.append("?_return_type=json");

        String value = restClient.Get(sb.toString(), null);

        if (value != null) {

            value = StringUtils.unescapeUnicodeString(value);

            arrayIPv4 = JsonUtils.parseJsonArray(value);
        }
    }

    // IPv6
    {
        StringBuilder sb = new StringBuilder();
        sb.append("/wapi/v1.0/ipv6network");
        sb.append("?_return_type=json");

        String value = restClient.Get(sb.toString(), null);

        if (value != null) {

            value = StringUtils.unescapeUnicodeString(value);

            arrayIPv6 = JsonUtils.parseJsonArray(value);
        }
    }

    // Merge
    JsonArray array = new JsonArray();

    if (arrayIPv4 != null)
        array.addAll(arrayIPv4);

    if (arrayIPv6 != null)
        array.addAll(arrayIPv6);

    return array;
}

From source file:com.shinwootns.common.infoblox.InfobloxWAPIHandler.java

public JsonArray getRangeInfo() {

    if (restClient == null)
        return null;

    JsonArray arrayIPv4 = null;/* w  ww.  java  2s  .  c  om*/
    JsonArray arrayIPv6 = null;

    // IPv4 Range
    {
        StringBuilder sb = new StringBuilder();

        sb.append("/wapi/v1.0/range");
        sb.append("?_return_type=json");
        sb.append("&_return_fields=network,network_view,start_addr,end_addr,comment,disable");

        String value = restClient.Get(sb.toString(), null);

        if (value == null)
            return null;

        // Change unescape-unicode
        value = StringUtils.unescapeUnicodeString(value);

        if (value != null) {
            value = StringUtils.unescapeUnicodeString(value);
            arrayIPv4 = JsonUtils.parseJsonArray(value);
        }
    }

    // IPv6 Range
    {
        StringBuilder sb = new StringBuilder();

        sb.append("/wapi/v1.0/ipv6range");
        sb.append("?_return_type=json");
        sb.append("&_return_fields=network,network_view,start_addr,end_addr,comment,disable");

        String value = restClient.Get(sb.toString(), null);

        if (value == null)
            return null;

        // Change unescape-unicode
        value = StringUtils.unescapeUnicodeString(value);

        if (value != null) {
            value = StringUtils.unescapeUnicodeString(value);
            arrayIPv6 = JsonUtils.parseJsonArray(value);
        }
    }

    // Merge
    JsonArray array = new JsonArray();

    if (arrayIPv4 != null)
        array.addAll(arrayIPv4);

    if (arrayIPv6 != null)
        array.addAll(arrayIPv6);

    return array;
}