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.trellmor.berrytube.ChatMessage.java

/**
 * Constructs a <code>ChatMessage</code> from an <code>JSONObject</code>
 * /*w ww.ja  v  a 2 s  . co m*/
 * @param message
 *            <code>JSONObject<code> containing all the required fields to form a chat message
 * @throws JSONException
 */
public ChatMessage(JSONObject message) throws JSONException {
    mNick = message.getString("nick");
    mMsg = message.getString("msg");
    mMulti = message.getInt("multi");
    mType = message.getInt("type");

    // check emote
    if (message.has("emote") && message.get("emote") instanceof String) {
        String emote = message.getString("emote");
        if (emote.compareTo("rcv") == 0)
            this.mEmote = EMOTE_RCV;
        else if (emote.compareTo("sweetiebot") == 0)
            this.mEmote = EMOTE_SWEETIEBOT;
        else if (emote.compareTo("spoiler") == 0)
            this.mEmote = EMOTE_SPOILER;
        else if (emote.compareTo("act") == 0)
            this.mEmote = EMOTE_ACT;
        else if (emote.compareTo("request") == 0)
            this.mEmote = EMOTE_REQUEST;
        else if (emote.compareTo("poll") == 0)
            this.mEmote = EMOTE_POLL;
        else if (emote.compareTo("drink") == 0)
            this.mEmote = EMOTE_DRINK;
    } else
        mEmote = 0;

    JSONObject metadata = message.getJSONObject("metadata");
    mFlair = metadata.optInt("flair");
    mFlaunt = metadata.optBoolean("nameflaunt");

    try {
        this.mTimeStamp = TIMESTAMP_FORMAT.parse(message.getString("timestamp")).getTime();
    } catch (ParseException pe) {
        Log.w(TAG, "Error parsing timestamp string");
        this.mTimeStamp = System.currentTimeMillis();
    }
    this.mHidden = (this.mEmote == EMOTE_SPOILER);
}

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

public Group(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();//from   ww w  .jav  a2 s .  c om
    // 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 the ones we want directly accessible
        if (!"actions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // grab any actions
    JSONArray jsonActions = jsonAction.optJSONArray("actions");
    // if we had some
    if (jsonActions != null) {
        _actions = Control.getActions(rapidServlet, jsonActions);
    }

}

From source file:com.google.enterprise.connector.db.diffing.DBSnapshotRepositoryTest.java

/**
 * Compares two JSON strings for equality. The order of the
 * name/value pairs in the string is not important (and that's why
 * this method is required, or we would just compare the strings
 * with each other).//from w  w  w  . j  a  va 2s  .  c o m
 */
private void assertJsonEquals(String message, String expectedString, String actualString) throws JSONException {
    JSONObject expected = new JSONObject(expectedString);
    JSONObject actual = new JSONObject(actualString);
    Set<String> expectedNames = Sets.newHashSet(JSONObject.getNames(expected));
    Set<String> actualNames = Sets.newHashSet(JSONObject.getNames(actual));
    assertEquals(message, expectedNames, actualNames);
    for (String name : expectedNames) {
        assertEquals(message, expected.get(name), actual.get(name));
    }
}

From source file:com.atolcd.alfresco.ProxyAuditFilter.java

@Override
public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain)
        throws IOException, ServletException {
    // Get the HTTP request/response/session
    HttpServletRequest request = (HttpServletRequest) sReq;
    // HttpServletResponse response = (HttpServletResponse) sRes;
    RequestWrapper requestWrapper = new RequestWrapper(request);
    // Initialize a new request context
    RequestContext context = ThreadLocalRequestContext.getRequestContext();

    String referer = request.getHeader("referer");

    if (context == null) {
        try {//  w w  w  .  ja  va2  s  .  co m
            // Perform a "silent" init - i.e. no user creation or remote
            // connections
            context = RequestContextUtil.initRequestContext(getApplicationContext(), request, true);
            try {
                RequestContextUtil.populateRequestContext(context, request);
            } catch (ResourceLoaderException e) {
                // e.printStackTrace();
            } catch (UserFactoryException e) {
                // e.printStackTrace();
            }
        } catch (RequestContextException ex) {
            throw new ServletException(ex);
        }
    }
    User user = context.getUser();
    String requestURI = request.getRequestURI();
    String method = request.getMethod().toUpperCase();

    if (user != null) {
        try {
            JSONObject auditSample = new JSONObject();
            auditSample.put(AUDIT_ID, "0");
            auditSample.put(AUDIT_USER_ID, user.getId());
            auditSample.put(AUDIT_SITE, "");
            auditSample.put(AUDIT_APP_NAME, "");
            auditSample.put(AUDIT_ACTION_NAME, "");
            auditSample.put(AUDIT_OBJECT, "");
            auditSample.put(AUDIT_TIME, Long.toString(System.currentTimeMillis()));

            // For documents only (only in sites!)
            if (requestURI.endsWith("/doclib/activity") && request.getMethod().equals(POST)) {
                String type = request.getContentType().split(";")[0];
                if (type.equals("application/json")) {
                    // Get JSON Object
                    JSONObject activityFeed = new JSONObject(requestWrapper.getStringContent());

                    String activityType = activityFeed.getString("type");
                    if (activityType != null) {
                        if ("file-added".equals(activityType)
                                || ("file-updated".equals(activityType)
                                        && (referer != null && !referer.contains("document-details"))) // Done in JavaScript on "document-details" page
                                || "file-deleted".equals(activityType)) {
                            if (activityFeed.has("nodeRef")) {
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                auditSample.put(AUDIT_SITE, activityFeed.getString("site"));
                                auditSample.put(AUDIT_ACTION_NAME, activityType);
                                auditSample.put(AUDIT_OBJECT, activityFeed.getString("nodeRef"));
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);

                                remoteCall(request, auditSample);
                            }
                        } else if ("files-added".equals(activityType) || "files-deleted".equals(activityType)) {
                            // multiple file uploads/deletions (5 or more)
                            Integer fileCount = activityFeed.getInt("fileCount");
                            if (fileCount != null && fileCount > 0) {
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                auditSample.put(AUDIT_SITE, activityFeed.getString("site"));
                                auditSample.put(AUDIT_ACTION_NAME, "file-" + activityType.split("-")[1]);
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                // auditSample.put(AUDIT_OBJECT, "");

                                for (int i = 0; i < fileCount; i++) {
                                    remoteCall(request, auditSample);
                                }
                            }
                        }
                    }
                }
            } else if (requestURI.startsWith(URI_NODE_UPDATE) && requestURI.endsWith(FORMPROCESSOR)) {
                JSONObject updatedData = new JSONObject(requestWrapper.getStringContent());
                // Online edit used the same form (plus the cm_content
                // metadata)
                if (!updatedData.has("prop_cm_content")) {
                    auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                    auditSample.put(AUDIT_ACTION_NAME, "update");
                    auditSample.put(AUDIT_SITE, TEMP_SITE);
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.endsWith("/activity/create")) {
                String jsonPost = requestWrapper.getStringContent();
                if (jsonPost != null && !jsonPost.isEmpty()) {
                    JSONObject json = new JSONObject(jsonPost);
                    String mod = AuditHelper.extractModFromActivity(json);
                    if (mod != null) {
                        auditSample.put(AUDIT_APP_NAME, mod);
                        auditSample.put(AUDIT_SITE, json.getString("site"));
                        auditSample.put(AUDIT_ACTION_NAME, AuditHelper.extractActionFromActivity(json));
                        auditSample.put(AUDIT_OBJECT, json.getString("nodeRef"));
                        remoteCall(request, auditSample);
                    }
                }
            } else if (requestURI.equals(URI_UPLOAD)) {
                // XXX: issue with big files
                // Nothing to do - Insert request is done in JavaScript
            } else if (requestURI.endsWith("/comments") || requestURI.endsWith("/replies")) {
                // Comments & replies
                String[] urlTokens = request.getHeader("referer").toString().split("/");
                HashMap<String, String> auditData = this.getUrlData(urlTokens);

                auditSample.put(AUDIT_SITE, auditData.get(KEY_SITE));
                auditSample.put(AUDIT_APP_NAME, auditData.get(KEY_MODULE));
                auditSample.put(AUDIT_ACTION_NAME, "comments");
                auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                // Remote call for DB
                remoteCall(request, auditSample);
            } else if (requestURI.startsWith(URI_WIKI)) {
                String[] urlTokens = requestURI.split("/");
                String wikiPageId = urlTokens[urlTokens.length - 1];
                String siteId = urlTokens[urlTokens.length - 2];
                if (method.equals(Method.PUT.toString().toString())) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_APP_NAME, MOD_WIKI);
                    if (params.has("currentVersion")) {
                        auditSample.put(AUDIT_ACTION_NAME, "update-post");
                    } else {
                        auditSample.put(AUDIT_ACTION_NAME, "create-post");
                    }

                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_WIKI,
                            wikiPageId);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    // Remote call
                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_APP_NAME, MOD_WIKI);
                    auditSample.put(AUDIT_ACTION_NAME, "delete-post");
                    auditSample.put(AUDIT_OBJECT, wikiPageId);
                    // Remote call
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_BLOG)) {
                auditSample.put(AUDIT_APP_NAME, MOD_BLOG);
                if (method.equals(POST)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "blog-create");
                    auditSample.put(AUDIT_OBJECT, params.get("title"));

                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "blog-update");
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0));

                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    String[] urlTokens = requestURI.split("/");
                    auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);
                    auditSample.put(AUDIT_ACTION_NAME, "blog-delete");

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_DISCUSSIONS)) {
                auditSample.put(AUDIT_APP_NAME, "discussions");
                if (method.equals(POST)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-create");
                    auditSample.put(AUDIT_OBJECT, params.get("title"));

                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    String siteId = (String) params.get("site");
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-update");

                    String[] urlTokens = requestURI.split("/");
                    String discussionId = urlTokens[urlTokens.length - 1];
                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, "discussions",
                            discussionId);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    String[] urlTokens = requestURI.split("/");
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-deleted");
                    auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_LINKS) && !method.equals(GET)) {
                String[] urlTokens = requestURI.split("/");
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                auditSample.put(AUDIT_APP_NAME, MOD_LINKS);

                if (method.equals(POST)) {
                    if (requestURI.startsWith(URI_LINKS + "delete/")) {
                        auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]);
                        auditSample.put(AUDIT_OBJECT, params.getJSONArray("items").get(0));
                        auditSample.put(AUDIT_ACTION_NAME, "links-delete");
                    } else {
                        auditSample.put(AUDIT_OBJECT, params.get("title"));
                        auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);
                        auditSample.put(AUDIT_ACTION_NAME, "links-create");
                    }
                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    String siteId = urlTokens[urlTokens.length - 3];
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_ACTION_NAME, "links-update");

                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_LINKS,
                            urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_DOWNLOAD)) {
                String a = request.getParameter("a");
                if (a != null && !a.isEmpty()) {
                    auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                    auditSample.put(AUDIT_ACTION_NAME, "true".equalsIgnoreCase(a) ? "download" : "stream");
                    auditSample.put(AUDIT_SITE, TEMP_SITE);
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_ACTION)) {
                // XXX: done in JavaScript
            } else if (requestURI.endsWith("memberships") && method.equals(GET)) {

                String type = request.getParameter("authorityType");
                String nf = request.getParameter("nf");
                String[] urlTokens = requestURI.split("/");

                auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]);
                auditSample.put(AUDIT_APP_NAME, MOD_MEMBERS);
                auditSample.put(AUDIT_ACTION_NAME, type.toLowerCase());
                auditSample.put(AUDIT_OBJECT, nf);
                remoteCall(request, auditSample);
            } else if (requestURI.endsWith(URI_CALENDAR)) {
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                auditSample.put(AUDIT_APP_NAME, MOD_CALENDAR);
                auditSample.put(AUDIT_ACTION_NAME, "create");
                auditSample.put(AUDIT_SITE, params.get("site"));
                auditSample.put(AUDIT_OBJECT, params.get("what"));

                remoteCall(request, auditSample);
            } else if ((requestURI.startsWith(URI_DATALIST) || requestURI.startsWith(URI_DATALIST_DELETE))
                    && method.equals(POST)) {
                boolean isDeleteRequest = request.getParameter("alf_method") != null;
                auditSample.put(AUDIT_APP_NAME, MOD_DATA);
                auditSample.put(AUDIT_SITE, TEMP_SITE);
                if (isDeleteRequest) {
                    auditSample.put(AUDIT_ACTION_NAME, "datalist-delete");
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    JSONArray items = params.getJSONArray("nodeRefs");
                    for (int i = 0; i < items.length(); i++) {
                        auditSample.put(AUDIT_OBJECT, items.getString(i));

                        remoteCall(request, auditSample);
                    }
                } else {
                    auditSample.put(AUDIT_ACTION_NAME, "datalist-post");
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0));

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_SOCIAL_PUBLISHING) && method.equals(POST)) {
                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                auditSample.put(AUDIT_SITE, TEMP_SITE);

                auditSample.put(AUDIT_ACTION_NAME, "publish");
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                JSONArray items = params.getJSONArray("publishNodes");
                for (int i = 0; i < items.length(); i++) {
                    auditSample.put(AUDIT_OBJECT, items.getString(i));
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.indexOf("/ratings") != -1) {
                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                auditSample.put(AUDIT_SITE, TEMP_SITE);
                int offset = 1;
                if (POST.equals(method)) {
                    auditSample.put(AUDIT_ACTION_NAME, "rate");
                } else if (DELETE.equals(method)) {
                    auditSample.put(AUDIT_ACTION_NAME, "unrate");
                    offset = 2;
                }
                auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, offset));
                remoteCall(request, auditSample);
            }

        } catch (JSONException e) {
            logger.error("JSON Error during a remote call ...");
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage(), e);
            }
        }
    }
    chain.doFilter(requestWrapper, sRes);
}

From source file:com.atolcd.alfresco.ProxyAuditFilter.java

private String getNodeRefRemoteCall(HttpServletRequest request, String userId, String siteId,
        String componentId, String objectId) throws JSONException, URIException, UnsupportedEncodingException {
    Connector connector;//from   w w w  .ja v a2  s. c o  m

    try {
        connector = FrameworkUtil.getConnector(request.getSession(true), userId,
                AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
        // <url>/share-stats/slingshot/details/{siteId}/{componentId}/{objectId}</url>
        Response resp = connector.call("/share-stats/slingshot/details/" + siteId + "/" + componentId + "/"
                + URLEncoder.encode(objectId, "UTF-8"));

        if (resp.getStatus().getCode() == Status.STATUS_OK) {
            try {
                JSONObject json = new JSONObject(resp.getResponse());
                if (json.has("nodeRef")) {
                    return (String) json.get("nodeRef");
                }
            } catch (JSONException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                }
            }
        }
    } catch (ConnectorServiceException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
    }

    return objectId;
}

From source file:com.atinternet.tracker.TVTracking.java

/**
 * Constructor/* w w w  .  j a  v  a  2s .co  m*/
 *
 * @param tracker Tracker
 */
TVTracking(Tracker tracker) {
    this.tracker = tracker;
    visitDuration = 10;
    campaignURL = "";

    String url = (String) tracker.getConfiguration().get(TrackerConfigurationKeys.TVTRACKING_URL);
    if (!TextUtils.isEmpty(url)) {
        campaignURL = url;
    } else {
        Tool.executeCallback(tracker.getListener(), Tool.CallbackType.warning, "TVTracking URL not set");
    }

    Integer visit = Integer.parseInt(
            String.valueOf(tracker.getConfiguration().get(TrackerConfigurationKeys.TVTRACKING_VISIT_DURATION)));
    if (visit != 0) {
        visitDuration = visit;
    }

    try {
        String remanentCampaign = Tracker.getPreferences()
                .getString(TrackerConfigurationKeys.REMANENT_CAMPAIGN_SAVED, null);
        if (remanentCampaign != null) {
            JSONObject remanentObject = new JSONObject(remanentCampaign);
            int lifetime;
            if (remanentObject.get("lifetime") instanceof String) {
                lifetime = Integer.parseInt((String) remanentObject.get("lifetime"));
            } else {
                lifetime = (Integer) remanentObject.get("lifetime");
            }
            long savedLifetime = Tracker.getPreferences()
                    .getLong(TrackerConfigurationKeys.REMANENT_CAMPAIGN_TIME_SAVED, 0);

            if (Tool.getDaysBetweenTimes(System.currentTimeMillis(), savedLifetime) >= lifetime) {
                Tracker.getPreferences().edit()
                        .putString(TrackerConfigurationKeys.REMANENT_CAMPAIGN_SAVED, null).apply();
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.beust.android.translate.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate.//ww w. ja va  2  s .com
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TranslateService.TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TranslateService.TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.gizwits.framework.activity.BaseActivity.java

/**
 * ??/*from  w  w  w  . j av  a2  s.c o  m*/
 * 
 * @param map
 *            the map
 * @param json
 *            the json
 * @throws JSONException
 *             the JSON exception
 */
protected void inputDataToMaps(ConcurrentHashMap<String, Object> map, String json) throws JSONException {
    Log.i("revjson", json);
    JSONObject receive = new JSONObject(json);
    Iterator actions = receive.keys();
    while (actions.hasNext()) {

        String action = actions.next().toString();
        Log.i("revjson", "action=" + action);
        // 
        if (action.equals("cmd") || action.equals("qos") || action.equals("seq") || action.equals("version")) {
            continue;
        }
        JSONObject params = receive.getJSONObject(action);
        Log.i("revjson", "params=" + params);
        Iterator it_params = params.keys();
        while (it_params.hasNext()) {
            String param = it_params.next().toString();
            Object value = params.get(param);
            map.put(param, value);
            Log.i(TAG, "Key:" + param + ";value" + value);
        }
    }
}

From source file:com.ibm.EmployeeServicesResource.java

@GET
@Produces("application/json")
@Path("/details/{empId}")
public String getAccount(@PathParam("empId") String id) throws IOException, org.json.JSONException {
    logger.info(">>EmployeeServicesResource -> in details() ...:" + id);
    JSONObject rsp = new JSONObject();
    try {/*from   ww w .ja  va 2s. c om*/
        JSONArray details = getDetails();
        for (int i = 0; i < details.length(); i++) {
            JSONObject obj = details.getJSONObject(i);
            logger.info(">> obj.get(_id).toString():" + obj.get("_id").toString());
            if (obj.get("_id").toString().equals(id)) {
                rsp.put("details", obj);
                return rsp.toString();
            }
        }
    } catch (org.json.JSONException e) {
        e.printStackTrace();
    }
    return rsp.toString();
}

From source file:io.github.howiefh.jeews.modules.sys.controller.LoginControllerTest.java

@Test
public void testLogin() throws Exception {
    String user = "{\"username\":\"root\",\"password\":\"u12345\"}";
    MvcResult result = mockMvc// ww  w  .  j  av a 2  s .c  om
            .perform(post("/login").contentType(MediaType.APPLICATION_JSON).content(user)
                    .accept(MediaTypes.HAL_JSON))
            .andExpect(status().isOk()) // 200
            .andExpect(jsonPath("$.access_token").exists()).andExpect(jsonPath("$.user.id").exists())
            .andReturn();
    String content = result.getResponse().getContentAsString();
    JSONObject json = new JSONObject(content);
    String accessToken = json.get("access_token").toString();

    mockMvc.perform(
            get("/users/1").header("Authorization", "Bearer " + accessToken).accept(MediaTypes.HAL_JSON))
            .andExpect(status().isOk()) // 200
            .andExpect(content().contentType(MediaTypes.HAL_JSON)) // ??contentType
            .andReturn();
    mockMvc.perform(get("/users/1")).andExpect(status().isUnauthorized()) // 401
            .andReturn();
    String requestBody = "{\"username\":\"fh" + UUID.randomUUID() + "\",\"password\":\"123456\",\"email\":\""
            + UUID.randomUUID() + "@qq.om\",\"mobile\":" + "\"" + new Random().nextInt()
            + "\",\"roles\":[1,2],\"organizations\":[1],\"locked\":true}";
    mockMvc.perform(post("/users").header("Authorization", "Bearer " + accessToken)
            .contentType(MediaType.APPLICATION_JSON).content(requestBody).accept(MediaTypes.HAL_JSON)) // 
            .andExpect(status().isCreated()) // 201
            .andExpect(jsonPath("$.id").exists()) // Json path?JSON
            .andExpect(content().contentType(MediaTypes.HAL_JSON)).andReturn();
}