Example usage for org.json.simple JSONArray contains

List of usage examples for org.json.simple JSONArray contains

Introduction

In this page you can find the example usage for org.json.simple JSONArray contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:com.intuit.utils.PopulateUsers.java

public static void main(String[] args) {
    Date now = new Date();
    System.out.println("Current date is: " + now.toString());

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("tweetsdb");
    DBCollection collection = db.getCollection("userscollection");
    WriteResult result = collection.remove(new BasicDBObject());

    int userIndex = 1;
    for (int i = 1; i <= 10; i++) {
        JSONObject userDocument = new JSONObject();
        String user = "user" + userIndex;
        userDocument.put("user", user);

        JSONArray followerList = new JSONArray();
        Random randomGenerator = new Random();
        for (int j = 0; j < 3; j++) {
            int followerId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be a follower on himself
            while (followerId == userIndex) {
                followerId = randomGenerator.nextInt(10) + 1;
            }//from   w  w w .  ja v a 2s . co m

            String follower = "user" + followerId;
            if (!followerList.contains(follower)) {
                followerList.add(follower);
            }
        }
        userDocument.put("followers", followerList);

        JSONArray followingList = new JSONArray();
        for (int k = 0; k < 3; k++) {
            int followingId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be following his own tweets
            while (followingId == userIndex) {
                followingId = randomGenerator.nextInt(10) + 1;
            }

            String followingUser = "user" + followingId;
            if (!followingList.contains(followingUser)) {
                followingList.add(followingUser);
            }
        }
        userDocument.put("following", followingList);
        System.out.println("Json string is: " + userDocument.toString());
        DBObject userDBObject = (DBObject) JSON.parse(userDocument.toString());
        collection.insert(userDBObject);
        userIndex++;

    }

    //        try {
    //            FileWriter file = new FileWriter("/Users/dmurty/Documents/MongoData/usersCollection.js");
    //            file.write(usersArray.toJSONString());
    //            file.flush();
    //            file.close();
    //        } catch (IOException ex) {
    //            Logger.getLogger(PopulateUsers.class.getName()).log(Level.SEVERE, null, ex);
    //        } 
}

From source file:mml.handler.MMLHandler.java

/**
 * Fetch one annotation from some database
 * @param conn the connection to the database
 * @param coll the database collection//from w  w  w  .  j a  v a2s . c  o m
 * @param docId the specific docid to match against
 * @return a JSONObject or null
 * @throws DbException 
 */
protected JSONObject fetchAnnotation(Connection conn, String coll, String docId) throws DbException {
    String jDoc = conn.getFromDb(coll, docId);
    JSONObject jObj = (JSONObject) JSONValue.parse(jDoc);
    if (isAnnotation(jObj)) {
        if (jObj.containsKey(JSONKeys.VERSIONS)) {
            JSONArray versions = (JSONArray) jObj.get(JSONKeys.VERSIONS);
            if (versions.contains(version1))
                return jObj;
        }
    }
    return null;
}

From source file:com.alvexcore.share.evaluators.AttachedToRegistryItemEvaluator.java

@Override
public boolean evaluate(JSONObject jsonObject) {
    try {/*  w  ww  . j  a  va  2s.c om*/
        JSONArray nodeAspects = getNodeAspects(jsonObject);
        if (nodeAspects == null)
            return false;

        if (nodeAspects.contains(ASPECT_ATTACHED))
            return true;

        return false;
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("Can not run evaluator: " + e.getMessage());
    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testJobTagsPrefix() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tags/startsWith/LOOP");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertTrue(jsonArray.contains("LOOP-T2-1"));
    assertTrue(jsonArray.contains("LOOP-T2-2"));
    assertTrue(jsonArray.contains("LOOP-T2-3"));
    assertEquals(3, jsonArray.size());/*w  ww  .j  a v  a 2  s  .  com*/
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testJobTags() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tags");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertTrue(jsonArray.contains("LOOP-T2-1"));
    assertTrue(jsonArray.contains("LOOP-T2-2"));
    assertTrue(jsonArray.contains("LOOP-T2-3"));
    assertTrue(jsonArray.contains("REPLICATE-T3-1"));
    assertTrue(jsonArray.contains("REPLICATE-T3-2"));
    assertEquals(5, jsonArray.size());/*from w  w  w.  j  a  va2 s.  c  o  m*/
}

From source file:mml.handler.get.MMLGetVersionsHandler.java

/**
 * Get the version listing from the MVD//from  ww  w  .  j a v a  2  s.  com
 * @param request the request
 * @param response the response
 * @param urn the remaining urn being empty
 * @throws MMLException 
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        String docid = request.getParameter(Params.DOCID);
        if (docid == null)
            throw new Exception("You must specify a docid parameter");
        AeseResource res = doGetResource(Database.CORTEX, docid);
        JSONArray jVersions = new JSONArray();
        if (res != null) {
            String[] versions = res.listVersions();
            HashMap<String, JSONObject> vSet = new HashMap<String, JSONObject>();
            for (int i = 0; i < versions.length; i++) {
                String base = Layers.stripLayer(versions[i]);
                JSONObject jObj = vSet.get(base);
                if (jObj == null)
                    jObj = new JSONObject();
                String upgraded = Layers.upgradeLayerName(versions, versions[i]);
                if (!upgraded.equals(versions[i])) {
                    JSONArray repl = (JSONArray) jObj.get("replacements");
                    if (repl == null) {
                        repl = new JSONArray();
                        jObj.put("replacements", repl);
                    }
                    JSONObject entry = new JSONObject();
                    entry.put("old", versions[i]);
                    entry.put("new", upgraded);
                    repl.add(entry);
                }
                if (upgraded.endsWith("layer-final"))
                    jObj.put("desc", res.getVersionLongName(i + 1));
                // add the layer names
                if (upgraded.endsWith("layer-final") || upgraded.matches(".*layer-[0-9]+$")) {
                    JSONArray jArr = (JSONArray) jObj.get("layers");
                    if (jArr == null)
                        jArr = new JSONArray();
                    int index = upgraded.lastIndexOf("layer");
                    String layerName = upgraded.substring(index);
                    if (!jArr.contains(layerName))
                        jArr.add(layerName);
                    if (!jObj.containsKey("layers"))
                        jObj.put("layers", jArr);
                }
                if (!vSet.containsKey(base))
                    vSet.put(base, jObj);
            }
            // convert hashmap to array
            Set<String> keys = vSet.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String version = iter.next();
                JSONObject jObj = vSet.get(version);
                jObj.put("vid", version);
                jVersions.add(jObj);
            }
        }
        response.setContentType("application/json");
        response.setCharacterEncoding(encoding);
        String jStr = jVersions.toJSONString().replaceAll("\\\\/", "/");
        response.getWriter().println(jStr);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskIdsByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1");
    JSONObject jsonObject = toJsonObject(response);
    JSONArray taskIds = (JSONArray) jsonObject.get("list");

    System.out.println(jsonObject.toJSONString());
    assertTrue(taskIds.contains("T1#1"));
    assertTrue(taskIds.contains("Print1#1"));
    assertTrue(taskIds.contains("Print2#1"));
    assertTrue(taskIds.contains("T2#1"));
    assertEquals("4", jsonObject.get("size").toString());
}

From source file:com.appcelerator.titanium.desktop.ui.wizard.TiManifestTest.java

protected void assertTiManifestContents(File file, final String appId, final String appName, final String guid,
        final String version, final String description, final String publisher, final String url,
        Set<String> platforms, String runtime, boolean release, String visibility, boolean showSplash)
        throws IOException, ParseException, FileNotFoundException {
    JSONParser parser = new JSONParser();
    JSONObject resultJSON = null;//from   w ww .jav  a  2 s  .  c  o m
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        resultJSON = (JSONObject) parser.parse(reader);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    assertNotNull(resultJSON);
    assertEquals("App ID didn't match", appId, resultJSON.get(TiManifest.APPID));
    assertEquals("App name didn't match", appName, resultJSON.get(TiManifest.APPNAME));
    assertEquals("App version didn't match", version, resultJSON.get(TiManifest.APPVERSION));
    assertEquals("App description didn't match", description, resultJSON.get(TiManifest.DESC));
    assertEquals("App GUID didn't match", guid, resultJSON.get(TiManifest.GUID));
    assertEquals("MID didn't match", TitaniumCorePlugin.getMID(), resultJSON.get(TiManifest.MID));
    assertEquals("'noinstall' value was incorrect", !showSplash, resultJSON.get(TiManifest.NO_INSTALL));
    JSONArray platformsArray = (JSONArray) resultJSON.get(TiManifest.PLATFORMS);
    assertEquals("'platforms' array size didn't match", platforms.size(), platformsArray.size());
    for (String platform : platforms) {
        assertTrue("'platforms' array didn't contain expected value: " + platform,
                platformsArray.contains(platform));
    }
    assertEquals("App publisher didn't match", publisher, resultJSON.get(TiManifest.PUBLISHER));
    assertEquals("'release' boolean didn't match", release, resultJSON.get(TiManifest.RELEASE));
    JSONObject runtimeObj = (JSONObject) resultJSON.get(TiManifest.RUNTIME);
    assertEquals("'runtime' didn't match", runtime, runtimeObj.get(TiManifest.PACKAGE));
    assertEquals("App URL didn't match", url, resultJSON.get(TiManifest.URL));
    assertEquals("Visibility is incorrect", visibility, resultJSON.get(TiManifest.VISIBILITY));
}

From source file:com.portfolio.security.LTIv2Servlet.java

protected void doRegister(HttpServletResponse response, Map<String, Object> payload, ServletContext application,
        String toolProxyPath, StringBuffer outTrace) {
    String launch_url = (String) payload.get("launch_url");
    response.setContentType("text/html");

    outTraceFormattedMessage(outTrace, "doRegister() - launch_url: " + launch_url);
    outTraceFormattedMessage(outTrace, "payload: " + payload);

    String key = null;// w  w w.  j a v  a  2  s  .  com
    String passwd = null;
    if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXYREGISTRATIONREQUEST
            .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) {
        key = (String) payload.get(LTI2Constants.REG_KEY);
        passwd = (String) payload.get(LTI2Constants.REG_PASSWORD);
    } else if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXY_RE_REGISTRATIONREQUEST
            .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) {
        key = (String) payload.get(LTIServletUtils.OAUTH_CONSUMER_KEY);
        final String configPrefix = "basiclti.provider." + key + ".";
        passwd = (String) application.getAttribute(configPrefix + "secret");

    } else {
        //TODO BOOM
        outTraceFormattedMessage(outTrace, "BOOM");
    }

    String returnUrl = (String) payload.get(BasicLTIConstants.LAUNCH_PRESENTATION_RETURN_URL);
    String tcProfileUrl = (String) payload.get(LTI2Constants.TC_PROFILE_URL);

    //Lookup tc profile
    if (tcProfileUrl != null && !"".equals(tcProfileUrl)) {
        InputStream is = null;
        try {
            URL url = new URL(tcProfileUrl);
            is = url.openStream();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(new InputStreamReader(is));
            //             is.close();
            outTraceFormattedMessage(outTrace, obj.toJSONString());
            JSONArray services = (JSONArray) obj.get("service_offered");
            String regUrl = null;
            for (int i = 0; i < services.size(); i++) {
                JSONObject service = (JSONObject) services.get(i);
                JSONArray formats = (JSONArray) service.get("format");
                if (formats.contains("application/vnd.ims.lti.v2.toolproxy+json")) {
                    regUrl = (String) service.get("endpoint");
                    outTraceFormattedMessage(outTrace, "RegEndpoint: " + regUrl);
                }
            }
            if (regUrl == null) {
                //TODO BOOM
                throw new RuntimeException("Need an endpoint");
            }

            JSONObject toolProxy = getToolProxy(toolProxyPath);
            //TODO do some replacement on stock values that need specifics from us here

            // Tweak the stock profile
            toolProxy.put("tool_consumer_profile", tcProfileUrl);
            //LTI2Constants.
            //            BasicLTIConstants.

            //            // Re-register
            JSONObject toolProfile = (JSONObject) toolProxy.get("tool_profile");
            JSONArray messages = (JSONArray) toolProfile.get("message");
            JSONObject message = (JSONObject) messages.get(0);
            message.put("path", launch_url);
            String baseUrl = (String) payload.get("base_url");

            JSONObject pi = (JSONObject) toolProfile.get("product_instance");
            JSONObject pInfo = (JSONObject) pi.get("product_info");
            JSONObject pFamily = (JSONObject) pInfo.get("product_family");
            JSONObject vendor = (JSONObject) pFamily.get("vendor");
            vendor.put("website", baseUrl);
            //            vendor.put("timestamp", new Date().toString());
            //            $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->website = $cur_base;
            //            $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->timestamp = "2013-07-13T09:08:16-04:00";
            //
            //            // I want this *not* to be unique per instance
            //            $tp_profile->tool_profile->product_instance->guid = "urn:sakaiproject:unit-test";
            //
            //            $tp_profile->tool_profile->product_instance->service_provider->guid = "http://www.sakaiproject.org/";
            //
            //            // Launch Request
            //            $tp_profile->tool_profile->resource_handler[0]->message[0]->path = "tool.php";
            //            $tp_profile->tool_profile->resource_handler[0]->resource_type->code = "sakai-api-test-01";

            //            $tp_profile->tool_profile->base_url_choice[0]->secure_base_url = $cur_base;
            //            $tp_profile->tool_profile->base_url_choice[0]->default_base_url = $cur_base;
            JSONObject choice = (JSONObject) ((JSONArray) toolProfile.get("base_url_choice")).get(0);
            choice.put("secure_base_url", baseUrl);
            choice.put("default_base_url", baseUrl);

            JSONObject secContract = (JSONObject) toolProxy.get("security_contract");
            secContract.put("shared_secret", passwd);
            JSONArray toolServices = (JSONArray) secContract.get("tool_service");
            JSONObject service = (JSONObject) toolServices.get(0);
            service.put("service", regUrl);

            outTraceFormattedMessage(outTrace, "ToolProxyJSON: " + toolProxy.toJSONString());

            /// From the Implementation Guid Version 2.0 Final (http://www.imsglobal.org/lti/ltiv2p0/ltiIMGv2p0.html)
            /// Section 10.1
            /// Get data
            JSONObject dataService = getData(tcProfileUrl);

            /// find endpoint with format: application/vnd.ims.lti.v2.toolproxy+json WITH POST action
            JSONArray offered = (JSONArray) dataService.get("service_offered");
            String registerAddress = "";
            for (int i = 0; i < offered.size(); ++i) {
                JSONObject offer = (JSONObject) offered.get(i);
                JSONArray offerFormat = (JSONArray) offer.get("format");
                String format = (String) offerFormat.get(0);
                JSONArray offerAction = (JSONArray) offer.get("action");
                String action = (String) offerAction.get(0);
                if ("application/vnd.ims.lti.v2.toolproxy+json".equals(format) && "POST".equals(action)) {
                    registerAddress = (String) offer.get("endpoint");
                    break;
                }
            }

            /// FIXME: Sakai return server name as "localhost", could be my configuration
            String[] serverAddr = tcProfileUrl.split("/");
            String addr = serverAddr[2];
            registerAddress = registerAddress.substring(registerAddress.indexOf("/", 8));
            registerAddress = "http://" + addr + registerAddress;

            /// Send POST to specified URL as signed request with given values
            int responseCode = postData(registerAddress, toolProxy.toJSONString(), key, passwd);
            if (responseCode != HttpServletResponse.SC_CREATED) {
                //TODO BOOM!
                throw new RuntimeException("Bad response code.  Got " + responseCode + " but expected "
                        + HttpServletResponse.SC_CREATED);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    String output = "<a href='" + returnUrl + "'>Continue to launch presentation url</a>";

    try {
        PrintWriter out = response.getWriter();
        out.println(output);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.bashtech.geobot.Channel.java

public boolean addToList(String listName, String newItem) {
    JSONObject list1 = (JSONObject) lists.get(listName);
    JSONArray list = (JSONArray) list1.get("items");
    if (!list.contains(newItem)) {
        list.add(newItem);//w w  w . j  a  v a2 s  . c o  m
        list1.put("items", list);
        lists.put(listName, list1);
        config.put("lists", lists);
        saveConfig(true);
        return true;
    } else {
        return false;
    }
}