Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:com.domuslink.elements.Alias.java

public Alias(JSONObject jsonElement) throws Exception {
    super();/*from ww  w  . ja  va 2 s  . co  m*/
    setState(0);
    setDimLevel(0);
    try {
        setLabel(jsonElement.getString("label"));
        setAliasMapElement(new AliasMap(jsonElement.getJSONObject("aliasMapElement")));
        if (!this.aliasMapElement.getElementType().contentEquals("Scene")) {
            setHouseCode(jsonElement.getString("houseCode"));
            setDevices(jsonElement.getString("devices"));
            setModuleType(jsonElement.getString("moduleType"));
            setModuleOptions(jsonElement.getString("moduleOptions"));
            setElementType(jsonElement.getString("elementType"));
            setElementLine(jsonElement.getString("elementLine"));
            setLineNum(jsonElement.getInt("lineNum"));
            setArrayNum(jsonElement.getInt("arrayNum"));
            setEnabled(jsonElement.getBoolean("enabled"));
            this.isScene = false;
            if (devices.indexOf(",") > 0 || devices.indexOf("-") > 0)
                this.isMultiAlias = true;
            else
                this.isMultiAlias = false;
        } else {
            this.isScene = true;
            this.isMultiAlias = false;
        }
    } catch (Exception e) {
        Log.e(TAG, "Error getting alias from JSONObject", e);
        throw e;
    }

}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;/*from   ww  w.ja  v  a2s  . c o m*/
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}

From source file:controlador.Controlador.java

private Destino handleUsuario(HttpServletRequest request, HttpServletResponse response, String op,
        String accion, String origen) throws JSONException {

    switch (op) {
    case "login":
        if (origen.equals("android")) {
            JSONObject obj = GestorUsuario.getLogin(request.getParameter("login"),
                    request.getParameter("pass"));
            return new Destino(Camino.print, "", obj.toString());
        }/*from   www  .jav  a 2 s  .  com*/
        if (origen.equals("web")) {
            JSONObject obj = GestorUsuario.getLogin(request.getParameter("login"),
                    request.getParameter("pass"));
            if (obj.getBoolean("r")) {
                List<Keep> keeps = GestorKeep.listKeeps(request.getParameter("login"));
                request.setAttribute("listado", keeps);
                request.setAttribute("login", GestorUsuario.getUserbyName(request.getParameter("login")));
                return new Destino(Camino.forward, "/WEB-INF/viewkeeps.jsp", keeps.toString());
            } else {
                return new Destino(Camino.print, "index.html", obj.toString());
            }
        }

    }
    return null;
}

From source file:produvia.com.scanner.LoginActivity.java

@Override
public void onTaskCompleted(final int flag, final JSONObject data) {
    runOnUiThread(new Runnable() {
        @Override/*  w  w w . j av  a2 s  . c o m*/
        public void run() {
            try {
                JSONObject json = data;

                if (json.getBoolean("success")) {

                    /**************************************************************************
                     * The user has been logged in - let's move on to the lights list activity
                     **************************************************************************/
                    Intent intent = new Intent(LoginActivity.this, DevicesActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    /**************************************************************************
                     * Sign in wasn't successful:
                     **************************************************************************/
                    showLoginView();
                    if (json.has("info"))
                        Toast.makeText(LoginActivity.this, json.getString("info"), Toast.LENGTH_LONG).show();

                }

            } catch (Exception e) {
                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });

}

From source file:org.cvrgrid.waveform.backing.GlobusUploadBacking.java

/**
 * Private API that polls all the endpoints for a user.
 *//*from   www . ja va2  s. c  om*/
private Status getEndpoints(JSONTransferAPIClient client, String query, String endpointType) {

    try {

        JSONTransferAPIClient.Result r = client.getResult(query);
        Map<String, GlobusEndpointList> globusEndpointLists = this.getGlobusEndpointLists();
        GlobusEndpointList globusEndpointList = globusEndpointLists.get(endpointType);
        logger.info("Endpoint Listing " + query + " for " + client.getUsername() + ": ");
        Iterator<?> keys = r.document.keys();
        while (keys.hasNext()) {
            String next = (String) keys.next();
            if (next.equalsIgnoreCase("data_type")) {

                globusEndpointList.setDataType(r.document.getString(next));

            } else if (next.equalsIgnoreCase("length")) {

                globusEndpointList.setLength(new Integer(r.document.getString(next)));

            } else if (next.equalsIgnoreCase("limit")) {

                globusEndpointList.setLimit(r.document.getString(next));

            } else if (next.equalsIgnoreCase("offset")) {

                globusEndpointList.setOffset(r.document.getString(next));

            } else if (next.equalsIgnoreCase("total")) {

                globusEndpointList.setTotal(r.document.getString(next));

            } else if (next.equalsIgnoreCase("data")) {
                JSONArray data = r.document.getJSONArray(next);
                int size = data.length();
                ArrayList<GlobusEndpoint> globusEndpoints = new ArrayList<GlobusEndpoint>();
                for (int j = 0; j < size; j++) {
                    GlobusEndpoint globusEndpoint = new GlobusEndpoint();
                    JSONObject globusEndpointInfo = data.getJSONObject(j);
                    Iterator<?> keys2 = globusEndpointInfo.keys();
                    while (keys2.hasNext()) {
                        String next2 = (String) keys2.next();
                        if (next2.equalsIgnoreCase("data_type")) {

                            globusEndpoint.setDataType(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("username")) {

                            globusEndpoint.setUserName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("globus_connect_setup_key")) {

                            globusEndpoint.setGlobusConnectSetupKey(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("name")) {

                            globusEndpoint.setName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("activated")) {

                            globusEndpoint.setActivated(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("is_globus_connect")) {

                            globusEndpoint.setIsGlobusConnect(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("ls_link")) {

                            JSONObject linkInfo = globusEndpointInfo.getJSONObject(next2);
                            GlobusLink lsLink = new GlobusLink();
                            Iterator<?> keys3 = linkInfo.keys();
                            while (keys3.hasNext()) {

                                String next3 = (String) keys3.next();
                                if (next3.equalsIgnoreCase("data_type")) {

                                    lsLink.setDataType(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("href")) {

                                    lsLink.setHref(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("resource")) {

                                    lsLink.setResource(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("relationship")) {

                                    lsLink.setRelationship(linkInfo.getString(next3));

                                } else if (next3.equalsIgnoreCase("title")) {

                                    lsLink.setTitle(linkInfo.getString(next3));

                                }

                            }
                            globusEndpoint.setLsLink(lsLink);

                        } else if (next2.equalsIgnoreCase("canonical_name")) {

                            globusEndpoint.setCanonicalName(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("myproxy_server")) {

                            globusEndpoint.setMyProxyServer(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("expire_time")) {

                            //globusEndpoint.setExpireTime(new Date(globusEndpointInfo.getString(next2)));

                        } else if (next2.equalsIgnoreCase("public")) {

                            globusEndpoint.setGlobusPublic(globusEndpointInfo.getBoolean(next2));

                        } else if (next2.equalsIgnoreCase("description")) {

                            globusEndpoint.setDescription(globusEndpointInfo.getString(next2));

                        } else if (next2.equalsIgnoreCase("data")) {

                            JSONArray serverData = globusEndpointInfo.getJSONArray(next2);
                            int serverDataSize = serverData.length();
                            ArrayList<GlobusServer> globusServers = new ArrayList<GlobusServer>();
                            for (int k = 0; k < serverDataSize; k++) {
                                GlobusServer globusServer = new GlobusServer();
                                JSONObject globusServerInfo = serverData.getJSONObject(k);
                                Iterator<?> keys4 = globusServerInfo.keys();
                                while (keys4.hasNext()) {
                                    String next4 = (String) keys4.next();
                                    if (next4.equalsIgnoreCase("data_type")) {

                                        globusServer.setDataType(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("id")) {

                                        globusServer.setId(globusServerInfo.getInt(next4));

                                    } else if (next4.equalsIgnoreCase("hostname")) {

                                        globusServer.setHostname(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("uri")) {

                                        globusServer.setUri(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("scheme")) {

                                        globusServer.setScheme(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("port")) {

                                        if (globusServerInfo.get("port").toString().equalsIgnoreCase("null")) {

                                            globusServer.setPort(0);

                                        } else {

                                            globusServer.setPort(globusServerInfo.getInt(next4));

                                        }

                                    } else if (next4.equalsIgnoreCase("subject")) {

                                        globusServer.setSubject(globusServerInfo.getString(next4));

                                    } else if (next4.equalsIgnoreCase("is_connected")) {

                                        globusServer.setIsConnected(globusServerInfo.getBoolean(next4));

                                    }

                                }
                                globusServers.add(globusServer);
                            }
                            globusEndpoint.setGlobusServers(globusServers);
                        }

                    }
                    globusEndpoints.add(globusEndpoint);
                }
                globusEndpointList.setGlobusEndpoints(globusEndpoints);
            }

        }

        globusEndpointLists.put(endpointType, globusEndpointList);
        this.setGlobusEndpointLists(globusEndpointLists);
        return Status.OK;

    } catch (Exception e) {

        logger.error("Got an exception..\n");
        logger.error(e.getMessage());
        logger.error(e.getStackTrace().toString());
        e.printStackTrace();
        return Status.FAIL;

    }

}

From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java

public ScanexSubscriptionItem(GetFiresService c, JSONObject object) {
    Prepare(c);/* ww w  .  j a  v a2 s.co m*/
    try {
        this.nID = object.getLong("id");
        this.sTitle = object.getString("title");
        this.sLayerName = object.getString("layer_name");
        this.sWKT = object.getString("wkt");
        this.bSMSEnable = object.getBoolean("sms_enabled");

        JSONArray jsonArray = object.getJSONArray("items");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            ScanexNotificationItem Item = new ScanexNotificationItem(c, jsonObject);
            if (Item.GetId() != -1) {
                mmoItems.put(Item.GetId(), Item);
            }
        }

    } catch (JSONException e) {
        SendError(e.getLocalizedMessage());
    }
}

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();/*  ww w.  ja v a2  s.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 testToRefKey() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

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

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        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);

        // git log for HEAD
        JSONObject log = logObject(gitHeadUri);

        // project contains only initial commit, so HEAD points to master branch
        // information about master branch is expected
        JSONObject toRef = log.getJSONObject(GitConstants.KEY_LOG_TO_REF);

        assertEquals(gitHeadUri, toRef.getString(GitConstants.KEY_HEAD));
        assertEquals(gitSection.getString(GitConstants.KEY_CLONE), toRef.getString(GitConstants.KEY_CLONE));
        assertEquals(GitConstants.KEY_BRANCH_NAME, toRef.getString(ProtocolConstants.KEY_TYPE));
        assertEquals(Constants.MASTER, toRef.getString(ProtocolConstants.KEY_NAME));
        assertEquals(true, toRef.getBoolean(GitConstants.KEY_BRANCH_CURRENT));
    }// w  w w.j  av  a2 s.  c  om
}

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

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

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

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        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);

        String logUri = gitHeadUri.replace(Constants.HEAD, Constants.HEAD + ".." + Constants.HEAD);
        // git log for HEAD..HEAD
        JSONObject log = logObject(logUri);

        // project contains only initial commit, so HEAD points to master branch
        // information about master branch is expected
        JSONObject fromRef = log.getJSONObject(GitConstants.KEY_LOG_FROM_REF);

        assertEquals(gitHeadUri, fromRef.getString(GitConstants.KEY_HEAD));
        assertEquals(gitSection.getString(GitConstants.KEY_CLONE), fromRef.getString(GitConstants.KEY_CLONE));
        assertEquals(GitConstants.KEY_BRANCH_NAME, fromRef.getString(ProtocolConstants.KEY_TYPE));
        assertEquals(Constants.MASTER, fromRef.getString(ProtocolConstants.KEY_NAME));
        assertEquals(true, fromRef.getBoolean(GitConstants.KEY_BRANCH_CURRENT));
    }/* w ww  . j a  v a2 s.c o  m*/
}

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.  j  av  a2s.c  om
    //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());
}