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:weathernotificationservice.wns.activities.MainActivity.java

public static String getRainString(JSONObject rainObj) {
    String rain = "0";
    if (rainObj != null) {
        rain = rainObj.optString("3h", "fail");
        if ("fail".equals(rain)) {
            rain = rainObj.optString("1h", "0");
        }// ww w .  j  av a  2 s  .c om
    }
    return rain;
}

From source file:org.brickred.socialauth.provider.AmazonImpl.java

private Profile getProfile() throws Exception {
    String presp;//from  w ww . ja  va 2s . c  o  m

    try {
        Response response = authenticationStrategy.executeFeed(PROFILE_URL);
        presp = response.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
    }
    try {
        LOG.debug("User Profile : " + presp);
        JSONObject resp = new JSONObject(presp);
        Profile p = new Profile();
        p.setFullName(resp.optString("name", null));
        p.setEmail(resp.optString("email", null));
        p.setValidatedId(resp.optString("user_id", null));
        p.setLocation(resp.optString("postal_code", null));
        if (config.isSaveRawResponse()) {
            p.setRawResponse(presp);
        }
        p.setProviderId(getProviderId());
        if (config.isSaveRawResponse()) {
            p.setRawResponse(presp);
        }
        userProfile = p;
        return p;

    } catch (Exception ex) {
        throw new ServerDataException("Failed to parse the user profile json : " + presp, ex);
    }
}

From source file:com.jelly.music.player.GMusicHelpers.MobileClientPlaylistEntriesSchema.java

@Override
public MobileClientPlaylistEntriesSchema fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        mKind = jsonObject.optString("kind", null);
        mPlaylistId = jsonObject.optString("playlistId", null);
        mCreationTimestamp = jsonObject.optString("creationTimestamp");
        mLastModifiedTimestamp = jsonObject.optString("lastModifiedTimestamp", null);
        mDeleted = jsonObject.optBoolean("deleted");
        mClientId = jsonObject.optString("clientId");
        mTrackId = jsonObject.optString("trackId");
        mId = jsonObject.optString("id");
        mSource = jsonObject.optString("source");
    }//from  w  w  w  .  j av a  2  s .  com

    //This method returns itself to support chaining.
    return this;
}

From source file:com.rapid.actions.Webservice.java

@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control,
        JSONObject jsonDetails) throws Exception {

    String js = "";

    if (_request != null) {

        // get the rapid servlet
        RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();

        // get the most recent sequence number for this action to stop slow-running early requests overwriting the results of fast later requests
        js += "var sequence = getWebserviceActionSequence('" + getId() + "');\n";

        // drop in the query variable which holds our inputs and sequence
        js += "var query = { inputs:[], sequence:sequence };\n";

        // build the inputs
        if (_request.getInputs() != null) {
            for (Parameter parameter : _request.getInputs()) {
                String itemId = parameter.getItemId();
                if (itemId != null) {
                    // get any parameter field
                    String field = parameter.getField();
                    // check if there was one
                    if (field == null) {
                        // no field
                        js += "  query.inputs.push({id:'" + itemId + "',value:" + Control.getDataJavaScript(
                                rapidServlet.getServletContext(), application, page, itemId, null) + "});\n";
                    } else {
                        // got field so let in appear in the inputs for matching later
                        js += "  query.inputs.push({id:'" + itemId + "',value:"
                                + Control.getDataJavaScript(rapidServlet.getServletContext(), application, page,
                                        itemId, field)
                                + ",field:'" + field + "'});\n";
                    }// w  w  w .jav  a 2s .c om
                }
            }
        } // got inputs

        // control can be null when the action is called from the page load
        String controlParam = "";
        if (control != null)
            controlParam = "&c=" + control.getId();

        // get the outputs
        ArrayList<Parameter> outputs = _request.getOutputs();

        // instantiate the jsonDetails if required
        if (jsonDetails == null)
            jsonDetails = new JSONObject();
        // look for a working page in the jsonDetails
        String workingPage = jsonDetails.optString("workingPage", null);
        // look for an offline page in the jsonDetails
        String offlinePage = jsonDetails.optString("offlinePage", null);

        // get the js to show the loading (if applicable)
        if (_showLoading)
            js += "  " + getLoadingJS(page, outputs, true);

        // stringify the query
        js += "query = JSON.stringify(query);\n";

        // open the ajax call
        js += "$.ajax({ url : '~?a=" + application.getId() + "&v=" + application.getVersion() + "&p="
                + page.getId() + controlParam + "&act=" + getId()
                + "', type: 'POST', contentType: 'application/json', dataType: 'json',\n";
        js += "  data: query,\n";
        js += "  error: function(server, status, message) {\n";

        // if there is a working page
        if (workingPage != null) {
            // remove any working page dialogue 
            js += "    $('#" + workingPage + "dialogue').remove();\n";
            // remove any working page dialogue cover
            js += "    $('#" + workingPage + "cover').remove();\n";
            // remove the working page so as not to affect actions further down the tree
        }

        // hide the loading javascript (if applicable)
        if (_showLoading)
            js += "    " + getLoadingJS(page, outputs, false);

        // this avoids doing the errors if the page is unloading or the back button was pressed
        js += "    if (server.readyState > 0) {\n";

        // retain if error actions
        boolean errorActions = false;

        // prepare a default error hander we'll show if no error actions, or pass to child actions for them to use
        String defaultErrorHandler = "alert('Error with webservice action : ' + server.responseText||message);";
        // if we have an offline page
        if (offlinePage != null) {
            // update defaultErrorHandler to navigate to offline page
            defaultErrorHandler = "if (Action_navigate && typeof _rapidmobile != 'undefined' && !_rapidmobile.isOnline()) {\n        Action_navigate('~?a="
                    + application.getId() + "&v=" + application.getVersion() + "&p=" + offlinePage
                    + "&action=dialogue',true,'" + getId() + "');\n      } else {\n         "
                    + defaultErrorHandler + "\n      }";
            // remove the offline page so we don't interfere with actions down the three
            jsonDetails.remove("offlinePage");
        }

        // add any error actions
        if (_errorActions != null) {
            // count the actions
            int i = 0;
            // loop the actions
            for (Action action : _errorActions) {
                // retain that we have custom error actions
                errorActions = true;
                // if this is the last error action add in the default error handler
                if (i == _errorActions.size() - 1)
                    jsonDetails.put("defaultErrorHandler", defaultErrorHandler);
                // add the js
                js += "         " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails)
                        .trim().replace("\n", "\n         ") + "\n";
                // if this is the last error action and the default error handler is still present, remove it so it isn't sent down the success path
                if (i == _errorActions.size() - 1 && jsonDetails.optString("defaultErrorHandler", null) != null)
                    jsonDetails.remove("defaultErrorHandler");
                // increase the count
                i++;
            }
        }
        // add default error handler if none in collection
        if (!errorActions)
            js += "      " + defaultErrorHandler + "\n";

        // close unloading check
        js += "    }\n";

        // close error actions
        js += "  },\n";

        // open success function
        js += "  success: function(data) {\n";

        // get the js to hide the loading (if applicable)
        if (_showLoading)
            js += "  " + getLoadingJS(page, outputs, false);

        // check there are outputs
        if (outputs != null) {
            if (outputs.size() > 0) {
                // open if data check
                js += "    if (data) {\n";
                // the outputs array we're going to make
                String jsOutputs = "";
                // loop the output parameters
                for (int i = 0; i < outputs.size(); i++) {

                    // get the parameter
                    Parameter output = outputs.get(i);
                    // get the control the data is going into
                    Control outputControl = page.getControl(output.getItemId());
                    // try the application if still null
                    if (outputControl == null)
                        outputControl = application.getControl(rapidServlet.getServletContext(),
                                output.getItemId());
                    // check the control is still on the page
                    if (outputControl != null) {
                        // get any mappings we may have
                        String details = outputControl.getDetailsJavaScript(application, page);
                        // set to empty string or clean up
                        if (details == null) {
                            details = "";
                        } else {
                            details = ", details: " + details;
                        }
                        // append the javascript outputs
                        jsOutputs += "{id: '" + outputControl.getId() + "', type: '" + outputControl.getType()
                                + "', field: '" + output.getField() + "'" + details + "}";
                        // add a comma if not the last
                        if (i < outputs.size() - 1)
                            jsOutputs += ",";
                    }

                }
                js += "      var outputs = [" + jsOutputs + "];\n";
                // send them them and the data to the webservice action            
                js += "      Action_webservice(ev, '" + getId() + "', data, outputs);\n";
                // close if data check
                js += "    }\n";
            }
        }

        // if there is a working page (from the details)
        if (workingPage != null) {
            // remove any working page dialogue 
            js += "  $('#" + workingPage + "dialogue').remove();\n";
            // remove any working page dialogue cover
            js += "  $('#" + workingPage + "cover').remove();\n";
            // remove the working page so as not to affect actions further down the tree
            jsonDetails.remove("workingPage");
        }

        // add any sucess actions
        if (_successActions != null) {
            for (Action action : _successActions) {
                js += "    " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails)
                        .trim().replace("\n", "\n    ") + "\n";
            }
        }

        // close success function
        js += "  }\n";

        // close ajax call
        js += "});";
    }

    // return what we built         
    return js;
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public Object[] sync(Connection con) {
    mSyncMsg = "";
    // if the deck has any pending changes, flush them first and bump mod time
    mCol.save();/*from   w  w  w  .  j a v  a2 s  . c om*/
    // step 1: login & metadata
    HttpResponse ret = mServer.meta();
    if (ret == null) {
        return null;
    }
    int returntype = ret.getStatusLine().getStatusCode();
    if (returntype == 403) {
        return new Object[] { "badAuth" };
    } else if (returntype != 200) {
        return new Object[] { "error", returntype, ret.getStatusLine().getReasonPhrase() };
    }
    try {
        mCol.getDb().getDatabase().beginTransaction();
        try {
            // Log.i(AnkiDroidApp.TAG, "Sync: getting meta data from server");
            JSONObject rMeta = new JSONObject(mServer.stream2String(ret.getEntity().getContent()));
            long rscm = rMeta.getLong("scm");
            int rts = rMeta.getInt("ts");
            mRMod = rMeta.getLong("mod");
            mMaxUsn = rMeta.getInt("usn");
            mMediaUsn = rMeta.getInt("musn");
            mSyncMsg = rMeta.getString("msg");
            // skip uname, AnkiDroid already stores and shows it
            if (!rMeta.getBoolean("cont")) {
                // Don't add syncMsg; it can be fetched by UI code using the accessor
                return new Object[] { "serverAbort" };
            } else {
                // don't abort, but ui should show messages after sync finishes
                // and require confirmation if it's non-empty
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: building local meta data");
            JSONObject lMeta = meta();
            mLMod = lMeta.getLong("mod");
            mMinUsn = lMeta.getInt("usn");
            long lscm = lMeta.getLong("scm");
            int lts = lMeta.getInt("ts");

            long diff = Math.abs(rts - lts);
            if (diff > 300) {
                return new Object[] { "clockOff", diff };
            }
            if (mLMod == mRMod) {
                // Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning");
                return new Object[] { "noChanges" };
            } else if (lscm != rscm) {
                // Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning");
                return new Object[] { "fullSync" };
            }
            mLNewer = mLMod > mRMod;
            // step 2: deletions
            publishProgress(con, R.string.sync_deletions_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection removed data");
            JSONObject lrem = removed();
            JSONObject o = new JSONObject();
            o.put("minUsn", mMinUsn);
            o.put("lnewer", mLNewer);
            o.put("graves", lrem);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data");
            JSONObject rrem = mServer.start(o);
            if (rrem == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rrem.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rrem.get("errorType"), rrem.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: applying removed data");
            remove(rrem);
            // ... and small objects
            publishProgress(con, R.string.sync_small_objects_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection small changes");
            JSONObject lchg = changes();
            JSONObject sch = new JSONObject();
            sch.put("changes", lchg);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes");
            JSONObject rchg = mServer.applyChanges(sch);
            if (rchg == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rchg.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rchg.get("errorType"), rchg.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: merging small changes");
            mergeChanges(lchg, rchg);
            // step 3: stream large tables from server
            publishProgress(con, R.string.sync_download_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data");
                JSONObject chunk = mServer.chunk();
                if (chunk == null) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return null;
                }
                if (chunk.has("errorType")) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return new Object[] { "error", chunk.get("errorType"), chunk.get("errorReason") };
                }
                // Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data");
                applyChunk(chunk);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 4: stream to server
            publishProgress(con, R.string.sync_upload_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data");
                JSONObject chunk = chunk();
                JSONObject sech = new JSONObject();
                sech.put("chunk", chunk);
                // Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data");
                mServer.applyChunk(sech);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 5: sanity check during beta testing
            JSONObject c = sanityCheck();
            JSONObject sanity = mServer.sanityCheck2(c);
            if (sanity == null || !sanity.optString("status", "bad").equals("ok")) {
                return new Object[] { "sanityCheckError", null };
            }
            // finalize
            publishProgress(con, R.string.sync_finish_message);
            // Log.i(AnkiDroidApp.TAG, "Sync: sending finish command");
            long mod = mServer.finish();
            if (mod == 0) {
                return new Object[] { "finishError" };
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: finishing");
            finish(mod);

            publishProgress(con, R.string.sync_writing_db);
            mCol.getDb().getDatabase().setTransactionSuccessful();
        } finally {
            mCol.getDb().getDatabase().endTransaction();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (OutOfMemoryError e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "OutOfMemoryError" };
    } catch (IOException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "IOException" };
    }
    return new Object[] { "success" };
}

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

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

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

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

    // modify//from   w  w  w  .  j a  va2s. c om
    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "test.txt change");
    addFile(testTxt);

    // commit1
    WebRequest request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // modify again
    JSONObject folder = getChild(project, "folder");
    JSONObject folderTxt = getChild(folder, "folder.txt");
    modifyFile(folderTxt, "folder.txt change");
    addFile(folderTxt);

    // commit2
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // get log for file
    JSONObject log = logObject(testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));

    String repositoryPath = log.getString(GitConstants.KEY_REPOSITORY_PATH);
    assertEquals("test.txt", repositoryPath);

    JSONArray commitsArray = log.getJSONArray(ProtocolConstants.KEY_CHILDREN);

    assertEquals(2, commitsArray.length());

    JSONObject commit = commitsArray.getJSONObject(0);
    assertEquals("commit1", commit.getString(GitConstants.KEY_COMMIT_MESSAGE));

    // check commit content location
    assertEquals("test.txt change", getCommitContent(commit));

    // check commit diff location
    String[] parts = GitDiffTest.getDiff(commit.getString(GitConstants.KEY_DIFF));

    assertEquals("", parts[1]); // no diff between the commit and working tree

    // check commit location
    JSONObject jsonObject = logObject(commit.getString(ProtocolConstants.KEY_LOCATION));

    assertEquals(log.getString(GitConstants.KEY_CLONE), jsonObject.getString(GitConstants.KEY_CLONE));
    assertEquals(log.getString(GitConstants.KEY_REPOSITORY_PATH),
            jsonObject.getString(GitConstants.KEY_REPOSITORY_PATH));
    assertNull(jsonObject.optString(GitConstants.KEY_LOG_TO_REF, null));
    assertNull(jsonObject.optString(GitConstants.KEY_LOG_FROM_REF, null));
    assertThat(jsonObject.getJSONArray(ProtocolConstants.KEY_CHILDREN),
            isJSONArrayEqual(log.getJSONArray(ProtocolConstants.KEY_CHILDREN)));

    // check second commit      
    commit = commitsArray.getJSONObject(1);
    assertEquals("Initial commit", commit.getString(GitConstants.KEY_COMMIT_MESSAGE));
    // check commit content location
    assertEquals("test", getCommitContent(commit));

    // check commit diff location
    parts = GitDiffTest.getDiff(commit.getString(GitConstants.KEY_DIFF));

    StringBuilder sb = new StringBuilder();
    sb.append("diff --git a/test.txt b/test.txt").append("\n");
    sb.append("index 30d74d2..3146ed5 100644").append("\n");
    sb.append("--- a/test.txt").append("\n");
    sb.append("+++ b/test.txt").append("\n");
    sb.append("@@ -1 +1 @@").append("\n");
    sb.append("-test").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    sb.append("+test.txt change").append("\n");
    sb.append("\\ No newline at end of file").append("\n");
    assertEquals(sb.toString(), parts[1]);

    // check commit location
    jsonObject = logObject(commit.getString(ProtocolConstants.KEY_LOCATION));
    JSONObject log2 = log;
    JSONArray commitsArray2 = log2.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    commitsArray2.remove(0);
    assertEquals(log.getString(GitConstants.KEY_CLONE), jsonObject.getString(GitConstants.KEY_CLONE));
    assertEquals(log.getString(GitConstants.KEY_REPOSITORY_PATH),
            jsonObject.getString(GitConstants.KEY_REPOSITORY_PATH));
    assertNull(jsonObject.optString(GitConstants.KEY_LOG_TO_REF, null));
    assertNull(jsonObject.optString(GitConstants.KEY_LOG_FROM_REF, null));
    assertThat(commitsArray2, isJSONArrayEqual(log.getJSONArray(ProtocolConstants.KEY_CHILDREN)));
}

From source file:org.eclipse.orion.server.tests.performance.GitPerformanceTest.java

@Test
public void readProjectNonDefaultLocationChildren()
        throws CoreException, IOException, SAXException, JSONException {

    // org.eclipse.e4.webide.server.tests.servlets.workspace.WorkspaceServiceTest.testCreateProjectNonDefaultLocation()
    // +//from   w ww. ja va2  s  . com
    //org.eclipse.e4.webide.server.tests.servlets.files.CoreFilesTest.testReadDirectoryChildren()
    // + 
    // PerformanceMeter

    Performance perf = Performance.getDefault();
    PerformanceMeter perfMeter = perf
            .createPerformanceMeter(this.getClass().getName() + '#' + getMethodName() + "()"); //$NON-NLS-1$

    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#" + getMethodName();
    WebResponse response = createWorkspace(workspaceName);
    URL workspaceLocation = response.getURL();

    GitFileStore projectLocation = initRemoteGitRepository();

    try {

        for (int i = 0; i < 100; i++) {

            perfMeter.start();

            // create a project
            String projectName = "GitProject" + System.currentTimeMillis();
            JSONObject body = new JSONObject();
            body.put("ContentLocation", projectLocation.toString());
            InputStream in = new ByteArrayInputStream(body.toString().getBytes());
            WebRequest request = new PostMethodWebRequest(workspaceLocation.toString(), in, "UTF-8");
            if (projectName != null)
                request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
            request.setHeaderField("EclipseWeb-Version", "1");
            request.setHeaderField(ProtocolConstants.KEY_CREATE_IF_DOESNT_EXIST,
                    Boolean.toString(Boolean.FALSE));
            setAuthentication(request);
            response = webConversation.getResponse(request);
            assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
            JSONObject project = new JSONObject(response.getText());
            assertEquals(projectName, project.getString("Name"));
            String projectId = project.optString("Id", null);
            assertNotNull(projectId);

            // get children
            request = getGetFilesRequest(projectId + "?depth=1");
            response = webConversation.getResponse(request);
            assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

            List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));

            /* expected children: .git, .gitignore, file0.txt, folder1 */
            assertEquals("Wrong number of directory children", 4, children.size());

            for (JSONObject child : children) {
                if (child.getString("Name").startsWith(".git"))
                    continue; // ignore git metadata
                if (child.getBoolean("Directory")) {
                    checkDirectoryMetadata(child, "folder1", null, null, null, null, null);
                } else {
                    checkFileMetadata(child, "file0.txt", null, null, null, null, null, null, null);
                }
            }

            perfMeter.stop();
        }

        perfMeter.commit();
        perf.assertPerformance(perfMeter);
    } finally {
        perfMeter.dispose();
    }

    // TODO: clean up
    // FileSystemHelper.clear(root.getLocalFile());
    // FileSystemHelper.clear(repositoryPath.toFile());
}

From source file:org.eclipse.orion.server.tests.performance.GitPerformanceTest.java

@Test
public void setFileContents() throws IOException, SAXException, CoreException, JSONException {
    Performance perf = Performance.getDefault();
    PerformanceMeter perfMeter = perf//from w  w  w . j a v a 2 s  .c o  m
            .createPerformanceMeter(this.getClass().getName() + '#' + getMethodName() + "()"); //$NON-NLS-1$

    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#" + getMethodName();
    WebResponse response = createWorkspace(workspaceName);
    URL workspaceLocation = response.getURL();

    GitFileStore projectLocation = initRemoteGitRepository();

    // create a project
    String projectName = "GitProject" + System.currentTimeMillis();
    JSONObject body = new JSONObject();
    body.put("ContentLocation", projectLocation.toString());
    InputStream in = new ByteArrayInputStream(body.toString().getBytes());
    WebRequest request = new PostMethodWebRequest(workspaceLocation.toString(), in, "UTF-8");
    if (projectName != null)
        request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
    request.setHeaderField("EclipseWeb-Version", "1");
    request.setHeaderField(ProtocolConstants.KEY_CREATE_IF_DOESNT_EXIST, Boolean.toString(Boolean.FALSE));
    setAuthentication(request);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString("Name"));
    String projectId = project.optString("Id", null);
    assertNotNull(projectId);

    // TODO: create folder

    try {

        for (int i = 0; i < 100; i++) {

            perfMeter.start();

            long now = System.currentTimeMillis();
            request = getPutFileRequest(projectId + "/file0.txt", Long.toString(now));
            response = webConversation.getResponse(request);
            assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

            perfMeter.stop();

            request = getGetFilesRequest(projectId + "/file0.txt");
            response = webConversation.getResponse(request);
            assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
            assertEquals("Invalid file content", Long.toString(now), response.getText());
        }

        perfMeter.commit();
        perf.assertPerformance(perfMeter);
    } finally {
        perfMeter.dispose();
    }

    // TODO: clean up
    // FileSystemHelper.clear(root.getLocalFile());
    // FileSystemHelper.clear(repositoryPath.toFile());
}

From source file:com.google.blockly.model.FieldLabel.java

public static FieldLabel fromJson(JSONObject json) {
    return new FieldLabel(json.optString("name", null), json.optString("text", ""));
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *//* w  w w .j  a  va 2 s .c  o m*/
public static ArrayList<VerifiedPurchase> verifyPurchase(Context context, String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConsts.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }
    boolean verified = false;
    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */

        SharedPreferences pref = context.getSharedPreferences("billingPK", 0);
        AESObfuscator obfuscator = AESObfuscator.getDefaultObfuscator(context);
        String publicKey = "";
        try {
            publicKey = obfuscator.unobfuscate(pref.getString("pk", ""));
        } catch (Exception e) {
            Log.e(TAG, "Error getting publicc key from repository");
            return null;
        }
        PublicKey key = BillingSecurity.generatePublicKey(publicKey);
        verified = BillingSecurity.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!BillingSecurity.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            //String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a verified nonce.
            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }
            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}