Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key, String defaultValue) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.clearner.youtube.Playlist.java

public void addPage(JSONObject jsonPlaylist) throws JSONException {
    pages.add(new Page(jsonPlaylist.getJSONArray("items"), jsonPlaylist.getString("etag"),
            jsonPlaylist.optString("nextPageToken", null)));
}

From source file:uk.co.senab.photup.model.Account.java

public Account(JSONObject object) throws JSONException {
    super(object, null);
    mAccessToken = object.optString("access_token", null);
    mAccessExpires = 0;/*  w w  w  .  ja v  a  2 s  . co  m*/
    mIsMainAccount = false;
}

From source file:com.solvian.androidpusher.pusher.PusherConnection.java

public void connect() {
    try {//from www .j av a2s .c o m
        URI url = new URI(mPusher.getUrl());
        Log.d(LOG_TAG, "Connecting to " + url.toString());

        mWebSocket = new WebSocketConnection(url);
        mWebSocket.setEventHandler(new WebSocketEventHandler() {
            public void onOpen() {
                Log.d(LOG_TAG, "Successfully opened Websocket");
            }

            public void onMessage(WebSocketMessage message) {
                Log.d(LOG_TAG, "Received from Websocket " + message.getText());

                try {
                    JSONObject parsed = new JSONObject(message.getText());
                    String eventName = parsed.getString("event");
                    String channelName = parsed.optString("channel", null);
                    String eventData = parsed.getString("data");

                    if (eventName.equals(Pusher.PUSHER_EVENT_CONNECTION_ESTABLISHED)) {
                        JSONObject parsedEventData = new JSONObject(eventData);
                        String socketId = parsedEventData.getString("socket_id");
                        mPusher.onConnected(socketId);
                    } else {
                        mPusher.dispatchEvents(eventName, eventData, channelName);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onClose() {
                Log.d(LOG_TAG, "Successfully closed Websocket");
            }
        });
        mWebSocket.connect();

    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (WebSocketException e) {
        e.printStackTrace();
    }
}

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

@Test
public void testCommitOnly() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "change to commit");
    addFile(testTxt);//  w  w  w.j  av a2 s  .c  om

    JSONObject folder1 = getChild(project, "folder");
    JSONObject folderTxt = getChild(folder1, "folder.txt");
    modifyFile(folderTxt, "change to commit");
    addFile(folderTxt);

    assertStatus(new StatusResult().setChanged(2), gitStatusUri);

    // "git commit -m 'message' -- test.txt
    final String commitMessage = "message";
    JSONObject commit = commitFile(testTxt, commitMessage);

    // check if response contains most important parts and if commit
    // message is valid
    assertNotNull(commit.optString(ProtocolConstants.KEY_LOCATION, null));
    assertNotNull(commit.optString(ProtocolConstants.KEY_NAME, null));
    assertEquals(commitMessage, commit.getString(GitConstants.KEY_COMMIT_MESSAGE));

    // still in index, not committed
    assertStatus(new StatusResult().setChangedNames("folder/folder.txt"), gitStatusUri);
}

From source file:dlauncher.modpacks.download.DefaultDownloadLocation.java

public static DownloadLocation valueOf(JSONObject obj) throws MalformedURLException, JSONException {
    byte[] md5 = null;
    byte[] sha512 = null;
    long fileLength = -1;
    String optMd5 = obj.optString("md5", null);
    String optSha512 = obj.optString("sha512", null);
    if (optMd5 != null) {
        md5 = hexStringToByteArray(optMd5);
    }/*from www .j  a  va 2s  .  c om*/
    if (optSha512 != null) {
        sha512 = hexStringToByteArray(optSha512);
    }
    fileLength = obj.optLong("size", fileLength);
    String urlStr = obj.getString("url");
    URL url;
    if (urlStr.startsWith("default:")) {
        url = DefaultDownloadLocation.class.getResource(urlStr.substring("default:".length()));
    } else {
        url = new URL(urlStr);
    }
    return new DefaultDownloadLocation(url, fileLength, md5, sha512);
}

From source file:org.bd2kccc.bd2kcccpubmed.Crawler.java

public static void main(String[] args) {
    HashMap<Integer, ArrayList<String>> publications = new HashMap();

    for (int i = 0; i < BD2K_CENTERS.length; i++) {
        String searchUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term="
                + BD2K_GRANTS[i] + "[Grant%20Number]&retmode=json&retmax=1000";

        System.out.println(searchUrl);
        HttpRequest request = HttpRequest.get(searchUrl);
        JSONObject req = new JSONObject(request.body());
        JSONArray idlist = req.getJSONObject("esearchresult").getJSONArray("idlist");
        System.out.println(BD2K_CENTERS[i] + ": " + idlist.length());
        for (int j = 0; j < idlist.length(); j++) {
            int pmid = idlist.optInt(j);
            if (!publications.containsKey(pmid)) {
                ArrayList<String> centerList = new ArrayList();
                centerList.add(BD2K_CENTERS[i]);
                publications.put(pmid, centerList);
            } else {
                publications.get(pmid).add(BD2K_CENTERS[i]);
            }// www .  j  a  v a  2s  .c  o  m
        }
    }

    Integer[] pmids = publications.keySet().toArray(new Integer[0]);
    int collaborations = 0;
    for (int i = 0; i < pmids.length; i++)
        if (publications.get(pmids[i]).size() > 1)
            collaborations++;

    System.out.println(pmids.length + " publications found.");
    System.out.println(collaborations + " BD2K Center collaborations found.");
    String summaryUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id="
            + pmids[0];
    for (int i = 1; i < pmids.length; i++)
        summaryUrl += "," + pmids[i];

    System.out.println(summaryUrl);
    HttpRequest request = HttpRequest.get(summaryUrl);
    JSONObject result = new JSONObject(request.body()).getJSONObject("result");

    ArrayList<Publication> publicationStructs = new ArrayList();

    for (int i = 0; i < pmids.length; i++) {
        JSONObject pub = result.getJSONObject("" + pmids[i]);
        Publication publication = new Publication();
        publication.pmid = pmids[i];
        publication.centers = publications.get(pmids[i]);
        publication.name = pub.optString("title", "NO_TITLE");
        //remove &lt;i&gt; and &lt;/i&gt;
        //replace &amp;amp; with &
        publication.name = unescapeHtml4(publication.name);
        publication.date = pub.optString("sortpubdate", "1066/01/01 00:00").substring(0, 10);
        publication.date = publication.date.replaceAll("/", "-");

        JSONArray articleIDs = pub.getJSONArray("articleids");
        for (int j = 0; j < articleIDs.length(); j++) {
            JSONObject id = articleIDs.optJSONObject(j);
            if (id.optString("idtype").equals("doi"))
                publication.doi = id.optString("value");
        }

        String issue = pub.optString("issue");
        if (!issue.isEmpty())
            issue = "(" + issue + ")";

        publication.citation = pub.optString("source") + ". " + pub.optString("pubdate") + ";"
                + pub.optString("volume") + issue + ":" + pub.optString("pages") + ".";

        publication.authors = new ArrayList();
        JSONArray aut = pub.getJSONArray("authors");
        for (int j = 0; j < aut.length(); j++) {
            publication.authors.add(aut.getJSONObject(j).optString("name"));
        }

        publicationStructs.add(publication);
    }

    Collections.sort(publicationStructs);

    for (Publication p : publicationStructs) {
        if (p.isTool())
            System.out.println(p.name);
    }

    JSONArray outputData = new JSONArray();

    for (Publication p : publicationStructs) {
        JSONArray row = new JSONArray();
        row.put(0, p.getName());
        row.put(1, p.getType());
        row.put(2, p.getDate());
        row.put(3, p.getCenter());
        row.put(4, p.getInitiative());
        row.put(5, p.getDescription());
        outputData.put(row);
    }

    System.out.println(outputData.toString(1));

}

From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java

protected DefaultEntityState readEntityState(DefaultEntityStoreUnitOfWork unitOfWork, Reader entityState)
        throws EntityStoreException {
    try {//from  w  ww  .ja  va 2  s. c  om
        ModuleSPI module = unitOfWork.module();
        JSONObject jsonObject = new JSONObject(new JSONTokener(entityState));
        EntityStatus status = EntityStatus.LOADED;

        String version = jsonObject.getString("version");
        long modified = jsonObject.getLong("modified");
        String identity = jsonObject.getString("identity");

        // Check if version is correct
        String currentAppVersion = jsonObject.optString(MapEntityStore.JSONKeys.application_version.name(),
                "0.0");
        if (!currentAppVersion.equals(application.version())) {
            if (migration != null) {
                migration.migrate(jsonObject, application.version(), this);
            } else {
                // Do nothing - set version to be correct
                jsonObject.put(MapEntityStore.JSONKeys.application_version.name(), application.version());
            }

            LOGGER.trace("Updated version nr on {} from {} to {}",
                    new Object[] { identity, currentAppVersion, application.version() });

            // State changed
            status = EntityStatus.UPDATED;
        }

        String type = jsonObject.getString("type");

        EntityDescriptor entityDescriptor = module.entityDescriptor(type);
        if (entityDescriptor == null) {
            throw new EntityTypeNotFoundException(type);
        }

        Map<QualifiedName, Object> properties = new HashMap<QualifiedName, Object>();
        JSONObject props = jsonObject.getJSONObject("properties");
        for (PropertyDescriptor propertyDescriptor : entityDescriptor.state().properties()) {
            Object jsonValue;
            try {
                jsonValue = props.get(propertyDescriptor.qualifiedName().name());
            } catch (JSONException e) {
                // Value not found, default it
                Object initialValue = propertyDescriptor.initialValue();
                properties.put(propertyDescriptor.qualifiedName(), initialValue);
                status = EntityStatus.UPDATED;
                continue;
            }
            if (jsonValue == JSONObject.NULL) {
                properties.put(propertyDescriptor.qualifiedName(), null);
            } else {
                Object value = ((PropertyTypeDescriptor) propertyDescriptor).propertyType().type()
                        .fromJSON(jsonValue, module);
                properties.put(propertyDescriptor.qualifiedName(), value);
            }
        }

        Map<QualifiedName, EntityReference> associations = new HashMap<QualifiedName, EntityReference>();
        JSONObject assocs = jsonObject.getJSONObject("associations");
        for (AssociationDescriptor associationType : entityDescriptor.state().associations()) {
            try {
                Object jsonValue = assocs.get(associationType.qualifiedName().name());
                EntityReference value = jsonValue == JSONObject.NULL ? null
                        : EntityReference.parseEntityReference((String) jsonValue);
                associations.put(associationType.qualifiedName(), value);
            } catch (JSONException e) {
                // Association not found, default it to null
                associations.put(associationType.qualifiedName(), null);
                status = EntityStatus.UPDATED;
            }
        }

        Map<QualifiedName, List<EntityReference>> manyAssociations = createManyAssociations(jsonObject,
                entityDescriptor);
        Map<QualifiedName, Map<String, EntityReference>> namedAssociations = createNamedAssociations(jsonObject,
                entityDescriptor);

        return new DefaultEntityState(unitOfWork, version, modified,
                EntityReference.parseEntityReference(identity), status, entityDescriptor, properties,
                associations, manyAssociations, namedAssociations);
    } catch (JSONException e) {
        throw new EntityStoreException(e);
    }
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from  ww  w.j  a v a2 s  .c  om

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.mikecorrigan.trainscorekeeper.FragmentButton.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.vc(VERBOSE, TAG, "onCreateView: inflater=" + inflater + ", container=" + container
            + ", savedInstanceState=" + Utils.bundleToString(savedInstanceState));

    View rootView = inflater.inflate(R.layout.fragment_button, container, false);

    Bundle args = getArguments();/*w  w  w  .j a va  2  s .  c o m*/
    if (args == null) {
        Log.e(TAG, "onCreateView: missing arguments");
        return rootView;
    }

    // The activity must support a standard OnClickListener.
    final MainActivity mainActivity = (MainActivity) getActivity();
    final Context context = mainActivity;

    players = mainActivity.getPlayers();
    if (players != null) {
        players.addListener(mPlayersListener);
    }

    // final int index = args.getInt(ARG_INDEX);
    final String tabSpec = args.getString(ARG_TAB_SPEC);

    try {
        JSONObject jsonTab = new JSONObject(tabSpec);

        final String tabName = jsonTab.optString(JsonSpec.TAB_NAME, JsonSpec.DEFAULT_TAB_NAME);
        if (!TextUtils.isEmpty(tabName)) {
            TextView tv = (TextView) rootView.findViewById(R.id.text_view_name);
            tv.setText(tabName);
        }

        tabLayout = (LinearLayout) rootView;

        JSONArray jsonSections = jsonTab.getJSONArray(JsonSpec.SECTIONS_KEY);
        for (int i = 0; i < jsonSections.length(); i++) {
            JSONObject jsonSection = jsonSections.getJSONObject(i);

            LinearLayout sectionLayout = new LinearLayout(context);
            sectionLayout.setOrientation(LinearLayout.VERTICAL);
            tabLayout.addView(sectionLayout);

            // If a section is named, label it.
            final String sectionName = jsonSection.optString(JsonSpec.SECTION_NAME,
                    JsonSpec.DEFAULT_SECTION_NAME);
            if (!TextUtils.isEmpty(sectionName)) {
                TextView textView = new TextView(context);
                textView.setText(sectionName);
                sectionLayout.addView(textView);
            }

            int numColumns = jsonSection.optInt(JsonSpec.SECTION_COLUMNS, JsonSpec.DEFAULT_SECTION_COLUMNS);

            List<View> buttonViews = new LinkedList<View>();

            JSONArray buttons = jsonSection.getJSONArray(JsonSpec.BUTTONS_KEY);
            for (int k = 0; k < buttons.length(); k++) {
                JSONObject jsonButton = buttons.getJSONObject(k);

                ScoreButton buttonView = new ScoreButton(context);
                buttonView.setButtonSpec(jsonButton);
                buttonView.setOnClickListener(mainActivity.getScoreClickListener());

                // Add the button to the section.
                buttonViews.add(buttonView);
            }

            GridView gridView = new GridView(context);
            gridView.setNumColumns(numColumns);
            gridView.setAdapter(new ViewAdapter(context, buttonViews));
            sectionLayout.addView(gridView);
        }
    } catch (JSONException e) {
        Log.th(TAG, e, "onCreateView: failed to parse JSON");
    }

    updateUi();

    return rootView;
}

From source file:at.alladin.rmbt.android.views.ResultDetailsView.java

@Override
public void taskEnded(final JSONArray testResultDetail) {
    //if (getVisibility()!=View.VISIBLE)
    //    return;

    if (this.resultFetchEndTaskListener != null) {
        this.resultFetchEndTaskListener.taskEnded(testResultDetail);
    }/*from   w  w w . j  av a  2 s  . c o  m*/

    if (testResultDetail != null && testResultDetail.length() > 0
            && (testResultDetailTask == null || !testResultDetailTask.hasError())) {
        this.testResult = testResultDetail;

        System.out.println("testResultDetail: " + testResultDetail);

        try {

            HashMap<String, String> viewItem;

            for (int i = 0; i < testResultDetail.length(); i++) {

                final JSONObject singleItem = testResultDetail.getJSONObject(i);

                viewItem = new HashMap<String, String>();
                viewItem.put("name", singleItem.optString("title", ""));

                if (singleItem.has("time")) {
                    final String timeString = Helperfunctions.formatTimestampWithTimezone(
                            singleItem.optLong("time", 0), singleItem.optString("timezone", null),
                            true /* seconds */);
                    viewItem.put("value", timeString == null ? "-" : timeString);
                } else
                    viewItem.put("value", singleItem.optString("value", ""));
                itemList.add(viewItem);
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        }

        valueList = new SimpleAdapter(activity, itemList, R.layout.test_result_detail_item,
                new String[] { "name", "value" }, new int[] { R.id.name, R.id.value });

        listView.setAdapter(valueList);

        listView.invalidate();

        progessBar.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);

    } else {
        Log.i(DEBUG_TAG, "LEERE LISTE");
        progessBar.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        emptyView.setText(activity.getString(R.string.error_no_data));
        emptyView.invalidate();
    }

}