Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

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

public Webservice(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // set the xml version
    super();/* w  w  w  .  jav a 2 s  .  co  m*/

    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for query
        if (!"request".equals(key) && !"root".equals(key) && !"showLoading".equals(key)
                && !"successActions".equals(key) && !"errorActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // try and build the query object
    JSONObject jsonQuery = jsonAction.optJSONObject("request");

    // check we got one
    if (jsonQuery != null) {
        // get the parameters                  
        ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
        String type = jsonQuery.optString("type");
        String url = jsonQuery.optString("url");
        String action = jsonQuery.optString("action");
        String body = jsonQuery.optString("body");
        String transform = jsonQuery.optString("transform");
        String root = jsonQuery.optString("root");
        ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
        // make the object
        _request = new Request(inputs, type, url, action, body, transform, root, outputs);
    }

    // look for showLoading
    _showLoading = jsonAction.optBoolean("showLoading");

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some
    if (jsonSuccessActions != null) {
        // instantiate our success actions collection
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
    }

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some
    if (jsonErrorActions != null) {
        // instantiate our error actions collection
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
    }

}

From source file:rsInstanceJumpstart.rackspaceAccount.java

public String[][] listServers() {
    String[][] thisServerList = new String[100][5];
    //String thisServerList;
    HttpURLConnection connection;
    String output = "";
    int thisServerListCounter = 0;
    String thisServerLink;/*from  w  w  w  .ja  va 2 s . c om*/
    try {

        for (int i = 0; i < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog")
                .length(); i++) {
            if ("cloudServersOpenStack".equals(serviceCatalogJson.getJSONObject("access")
                    .getJSONArray("serviceCatalog").getJSONObject(i).get("name").toString())) {
                for (int ii = 0; ii < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog")
                        .getJSONObject(i).getJSONArray("endpoints").length(); ii++) {
                    String thisEndpoint = serviceCatalogJson.getJSONObject("access")
                            .getJSONArray("serviceCatalog").getJSONObject(i).getJSONArray("endpoints")
                            .getJSONObject(ii).get("publicURL").toString();
                    if (thisEndpoint.length() > 0) {
                        try {
                            output = "";
                            System.out.println("current endpoint: " + thisEndpoint);
                            connection = (HttpURLConnection) new URL(thisEndpoint + "/servers")
                                    .openConnection();

                            connection.setRequestProperty("Accept", "application/json");
                            connection.setRequestProperty("X-Auth-Token", currentAuthToken);

                            InputStream response;

                            response = connection.getInputStream();

                            //System.out.println(String.valueOf(connection.getResponseCode()));

                            BufferedReader reader = null;
                            try {
                                reader = new BufferedReader(new InputStreamReader(response));
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    output += line + "\n";
                                }
                            } finally {
                                if (reader != null) {
                                    try {
                                        reader.close();
                                    } catch (IOException e) {
                                        System.out.println(e);
                                    }
                                }
                            }
                        } catch (IOException e) {
                            System.out.println(e);
                        }
                        JSONObject thisResponseJson = new JSONObject(output);
                        if (thisResponseJson.getJSONArray("servers").length() > 0) {
                            for (int iii = 0; iii < thisResponseJson.getJSONArray("servers").length(); iii++) {
                                thisServerLink = thisResponseJson.getJSONArray("servers").getJSONObject(iii)
                                        .getJSONArray("links").getJSONObject(0).get("href").toString();
                                //query for details of each server

                                try {
                                    output = "";
                                    connection = (HttpURLConnection) new URL(thisServerLink).openConnection();

                                    connection.setRequestProperty("Accept", "application/json");
                                    connection.setRequestProperty("X-Auth-Token", currentAuthToken);

                                    InputStream response;

                                    response = connection.getInputStream();

                                    //System.out.println(String.valueOf(connection.getResponseCode()));

                                    BufferedReader reader = null;
                                    try {
                                        reader = new BufferedReader(new InputStreamReader(response));
                                        String line;
                                        while ((line = reader.readLine()) != null) {
                                            output += line + "\n";
                                        }
                                    } finally {
                                        if (reader != null) {
                                            try {
                                                reader.close();
                                            } catch (IOException e) {
                                                System.out.println(e);
                                            }
                                        }
                                    }
                                } catch (IOException e) {
                                    System.out.println(e);
                                }
                                //System.out.println(output);
                                JSONObject thisServer = new JSONObject(output);
                                System.out.println(thisServer.getJSONObject("server").get("name").toString());
                                if ("SHUTOFF".equals(thisServerList[thisServerListCounter][2] = thisServer
                                        .getJSONObject("server").getString("status"))) {
                                    thisServerList[thisServerListCounter][0] = thisServer
                                            .getJSONObject("server").getString("name");
                                    thisServerList[thisServerListCounter][1] = thisServer
                                            .getJSONObject("server").getString("id");
                                    thisServerList[thisServerListCounter][2] = thisServer
                                            .getJSONObject("server").getString("status");
                                    thisServerList[thisServerListCounter][3] = thisServerLink;
                                    thisServerList[thisServerListCounter][4] = thisServer
                                            .getJSONObject("server").getString("accessIPv4");
                                    System.out.println(thisServerList[thisServerListCounter][2]);
                                    thisServerListCounter++;
                                }
                            }
                        }
                    }

                }

            }

        }

    } catch (JSONException e) {
        //let's assume for now we won't have any
    }

    //thisServerList = output;
    return thisServerList;
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.SearchMovie.java

boolean isMovieInRPC(String searchString) {
    JSONArray arr;// w w  w .  j  a v a 2s  .  com
    boolean isInRPC = false;
    try {
        //Call async method to retrieve the movie list names and check in the movie list
        MethodInformation mi = new MethodInformation("http://10.0.2.2:8080/", "getTitles", new String[] {});
        JSONObject ac = new AsyncCollectionConnect().execute(mi).get();
        arr = (JSONArray) ac.get("result");

        //Check if the list has our movie name and set flag
        for (int i = 0; i < arr.length(); i++) {
            System.out.println(arr.get(i));
            String mv = (String) arr.get(i);
            if (mv.equalsIgnoreCase(searchString)) {
                isInRPC = true;
                break;
            }
        }
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }
    return isInRPC;
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.SearchMovie.java

void getMovieDetails(String searchString) {
    try {/*ww w  .  j  a  v a2  s.  co  m*/
        MethodInformation mi = new MethodInformation("http://10.0.2.2:8080/", "get",
                new String[] { searchString });
        JSONObject ac = new AsyncCollectionConnect().execute(mi).get();
        result = (JSONObject) ac.get("result");

        info[1].setText(result.getString("Title"));
        info[2].setText(result.getString("Genre"));
        info[3].setText(result.getString("Year"));
        info[4].setText(result.getString("Actors"));

        if (result.getString("Rated").equals("PG"))
            dropdown.setSelection(0);
        else if (result.getString("Rated").equals("PG-13"))
            dropdown.setSelection(1);
        else if (result.getString("Rated").equals("R"))
            dropdown.setSelection(2);

        videoFile = result.getString("Filename");
    } catch (Exception ex) {
        android.util.Log.w(this.getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }
}

From source file:com.serenegiant.media.TLMediaEncoder.java

private static final MediaFormat asMediaFormat(final String format_str) {
    MediaFormat format = new MediaFormat();
    try {//  w ww.  j  a  v a2  s. c  o m
        final JSONObject map = new JSONObject(format_str);
        if (map.has(MediaFormat.KEY_MIME))
            format.setString(MediaFormat.KEY_MIME, (String) map.get(MediaFormat.KEY_MIME));
        if (map.has(MediaFormat.KEY_WIDTH))
            format.setInteger(MediaFormat.KEY_WIDTH, (Integer) map.get(MediaFormat.KEY_WIDTH));
        if (map.has(MediaFormat.KEY_HEIGHT))
            format.setInteger(MediaFormat.KEY_HEIGHT, (Integer) map.get(MediaFormat.KEY_HEIGHT));
        if (map.has(MediaFormat.KEY_BIT_RATE))
            format.setInteger(MediaFormat.KEY_BIT_RATE, (Integer) map.get(MediaFormat.KEY_BIT_RATE));
        if (map.has(MediaFormat.KEY_COLOR_FORMAT))
            format.setInteger(MediaFormat.KEY_COLOR_FORMAT, (Integer) map.get(MediaFormat.KEY_COLOR_FORMAT));
        if (map.has(MediaFormat.KEY_FRAME_RATE))
            format.setInteger(MediaFormat.KEY_FRAME_RATE, (Integer) map.get(MediaFormat.KEY_FRAME_RATE));
        if (map.has(MediaFormat.KEY_I_FRAME_INTERVAL))
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL,
                    (Integer) map.get(MediaFormat.KEY_I_FRAME_INTERVAL));
        if (map.has(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER))
            format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER,
                    (Long) map.get(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER));
        if (map.has(MediaFormat.KEY_MAX_INPUT_SIZE))
            format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE,
                    (Integer) map.get(MediaFormat.KEY_MAX_INPUT_SIZE));
        if (map.has(MediaFormat.KEY_DURATION))
            format.setInteger(MediaFormat.KEY_DURATION, (Integer) map.get(MediaFormat.KEY_DURATION));
        if (map.has(MediaFormat.KEY_CHANNEL_COUNT))
            format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, (Integer) map.get(MediaFormat.KEY_CHANNEL_COUNT));
        if (map.has(MediaFormat.KEY_SAMPLE_RATE))
            format.setInteger(MediaFormat.KEY_SAMPLE_RATE, (Integer) map.get(MediaFormat.KEY_SAMPLE_RATE));
        if (map.has(MediaFormat.KEY_CHANNEL_MASK))
            format.setInteger(MediaFormat.KEY_CHANNEL_MASK, (Integer) map.get(MediaFormat.KEY_CHANNEL_MASK));
        if (map.has(MediaFormat.KEY_AAC_PROFILE))
            format.setInteger(MediaFormat.KEY_AAC_PROFILE, (Integer) map.get(MediaFormat.KEY_AAC_PROFILE));
        if (map.has(MediaFormat.KEY_AAC_SBR_MODE))
            format.setInteger(MediaFormat.KEY_AAC_SBR_MODE, (Integer) map.get(MediaFormat.KEY_AAC_SBR_MODE));
        if (map.has(MediaFormat.KEY_MAX_INPUT_SIZE))
            format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE,
                    (Integer) map.get(MediaFormat.KEY_MAX_INPUT_SIZE));
        if (map.has(MediaFormat.KEY_IS_ADTS))
            format.setInteger(MediaFormat.KEY_IS_ADTS, (Integer) map.get(MediaFormat.KEY_IS_ADTS));
        if (map.has("what"))
            format.setInteger("what", (Integer) map.get("what"));
        if (map.has("csd-0"))
            format.setByteBuffer("csd-0", asByteBuffer((String) map.get("csd-0")));
        if (map.has("csd-1"))
            format.setByteBuffer("csd-1", asByteBuffer((String) map.get("csd-1")));
    } catch (JSONException e) {
        Log.e(TAG_STATIC, "writeFormat:" + format_str, e);
        format = null;
    }
    return format;
}

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  va  2s .co  m*/
    // 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 testLog() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

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

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

        // modify
        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first change");
        addFile(testTxt);/*from  w  ww  .  j av  a  2 s .  co  m*/

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

        // modify again
        modifyFile(testTxt, "second change");
        addFile(testTxt);

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

        // get the full log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String initialGitCommitName = commit.getString(ProtocolConstants.KEY_NAME);
        String initialGitCommitURI = gitHeadUri.replaceAll(Constants.HEAD, initialGitCommitName);

        //get log for given page size
        commitsArray = log(gitHeadUri, 1, 1, false, true);
        assertEquals(1, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        //get log for second page
        commitsArray = log(gitHeadUri, 2, 1, true, true);
        assertEquals(1, commitsArray.length());

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

        // prepare a scoped log location
        request = getPostForScopedLogRequest(initialGitCommitURI, Constants.HEAD);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        String newGitCommitUri = response.getHeaderField(ProtocolConstants.KEY_LOCATION);
        assertEquals(newGitCommitUri,
                new JSONObject(response.getText()).getString(ProtocolConstants.KEY_LOCATION));

        // get a scoped log
        commitsArray = log(newGitCommitUri);
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

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

@Test
public void testLogWithParents() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

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

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

        // modify
        JSONObject testTxt = getChild(project, "test.txt");
        modifyFile(testTxt, "first change");
        addFile(testTxt);/*from   w w w. j a  va  2s  .c  o m*/

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

        // modify again
        modifyFile(testTxt, "second change");
        addFile(testTxt);

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

        // get the full log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(1, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
        String parent = commit.getJSONArray(ProtocolConstants.KEY_PARENTS).getJSONObject(0)
                .getString(ProtocolConstants.KEY_NAME);

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(parent, commit.get(ProtocolConstants.KEY_NAME));
        assertEquals(1, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
        parent = commit.getJSONArray(ProtocolConstants.KEY_PARENTS).getJSONObject(0)
                .getString(ProtocolConstants.KEY_NAME);

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(parent, commit.get(ProtocolConstants.KEY_NAME));
        assertEquals(0, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
    }
}

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

@Test
public void testLogAllBranches() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);
        String gitCommitUri = clone.getString(GitConstants.KEY_COMMIT);

        // get project metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        // create branch
        final String newBranchName = "branch";
        branch(branchesLocation, newBranchName);

        // modify
        JSONObject testTxt = getChild(project, "test.txt");
        modifyFile(testTxt, "first change");
        addFile(testTxt);/*from  w  ww . j av a 2  s .  c o  m*/

        // commit1
        Thread.sleep(1000); // TODO: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=370696#c1
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // checkout "branch"
        checkoutBranch(cloneLocation, newBranchName);

        // modify again
        modifyFile(testTxt, "second change");
        addFile(testTxt);

        // commit2
        Thread.sleep(1000); // TODO: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=370696#c1
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get standard log for HEAD - only init and commit2 should be visible
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        // get log for all branches - all 3 commits should be listed
        commitsArray = log(gitCommitUri);
        assertEquals(3, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        JSONArray branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_HEADS + newBranchName,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_HEADS + Constants.MASTER,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));
    }
}

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

@Test
public void testLogFolder() 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 ww .  j  av a2  s.com*/
    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(gitHeadUri);

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

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

    assertEquals(3, commitsArray.length());

    JSONObject commit = commitsArray.getJSONObject(0);
    assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

    commit = commitsArray.getJSONObject(1);
    assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

    commit = commitsArray.getJSONObject(2);
    assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

    log = logObject(folder.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));

    repositoryPath = log.getString(GitConstants.KEY_REPOSITORY_PATH);
    assertEquals("folder/", repositoryPath);

    commitsArray = log.getJSONArray(ProtocolConstants.KEY_CHILDREN);

    assertEquals(2, commitsArray.length());

    commit = commitsArray.getJSONObject(0);
    assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

    commit = commitsArray.getJSONObject(1);
    assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
}