Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:org.catnut.fragment.TweetFragment.java

private void toggleFavorite() {
    mRequestQueue.add(/*from ww  w.j ava  2  s .  c  o  m*/
            new CatnutRequest(getActivity(), mFavorited ? FavoritesAPI.destroy(mId) : FavoritesAPI.create(mId),
                    new StatusProcessor.FavoriteTweetProcessor(), new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Toast.makeText(getActivity(),
                                    mFavorited ? R.string.cancle_favorite_success : R.string.favorite_success,
                                    Toast.LENGTH_SHORT).show();
                            mFavorited = !mFavorited;
                            // ?ui
                            JSONObject status = response.optJSONObject(Status.SINGLE);
                            mReplayCount.setText(CatnutUtils.approximate(status.optInt(Status.comments_count)));
                            mReteetCount.setText(CatnutUtils.approximate(status.optInt(Status.reposts_count)));
                            mFavoriteCount
                                    .setText(CatnutUtils.approximate(status.optInt(Status.attitudes_count)));
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            WeiboAPIError weiboAPIError = WeiboAPIError.fromVolleyError(error);
                            Toast.makeText(getActivity(), weiboAPIError.error, Toast.LENGTH_SHORT).show();
                        }
                    }))
            .setTag(TAG);
}

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

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

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

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);//  ww  w  . j a  va 2 s .c  om
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git merge master"
    JSONObject merge = merge(gitHeadUri, Constants.MASTER, true);
    MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
    assertEquals(MergeStatus.ALREADY_UP_TO_DATE, mergeResult);
}

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

@Test
public void testMergeSquashConflict() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);/*from   w w  w  .  j  a  v  a 2 s .  c  o  m*/
    String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE, null);
    assertNotNull(gitRemoteUri);

    // create branch 'a'
    branch(branchesLocation, "a");

    // checkout 'a'
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
    Git git = new Git(db1);
    assertBranchExist(git, "a");
    checkoutBranch(cloneLocation, "a");

    // modify while on 'a'
    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "change in a");

    gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git add ."
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

    // assert clean
    assertStatus(StatusResult.CLEAN, gitStatusUri);

    // checkout 'master'
    checkoutBranch(cloneLocation, Constants.MASTER);

    // modify the same file on master
    modifyFile(testTxt, "change in master");

    gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // "git add ."
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

    // assert clean
    assertStatus(StatusResult.CLEAN, gitStatusUri);

    // merge: "git merge a"
    JSONObject merge = merge(gitHeadUri, "a", true);
    MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
    assertEquals(MergeStatus.CONFLICTING, mergeResult);

    // check status
    assertStatus(new StatusResult().setConflictingNames("test.txt"), gitStatusUri);

    request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String[] responseLines = response.getText().split("\n");
    assertEquals(5, responseLines.length);
    assertEquals("<<<<<<< HEAD", responseLines[0]);
    assertEquals("change in master", responseLines[1]);
    assertEquals("=======", responseLines[2]);
    assertEquals("change in a", responseLines[3]);
    // ignore the last line since it's different each time
    // assertEquals(">>>>>>> c5ddb0e22e7e829683bb3b336ca6cb24a1b5bb2e", responseLines[4]);

    // TODO: check commits, bug 340051
}

From source file:com.soomla.cocos2dx.profile.ProfileBridge.java

/**
 * Constructor/*from  w ww.j  ava  2  s . co  m*/
 *
 * The main constructor for the bridge.
 * Registers all glue between native and Cocos2dx
 */
public ProfileBridge() {
    profileEventHandlerBridge = new ProfileEventHandlerBridge();

    final DomainFactory domainFactory = DomainFactory.getInstance();

    domainFactory.registerCreator(ProfileConsts.JSON_JSON_TYPE_USER_PROFILE,
            new DomainFactory.Creator<UserProfile>() {
                @Override
                public UserProfile create(JSONObject jsonObject) {
                    try {
                        return new UserProfile(jsonObject);
                    } catch (JSONException e) {
                        throw new IllegalStateException(e);
                    }
                }
            });

    final NdkGlue ndkGlue = NdkGlue.getInstance();

    ndkGlue.registerCallHandler("CCProfileBridge::init", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            HashMap<IProvider.Provider, HashMap<String, String>> providerParams = parseProviderParams(
                    params.optJSONObject("params"));
            SoomlaUtils.LogDebug("SOOMLA", "initialize is called from java!");
            SoomlaProfile.getInstance().initialize(providerParams);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::login", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().login(ndkGlue.getActivityRef().get(),
                    IProvider.Provider.getEnum(provider), payload, reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::logout", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            SoomlaProfile.getInstance().logout(IProvider.Provider.getEnum(provider));
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::getStoredUserProfile", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            UserProfile userProfile = SoomlaProfile.getInstance()
                    .getStoredUserProfile(IProvider.Provider.getEnum(provider));
            if (userProfile != null) {
                retParams.put("return", userProfile.toJSONObject());
            }
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatus", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String status = params.getString("status");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStatus(IProvider.Provider.getEnum(provider), status, payload,
                    reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatusWithConfirmation", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String status = params.getString("status");
            String payload = params.getString("payload");
            String customMessage = params.optString("customMessage");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStatusWithConfirmation(IProvider.Provider.getEnum(provider),
                    status, payload, reward, ndkGlue.getActivityRef().get(), customMessage);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStatusDialog", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String link = params.optString("link");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStatusDialog(IProvider.Provider.getEnum(provider), link, payload,
                    reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStory", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String message = params.getString("message");
            String name = params.getString("name");
            String caption = params.getString("caption");
            String description = params.getString("description");
            String link = params.getString("link");
            String picture = params.getString("picture");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStory(IProvider.Provider.getEnum(provider), message, name,
                    caption, description, link, picture, payload, reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStoryWithConfirmation", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String message = params.getString("message");
            String name = params.getString("name");
            String caption = params.getString("caption");
            String description = params.getString("description");
            String link = params.getString("link");
            String picture = params.getString("picture");
            String payload = params.getString("payload");
            String customMessage = params.optString("customMessage");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStoryWithConfirmation(IProvider.Provider.getEnum(provider),
                    message, name, caption, description, link, picture, payload, reward,
                    ndkGlue.getActivityRef().get(), customMessage);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::updateStoryDialog", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String name = params.optString("name");
            String caption = params.optString("caption");
            String description = params.optString("description");
            String link = params.optString("link");
            String picture = params.optString("picture");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().updateStoryDialog(IProvider.Provider.getEnum(provider), name, caption,
                    description, link, picture, payload, reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::uploadImage", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String message = params.getString("message");
            String filePath = params.getString("filePath");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().uploadImage(IProvider.Provider.getEnum(provider), message, filePath,
                    payload, reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::uploadImageWithConfirmation", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String message = params.getString("message");
            String filePath = params.getString("filePath");
            String payload = params.getString("payload");
            String customMessage = params.optString("customMessage");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().uploadImageWithConfirmation(IProvider.Provider.getEnum(provider),
                    message, filePath, payload, reward, ndkGlue.getActivityRef().get(), customMessage);

        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::getContacts", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            Boolean fromStart = params.getBoolean("fromStart");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().getContacts(IProvider.Provider.getEnum(provider), fromStart, payload,
                    reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::getFeed", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            Boolean fromStart = params.getBoolean("fromStart");
            String payload = params.getString("payload");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().getFeed(IProvider.Provider.getEnum(provider), fromStart, payload,
                    reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::isLoggedIn", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            boolean result = SoomlaProfile.getInstance().isLoggedIn(ndkGlue.getActivityRef().get(),
                    IProvider.Provider.getEnum(provider));
            retParams.put("return", result);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::like", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String provider = params.getString("provider");
            String pageId = params.getString("pageId");
            JSONObject rewardJson = params.optJSONObject("reward");
            Reward reward = (rewardJson != null) ? domainFactory.<Reward>createWithJsonObject(rewardJson)
                    : null;
            SoomlaProfile.getInstance().like(ndkGlue.getActivityRef().get(),
                    IProvider.Provider.getEnum(provider), pageId, reward);
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::openAppRatingPage", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            SoomlaProfile.getInstance()
                    .openAppRatingPage(ndkGlue.getActivityRef().get().getApplicationContext());
        }
    });

    ndkGlue.registerCallHandler("CCSoomlaProfile::multiShare", new NdkGlue.CallHandler() {
        @Override
        public void handle(JSONObject params, JSONObject retParams) throws Exception {
            String text = params.getString("text");
            String imageFilePath = params.getString("imageFilePath");
            SoomlaProfile.getInstance().multiShare(text, imageFilePath);
        }
    });

    final NdkGlue.ExceptionHandler exceptionHandler = new NdkGlue.ExceptionHandler() {
        @Override
        public void handle(Exception exception, JSONObject params, JSONObject retParams) throws Exception {
            retParams.put("errorInfo", exception.getClass().getName());
        }
    };

    ndkGlue.registerExceptionHandler(ProviderNotFoundException.class.getName(), exceptionHandler);
    ndkGlue.registerExceptionHandler(UserProfileNotFoundException.class.getName(), exceptionHandler);
}

From source file:com.soomla.cocos2dx.profile.ProfileBridge.java

private HashMap<IProvider.Provider, HashMap<String, String>> parseProviderParams(JSONObject sentParams) {
    if (sentParams == null) {
        SoomlaUtils.LogDebug("SOOMLA", "no provider params were sent");
        return null;
    }// www . j  a v a2 s  .c  om

    HashMap<IProvider.Provider, HashMap<String, String>> result = new HashMap<IProvider.Provider, HashMap<String, String>>();
    Iterator keysIterator = sentParams.keys();
    while (keysIterator.hasNext()) {
        String providerStr = (String) keysIterator.next();
        JSONObject paramsEntry = sentParams.optJSONObject(providerStr);

        if (paramsEntry != null) {
            HashMap<String, String> currentProviderParams = new HashMap<String, String>();
            Iterator innerKeysIterator = paramsEntry.keys();
            while (innerKeysIterator.hasNext()) {
                String innerKey = (String) innerKeysIterator.next();
                String innerValue = paramsEntry.optString(innerKey);
                currentProviderParams.put(innerKey, innerValue);
            }

            result.put(IProvider.Provider.getEnum(providerStr), currentProviderParams);
        }
    }

    return result;
}

From source file:com.lmpessoa.sonarview.core.Issue.java

public Issue(JSONObject source) {
    author = source.getString("author");
    message = source.getString("message");
    ruleId = source.getString("rule");
    severity = Severity.valueOf(source.getString("severity"));
    String[] subProject = source.getString("subProject").split(":", 2);
    projectId = subProject[subProject.length - 1];
    sourceFile = source.getString("component").substring(source.getString("subProject").length() + 1);
    JSONObject range = source.optJSONObject("textRange");
    if (range != null) {
        startLine = range.getInt("startLine");
        endLine = range.getInt("endLine");
        startOffset = range.getInt("startOffset");
        endOffset = range.getInt("endOffset");
    }/*from  w  ww . ja  va  2s.com*/
    debt = source.optString("debt");
}

From source file:org.jraf.android.cinetoday.mobile.api.codec.movie.MovieCodec.java

public void fill(Movie movie, JSONObject jsonMovie) throws ParseException {
    try {/*from w  w w  . j ava 2s.  co m*/
        movie.id = jsonMovie.getString("code");
        movie.localTitle = jsonMovie.getString("title");
        movie.originalTitle = jsonMovie.optString("originalTitle", null);
        movie.synopsis = jsonMovie.optString("synopsis", null);
        if (movie.synopsis != null) {
            // Strip html
            movie.synopsis = Html.fromHtml(movie.synopsis).toString().trim();
        }

        JSONObject jsonCastingShort = jsonMovie.optJSONObject("castingShort");
        if (jsonCastingShort != null) {
            movie.directors = jsonCastingShort.optString("directors", null);
            movie.actors = jsonCastingShort.optString("actors", null);
        }

        JSONObject jsonRelease = jsonMovie.optJSONObject("release");
        if (jsonRelease != null) {
            String releaseDateStr = jsonRelease.getString("releaseDate");
            try {
                movie.releaseDate = Api.SIMPLE_DATE_FORMAT.parse(releaseDateStr);
            } catch (java.text.ParseException e) {
                Log.d(e, "Invalid releaseDate %s in movie %s", movie, releaseDateStr);
            }
        }

        movie.durationSeconds = jsonMovie.getInt("runtime");

        JSONArray jsonGenreArray = jsonMovie.getJSONArray("genre");
        int len = jsonGenreArray.length();
        ArrayList<String> genres = new ArrayList<>(len);
        for (int i = 0; i < len; i++) {
            JSONObject jsonGenre = jsonGenreArray.getJSONObject(i);
            genres.add(jsonGenre.getString("$"));
        }
        movie.genres = genres.toArray(new String[len]);

        JSONObject jsonPoster = jsonMovie.optJSONObject("poster");
        if (jsonPoster != null)
            movie.posterUri = jsonPoster.getString("href");

        JSONObject jsonTrailer = jsonMovie.optJSONObject("trailer");
        if (jsonTrailer != null)
            movie.trailerUri = jsonTrailer.getString("href");

        JSONArray jsonLinkArray = jsonMovie.getJSONArray("link");
        JSONObject jsonLink = jsonLinkArray.getJSONObject(0);
        movie.webUri = jsonLink.getString("href");
    } catch (JSONException e) {
        throw new ParseException(e);
    }
}

From source file:com.liferay.mobile.android.http.Response.java

protected void checkPortalException(String json) throws ServerException {
    try {//from  w  w  w .ja v a  2s  .  c o  m
        if (isJSONObject(json)) {
            JSONObject jsonObj = new JSONObject(json);

            if (jsonObj.has("exception")) {
                String message = jsonObj.getString("exception");
                String detail = jsonObj.optString("message", null);

                JSONObject error = jsonObj.optJSONObject("error");

                if (error != null) {
                    message = error.getString("type");
                    detail = error.getString("message");
                }

                if ((message != null) && message.equals("java.lang.SecurityException")) {

                    throw new AuthenticationException(message, detail);
                }

                throw new ServerException(message, detail);
            }
        }
    } catch (JSONException je) {
        throw new ServerException(je);
    }
}

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

@Test
public void testGetUnknownRemote() throws Exception {
    // clone a  repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);/*from   ww  w. j av a2s  .com*/

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);

    request = getGetGitRemoteRequest(gitRemoteUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject remotes = new JSONObject(response.getText());
    JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, remotesArray.length());
    JSONObject remote = remotesArray.getJSONObject(0);
    assertNotNull(remote);
    String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(remoteLocation);

    URI u = URI.create(toRelativeURI(remoteLocation));
    IPath p = new Path(u.getPath());
    p = p.uptoSegment(2).append("xxx").append(p.removeFirstSegments(3));
    URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), p.toString(), u.getQuery(),
            u.getFragment());

    request = getGetGitRemoteRequest(nu.toString());
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response);
    assertEquals(status.toString(), status.getHttpCode(), HttpURLConnection.HTTP_NOT_FOUND);

    p = new Path(u.getPath());
    p = p.uptoSegment(3).append("xxx").append(p.removeFirstSegments(3));
    nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), p.toString(), u.getQuery(),
            u.getFragment());

    request = getGetGitRemoteRequest(nu.toString());
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

From source file:dentex.youtube.downloader.utils.Json.java

public static void addEntryToJsonFile(Context context, String id, String type, String ytId, int pos,
        String status, String path, String filename, String basename, String audioExt, String size,
        boolean forceCopy) {

    // parse existing/init new JSON 
    String previousJson = Json.readJsonDashboardFile(context);

    // create new "complex" object
    JSONObject mO = null;
    JSONObject jO = new JSONObject();

    try {// www.ja  va 2 s.  c  o  m
        mO = new JSONObject(previousJson);

        JSONObject obj = mO.optJSONObject(id);
        if (obj != null) {
            if (forceCopy) {
                String newId = String.valueOf(System.currentTimeMillis());
                Utils.logger("v", "Copying existent ID " + id + " into " + newId, DEBUG_TAG);
                id = newId;
            } else {
                Utils.logger("v", "Updating existent ID " + id, DEBUG_TAG);
            }
        } else {
            Utils.logger("v", "Addind new ID " + id, DEBUG_TAG);
        }

        if (status.equals(YTD.ctx.getResources().getString(R.string.json_status_completed)))
            status = YTD.JSON_DATA_STATUS_COMPLETED;
        if (status.equals(YTD.ctx.getResources().getString(R.string.json_status_in_progress)))
            status = YTD.JSON_DATA_STATUS_IN_PROGRESS;
        if (status.equals(YTD.ctx.getResources().getString(R.string.json_status_failed)))
            status = YTD.JSON_DATA_STATUS_FAILED;
        if (status.equals(YTD.ctx.getResources().getString(R.string.json_status_paused)))
            status = YTD.JSON_DATA_STATUS_PAUSED;
        if (status.equals(YTD.ctx.getResources().getString(R.string.json_status_imported)))
            status = YTD.JSON_DATA_STATUS_IMPORTED;

        jO.put(YTD.JSON_DATA_TYPE, type);
        jO.put(YTD.JSON_DATA_YTID, ytId);
        jO.put(YTD.JSON_DATA_POS, pos);
        jO.put(YTD.JSON_DATA_STATUS, status);
        jO.put(YTD.JSON_DATA_PATH, path);
        jO.put(YTD.JSON_DATA_FILENAME, filename);
        jO.put(YTD.JSON_DATA_BASENAME, basename);
        jO.put(YTD.JSON_DATA_AUDIO_EXT, audioExt);
        jO.put(YTD.JSON_DATA_SIZE, size);
        mO.put(id, jO);
    } catch (JSONException e1) {
        Log.e(DEBUG_TAG, "JSONException @ addEntryToJsonFile");
    }

    // generate string from the object
    String jsonString = null;
    try {
        jsonString = mO.toString(4);

        // write back JSON file
        Utils.logger("v", "-> " + jsonString, DEBUG_TAG);
        Utils.writeToFile(YTD.JSON_FILE, jsonString);
    } catch (JSONException e1) {
        Log.e(DEBUG_TAG, "JSONException @ addEntryToJsonFile");
    } catch (NullPointerException e1) {
        Log.e(DEBUG_TAG, "NPE @ addEntryToJsonFile");
    }
}