Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.microsoft.applicationinsights.test.framework.telemetries.RequestTelemetryItem.java

/**
 * Converts JSON object to Request TelemetryItem
 * @param json The JSON object/*  www .  j a v  a  2  s. c o m*/
 */
private void initRequestTelemetryItem(JSONObject json) throws URISyntaxException, JSONException {
    System.out.println("Converting JSON object to RequestTelemetryItem");
    JSONObject requestProperties = json.getJSONArray("request").getJSONObject(0);

    String address = requestProperties.getString("url");
    Integer port = requestProperties.getJSONObject("urlData").getInt("port");
    Integer responseCode = requestProperties.getInt("responseCode");
    String requestName = requestProperties.getString("name");

    JSONArray parameters = requestProperties.getJSONObject("urlData").getJSONArray("queryParameters");
    Hashtable<String, String> queryParameters = new Hashtable<String, String>();
    for (int i = 0; i < parameters.length(); ++i) {
        JSONObject parameterPair = parameters.getJSONObject(i);
        String name = parameterPair.getString("parameter");
        String value = parameterPair.getString("value");
        queryParameters.put(name, value);
    }

    this.setProperty("uri", address);
    this.setProperty("port", port.toString());
    this.setProperty("responseCode", responseCode.toString());
    this.setProperty("requestName", requestName);

    for (String key : queryParameters.keySet()) {
        this.setProperty("queryParameter." + key, queryParameters.get(key));
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools,
        final LinearLayout toolContainer) {
    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        List<ToolEntry> localTools = new ArrayList<>();
        final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>();
        final List<ToolEntry> synchedTools = new ArrayList<>();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) {
                    synchedTools.add(toolEntry);
                } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) {
                    localTools.add(toolEntry);
                } else {
                    unconfirmedRemovedTools.add(toolEntry);
                }/*from   www  .  java2  s .c  om*/
            }
        }

        barentswatchApi.setAccesToken(user.getToken());

        Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON");

        if (response == null) {
            Log.d(TAG, "RESPONSE == NULL");
        }

        byte[] toolData;
        try {
            toolData = FiskInfoUtility.toByteArray(response.getBody().in());
            JSONObject featureCollection = new JSONObject(new String(toolData));
            JSONArray jsonTools = featureCollection.getJSONArray("features");
            JSONArray matchedTools = new JSONArray();
            UserSettings settings = user.getSettings();

            for (int i = 0; i < jsonTools.length(); i++) {
                JSONObject tool = jsonTools.getJSONObject(i);
                boolean hasCopy = false;

                for (int j = 0; j < localTools.size(); j++) {
                    if (localTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault());

                        sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                        /* Timestamps from BW seem to be one hour earlier than UTC/GMT?  */
                        sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        Date localLastUpdatedDateTime;
                        Date localUpdatedBySourceDateTime;
                        Date serverUpdatedDateTime;
                        Date serverUpdatedBySourceDateTime = null;
                        try {
                            localLastUpdatedDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedDateTime());
                            localUpdatedBySourceDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedBySource());

                            serverUpdatedDateTime = tool.getJSONObject("properties")
                                    .getString("lastchangeddatetime").length() == getResources()
                                            .getInteger(R.integer.datetime_without_milliseconds_length)
                                                    ? sdfRemote.parse(tool.getJSONObject("properties")
                                                            .getString("lastchangeddatetime"))
                                                    : sdfMilliSecondsRemote
                                                            .parse(tool.getJSONObject("properties")
                                                                    .getString("lastchangeddatetime"));

                            if (tool.getJSONObject("properties").has("lastchangedbysource")) {
                                serverUpdatedBySourceDateTime = tool.getJSONObject("properties")
                                        .getString("lastchangedbysource").length() == getResources()
                                                .getInteger(R.integer.datetime_without_milliseconds_length)
                                                        ? sdfRemote.parse(tool.getJSONObject("properties")
                                                                .getString("lastchangedbysource"))
                                                        : sdfMilliSecondsRemote
                                                                .parse(tool.getJSONObject("properties")
                                                                        .getString("lastchangedbysource"));
                            }

                            if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime)
                                    || localLastUpdatedDateTime.before(serverUpdatedDateTime))
                                    && serverUpdatedBySourceDateTime != null
                                    && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime)
                                            || localUpdatedBySourceDateTime
                                                    .before(serverUpdatedBySourceDateTime))) {
                                localTools.get(j).updateFromGeoJson(tool, getActivity());

                                localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED);
                            } else if (serverUpdatedBySourceDateTime != null
                                    && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) {
                                // TODO: Do nothing, local changes should be reported.

                            } else {
                                // TODO: what gives?
                            }

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

                        localTools.remove(j);
                        j--;

                        hasCopy = true;
                        break;
                    }
                }

                for (int j = 0; j < unconfirmedRemovedTools.size(); j++) {
                    if (unconfirmedRemovedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        unconfirmedRemovedTools.remove(j);
                        j--;
                    }
                }

                for (int j = 0; j < synchedTools.size(); j++) {
                    if (synchedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        synchedTools.remove(j);
                        j--;
                    }
                }

                if (!hasCopy && settings != null) {
                    if ((!settings.getVesselName().isEmpty()
                            && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName())
                                    .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname"))
                                    || settings.getVesselName().equalsIgnoreCase(
                                            tool.getJSONObject("properties").getString("vesselname"))))
                            && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase()
                                    .equals(tool.getJSONObject("properties").getString("ircs")))
                                    || (!settings.getMmsi().isEmpty() && settings.getMmsi()
                                            .equals(tool.getJSONObject("properties").getString("mmsi")))
                                    || (!settings.getImo().isEmpty() && settings.getImo()
                                            .equals(tool.getJSONObject("properties").getString("imo"))))) {
                        matchedTools.put(tool);
                    }
                }
            }

            if (matchedTools.length() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);
                final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>();

                for (int i = 0; i < matchedTools.length(); i++) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(),
                            matchedTools.getJSONObject(i));
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                    matchedToolsList.add(confirmationRow);
                }

                addToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolConfirmationRow row : matchedToolsList) {
                            if (row.isChecked()) {
                                ToolEntry newTool = row.getToolEntry();
                                user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10));
                                ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool,
                                        utilityOnClickListeners.getToolEntryEditDialogOnClickListener(
                                                getActivity(), getFragmentManager(), mGpsLocationTracker,
                                                newTool, user));
                                row.getView().setTag(newTool.getToolId());
                                toolContainer.addView(newRow.getView());
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.removed_tools_information_text);
                archiveToolsButton.setText(R.string.ok);
                cancelButton.setVisibility(View.GONE);

                for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.unexpected_tool_removal_info_text);
                archiveToolsButton.setText(R.string.archive);

                for (ToolEntry removedEntry : synchedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : synchedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                // TODO: If not found server side, tool is assumed to be removed. Inform user.

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.removed_tools_information_text));
                cancelButton.setVisibility(View.GONE);
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                //                    // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive?

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text));
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : synchedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : synchedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));

                dialog.show();
            }

            user.writeToSharedPref(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.olejon.mdapp.LvhAdapter.java

@Override
public void onBindViewHolder(CategoryViewHolder viewHolder, int i) {
    try {//from  ww  w. j av  a2 s . co m
        final String color;
        final String icon;

        final JSONObject categoriesJsonObject = mCategories.getJSONObject(i);

        switch (i) {
        case 0: {
            color = "#F44336";
            icon = "lvh_urgent";

            viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.red));
            viewHolder.icon.setImageResource(R.drawable.ic_favorite_white_24dp);

            break;
        }
        case 1: {
            color = "#9C27B0";
            icon = "lvh_symptoms";

            viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.purple));
            viewHolder.icon.setImageResource(R.drawable.ic_stethoscope);

            break;
        }
        case 2: {
            color = "#FF9800";
            icon = "lvh_injuries";

            viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.orange));
            viewHolder.icon.setImageResource(R.drawable.ic_healing_white_24dp);

            break;
        }
        case 3: {
            color = "#009688";
            icon = "lvh_administrative";

            viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.teal));
            viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp);

            break;
        }
        default: {
            color = "#009688";
            icon = "lvh_administrative";

            viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.teal));
            viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp);
        }
        }

        viewHolder.title.setText(categoriesJsonObject.getString("title"));

        viewHolder.categories.removeAllViews();

        final JSONArray categoriesJsonArray = categoriesJsonObject.getJSONArray("categories");

        for (int f = 0; f < categoriesJsonArray.length(); f++) {
            final JSONObject categoryJsonObject = categoriesJsonArray.getJSONObject(f);

            final String title = categoryJsonObject.getString("title");
            final String subcategories = categoryJsonObject.getString("subcategories");

            TextView textView = (TextView) mLayoutInflater.inflate(R.layout.activity_lvh_card_categories_item,
                    null);
            textView.setText(categoryJsonObject.getString("title"));

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, LvhCategoriesActivity.class);
                    intent.putExtra("color", color);
                    intent.putExtra("icon", icon);
                    intent.putExtra("title", title);
                    intent.putExtra("subcategories", subcategories);
                    mContext.startActivity(intent);
                }
            });

            viewHolder.categories.addView(textView);
        }

        animateView(viewHolder.card, i);
    } catch (Exception e) {
        Log.e("LvhAdapter", Log.getStackTraceString(e));
    }
}

From source file:com.android.browser.GearsSettingsDialog.java

public void setup() {
    // First let's add the permissions' resources
    LOCAL_STORAGE.setResources(R.string.settings_storage_title, R.string.settings_storage_subtitle_on,
            R.string.settings_storage_subtitle_off);
    LOCATION_DATA.setResources(R.string.settings_location_title, R.string.settings_location_subtitle_on,
            R.string.settings_location_subtitle_off);
    // add the permissions to the list of permissions.
    mPermissions = new Vector<PermissionType>();
    mPermissions.add(LOCAL_STORAGE);//from   w ww. jav a 2s.  c o  m
    mPermissions.add(LOCATION_DATA);
    OriginPermissions.setListener(this);

    setupDialog();

    // We manage the permissions using three vectors, mSitesPermissions,
    // mOriginalPermissions and mCurrentPermissions.
    // The dialog's arguments are parsed and a list of permissions is
    // generated and stored in those three vectors.
    // mOriginalPermissions is a separate copy and will not be modified;
    // mSitesPermissions contains the current permissions _only_ --
    // if an origin is removed, it is also removed from mSitesPermissions.
    // Finally, mCurrentPermissions contains the current permissions and
    // is a clone of mSitesPermissions, but removed sites aren't removed,
    // their permissions are simply set to PERMISSION_NOT_SET. This
    // allows us to easily generate the final difference between the
    // original permissions and the final permissions, while directly
    // using mSitesPermissions for the listView adapter (SettingsAdapter).

    mSitesPermissions = new Vector<OriginPermissions>();
    mOriginalPermissions = new Vector<OriginPermissions>();

    try {
        JSONObject json = new JSONObject(mDialogArguments);
        if (json.has("permissions")) {
            JSONArray jsonArray = json.getJSONArray("permissions");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject infos = jsonArray.getJSONObject(i);
                String name = null;
                int localStorage = PermissionType.PERMISSION_NOT_SET;
                int locationData = PermissionType.PERMISSION_NOT_SET;
                if (infos.has("name")) {
                    name = infos.getString("name");
                }
                if (infos.has(LOCAL_STORAGE_STRING)) {
                    JSONObject perm = infos.getJSONObject(LOCAL_STORAGE_STRING);
                    if (perm.has("permissionState")) {
                        localStorage = perm.getInt("permissionState");
                    }
                }
                if (infos.has(LOCATION_DATA_STRING)) {
                    JSONObject perm = infos.getJSONObject(LOCATION_DATA_STRING);
                    if (perm.has("permissionState")) {
                        locationData = perm.getInt("permissionState");
                    }
                }
                OriginPermissions perms = new OriginPermissions(name);
                perms.setPermission(LOCAL_STORAGE, localStorage);
                perms.setPermission(LOCATION_DATA, locationData);

                mSitesPermissions.add(perms);
                mOriginalPermissions.add(new OriginPermissions(perms));
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception ", e);
    }
    mCurrentPermissions = (Vector<OriginPermissions>) mSitesPermissions.clone();

    View listView = findViewById(R.id.sites_list);
    if (listView != null) {
        ListView list = (ListView) listView;
        mListAdapter = new SettingsAdapter(mActivity, mSitesPermissions);
        list.setAdapter(mListAdapter);
        list.setScrollBarStyle(android.view.View.SCROLLBARS_OUTSIDE_INSET);
        list.setOnItemClickListener(mListAdapter);
    }
    if (mDebug) {
        printPermissions();
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitPullTest.java

@Test
public void testPullRemoteUpToDate() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // get HEAD/*from  w  w  w . j a  v a2 s  . c  o  m*/
    JSONArray commitsArray = log(gitHeadUri);
    String headSha1 = commitsArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME);

    // list remotes
    request = GitRemoteTest.getGetGitRemoteRequest(gitRemoteUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject remotes = new JSONObject(response.getText());
    JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, remotesArray.length());
    JSONObject remote = remotesArray.getJSONObject(0);
    assertNotNull(remote);
    assertEquals(Constants.DEFAULT_REMOTE_NAME, remote.getString(ProtocolConstants.KEY_NAME));
    String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(remoteLocation);

    // get remote details
    JSONObject details = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
    String refId = details.getString(ProtocolConstants.KEY_ID);

    // pull
    pull(cloneLocation);

    // get remote details again
    String newRefId = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER).getString(ProtocolConstants.KEY_ID);
    // up to date
    assertEquals(refId, newRefId);

    // get the current branch
    request = getGetRequest(gitHeadUri);
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response);
    assertTrue(status.toString(), status.isOK());
    JSONObject newHead = status.getJsonData();
    String newHeadSha1 = newHead.getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(0)
            .getString(ProtocolConstants.KEY_NAME);
    assertEquals(headSha1, newHeadSha1);
}

From source file:com.example.android.sunshine.data.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from   w w  w  . ja va 2  s  .c o  m*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherContract.WeatherEntry
                .buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:fr.bmartel.android.fadecandy.model.FadecandyColor.java

public FadecandyColor(JSONObject color) {

    try {//from w  ww .  ja  v a  2  s  .  c om
        if (color.has(Constants.CONFIG_GAMMA) && color.has(Constants.CONFIG_WHITEPOINT)) {
            mGamma = (float) color.getDouble(Constants.CONFIG_GAMMA);

            JSONArray whitepoints = color.getJSONArray(Constants.CONFIG_WHITEPOINT);

            for (int i = 0; i < whitepoints.length(); i++) {
                mWhitepoints.add((float) whitepoints.getDouble(i));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    JSONArray jsonset;/*from  w w w.  j  av a 2  s  .  co m*/
    if (o instanceof JSONArray) {
        jsonset = (JSONArray) o;

    } else if (o instanceof JSONObject) {
        final JSONObject jso = (JSONObject) o;
        String java_class;

        // Hint presence
        try {
            java_class = jso.getString("javaClass");
        } catch (final JSONException e) {
            throw new UnmarshallException("Could not read javaClass", e);
        }
        if (java_class == null) {
            throw new UnmarshallException("no type hint");
        }

        // Class compatibility check
        if (!classNameCheck(java_class)) {
            throw new UnmarshallException("not a Set");
        }

        // JSON Format check
        try {
            jsonset = jso.getJSONArray("set");
        } catch (final JSONException e) {
            throw new UnmarshallException("set missing", e);
        }
    } else {
        throw new UnmarshallException("Given object is not JSON object/array");
    }

    if (jsonset == null) {
        throw new UnmarshallException("set missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    int idx = 0;
    try {
        for (idx = 0; idx < jsonset.length(); idx++) {
            m.setMismatch(ser.tryUnmarshall(state, null, jsonset.get(idx)).max(m).getMismatch());
        }

    } catch (final UnmarshallException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    }
    return m;
}

From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java

@Override
public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONArray jsonset;
    final Set<Object> abset;
    if (o instanceof JSONArray) {
        jsonset = (JSONArray) o;/*from   w w w  .ja v  a2  s  . co  m*/
        abset = new LinkedHashSet<Object>();

    } else if (o instanceof JSONObject) {
        final JSONObject jso = (JSONObject) o;
        String java_class;

        // Hint check
        try {
            java_class = jso.getString("javaClass");
        } catch (final JSONException e) {
            throw new UnmarshallException("Could not read javaClass", e);
        }

        if (java_class == null) {
            throw new UnmarshallException("no type hint");
        }

        // Create the set
        if (java_class.equals("java.util.Set") || java_class.equals("java.util.AbstractSet")
                || java_class.equals("java.util.HashSet")) {
            abset = new HashSet<Object>();
        } else if (java_class.equals("java.util.TreeSet")) {
            abset = new TreeSet<Object>();
        } else if (java_class.equals("java.util.LinkedHashSet")) {
            abset = new LinkedHashSet<Object>();
        } else {
            throw new UnmarshallException("not a Set");
        }

        // Parse the JSON set
        try {
            jsonset = jso.getJSONArray("set");

        } catch (final JSONException e) {
            throw new UnmarshallException("set missing", e);
        }
    } else {
        throw new UnmarshallException("Given object is not JSON object/array");
    }

    if (jsonset == null) {
        throw new UnmarshallException("set missing");
    }

    state.setSerialized(o, abset);

    int idx = 0;
    try {
        for (idx = 0; idx < jsonset.length(); idx++) {
            abset.add(ser.unmarshall(state, null, jsonset.get(idx)));
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    }
    return abset;
}

From source file:jGW2API.util.event.Events.java

public Events(JSONObject json) {
    JSONArray e = json.getJSONArray("events");
    this.events = new HashMap();
    for (int i = 0; i < e.length(); i++) {
        Event tmp = new Event(e.getJSONObject(i));
        this.events.put(tmp.getEventID(), tmp);
    }//from  w ww .j a  v  a2  s.  c o  m
}