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:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

/**
 * Tests creating a project that is stored at a non-default location on the server.
 *///from  w w w . j a va2  s . c o  m
@Test
public void testCreateProjectNonDefaultLocation() throws IOException, SAXException, JSONException {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProjectNonDefaultLocation";
    URI workspaceLocation = createWorkspace(workspaceName);

    String tmp = System.getProperty("java.io.tmpdir");
    File projectLocation = new File(new File(tmp), "Orion-testCreateProjectNonDefaultLocation");
    toDelete.add(EFS.getLocalFileSystem().getStore(projectLocation.toURI()));
    projectLocation.mkdir();

    //at first forbid all project locations
    ServletTestingSupport.allowedPrefixes = null;

    //create a project
    String projectName = "My Project";
    WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, projectLocation.toString());
    if (projectName != null)
        request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode());

    //now set the allowed prefixes and try again
    ServletTestingSupport.allowedPrefixes = projectLocation.toString();
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
    String projectId = project.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(projectId);
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testGetWorkspaces() throws IOException, SAXException, JSONException {
    WebRequest request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);/*from   w ww.  j  av a 2s.  co  m*/
    WebResponse response = webConversation.getResponse(request);

    //before creating an workspaces we should get an empty list
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    String userId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(userId);
    assertEquals(testUserId, responseObject.optString("UserName"));
    JSONArray workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(0, workspaces.length());

    //now create a workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testGetWorkspaces";
    response = basicCreateWorkspace(workspaceName);
    responseObject = new JSONObject(response.getText());
    String workspaceId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(workspaceId);

    //get the workspace list again
    request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);
    response = webConversation.getResponse(request);

    //assert that the workspace we created is found by a subsequent GET
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    assertEquals(userId, responseObject.optString(ProtocolConstants.KEY_ID));
    assertEquals(testUserId, responseObject.optString("UserName"));
    workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(1, workspaces.length());
    JSONObject workspace = (JSONObject) workspaces.get(0);
    assertEquals(workspaceId, workspace.optString(ProtocolConstants.KEY_ID));
    assertNotNull(workspace.optString(ProtocolConstants.KEY_LOCATION, null));
}

From source file:com.rdsic.pcm.service.pe.ProcessFunction.java

public String prepareInput(String jsonStr) throws PCMException {
    if (Util.isNullOrEmpty(jsonStr)) {
        throw new PCMException("Invalid json data input", Constant.STATUS_CODE.ERR_SYSTEM_FAIL);
    }//  w w  w. j  ava2  s.  c o  m
    JSONObject jsonObj = new JSONObject(jsonStr);

    List<Oprtag> tags = GenericHql.INSTANCE.query("from Oprtag where oprcode=:function order by seq ",
            new Object[] { "function", this.function });
    StringWriter sw = new StringWriter();
    for (int i = 0; i < tags.size(); i++) {
        Oprtag tag = (Oprtag) tags.get(i);
        String tagName = tag.getId().getTag();
        if ((tag.getRequired()) && (!jsonObj.has(tagName))) {
            throw new PCMException("Tag name is required: " + tagName, Constant.STATUS_CODE.ERR_DATA_REQUIRED);
        }
        String tagVal = jsonObj.optString(tagName, tag.getDefval());
        sw.append(tag.getId().getTag().toUpperCase()).append("=").append(tagVal);
        if (i < tags.size() - 1) {
            sw.append(Constant.GLOBAL.PCM_DATA_DELIMITER);
        }
    }
    return sw.toString();
}

From source file:uk.ac.imperial.presage2.web.export.AgentPropertyColumn.java

AgentPropertyColumn(JSONObject column, boolean timeSeries) throws JSONException {
    super(ColumnType.AGENT_PROPERTY,
            column.optString(JSON_NAME_KEY,
                    column.getString(JSON_PROPERTY_KEY) + "-" + column.getString(JSON_FUNCTION_KEY)),
            column.getString(JSON_PROPERTY_KEY), GroupFunction.get(column.getString(JSON_FUNCTION_KEY)),
            timeSeries);/*from  w  ww.  j a  v  a 2 s  . c  o m*/
    if (column.has(JSON_CONDITION_KEY)) {
        condition = new RootCondition(column.getJSONObject(JSON_CONDITION_KEY));
    } else {
        condition = null;
    }
}

From source file:com.facebook.notifications.internal.content.TextContent.java

public TextContent(@NonNull JSONObject json) throws JSONException {
    text = json.optString("text", "");
    textColor = ColorAssetHandler.fromRGBAHex(json.optString("color"));

    typeface = json.optString("font");
    typefaceSize = (float) json.optDouble("size", 18); // Default to 18sp, or 'medium' size.

    textAlignment = Alignment.parse(json.optString("align", "center"));
}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;/*  w  w w .  j  a  va  2 s.  com*/

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            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 leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

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

            log.info("fetched exchange rates from {}, took {} ms", url, (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.ScoreEvent.java

public ScoreEvent(int playerId, final String playerName, JSONObject jsonButton) {
    this.playerId = playerId;
    this.playerName = playerName;
    this.type = jsonButton.optInt(JsonSpec.BUTTON_TYPE, JsonSpec.DEFAULT_BUTTON_TYPE);
    this.value = jsonButton.optInt(JsonSpec.BUTTON_VALUE, JsonSpec.DEFAULT_BUTTON_VALUE);
    this.history = jsonButton.optString(JsonSpec.BUTTON_HISTORY, JsonSpec.DEFAULT_BUTTON_HISTORY);

    Log.vc(VERBOSE, TAG, "ctor: " + this);
}

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

public ScoreEvent(JSONObject jsonScoreEvent) {
    this.playerId = jsonScoreEvent.optInt(JsonSpec.SCORE_ID, JsonSpec.DEFAULT_SCORE_ID);
    this.playerName = jsonScoreEvent.optString(JsonSpec.SCORE_NAME, JsonSpec.DEFAULT_SCORE_NAME);
    this.type = jsonScoreEvent.optInt(JsonSpec.SCORE_TYPE, JsonSpec.DEFAULT_SCORE_TYPE);
    this.value = jsonScoreEvent.optInt(JsonSpec.SCORE_VALUE, JsonSpec.DEFAULT_SCORE_VALUE);
    this.history = jsonScoreEvent.optString(JsonSpec.SCORE_HISTORY, JsonSpec.DEFAULT_SCORE_HISTORY);

    Log.vc(VERBOSE, TAG, "ctor: " + this);
}

From source file:com.rathravane.drumlin.examples.accounts.exampleAcctPersistence.java

private recordInfo readIndexedObject(String indexName, String key, String type)
        throws DrumlinAccountsException {
    try {//w  ww . j  a  v a2  s. c o m
        final long index = readIndex(indexName, key);
        if (index >= 0) {
            final JSONObject result = fStore.read(index);
            if (result.optString(kField_Type, "").equals(type)) {
                return new recordInfo(index, result);
            }
        }
        return null;
    } catch (IOException e) {
        throw new DrumlinAccountsException(e);
    }
}

From source file:net.netheos.pcsapi.credentials.OAuth2Credentials.java

static OAuth2Credentials fromJson(JSONObject jsonObj) {
    String accessToken = jsonObj.optString(OAuth2Credentials.ACCESS_TOKEN, null);
    Date expiresAt = calculateExpiresAt(jsonObj);
    String refreshToken = jsonObj.optString(OAuth2.REFRESH_TOKEN, null);
    String tokenType = jsonObj.optString(OAuth2Credentials.TOKEN_TYPE, null);

    return new OAuth2Credentials(accessToken, expiresAt, refreshToken, tokenType);
}