Example usage for org.json.simple JSONObject toString

List of usage examples for org.json.simple JSONObject toString

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:mml.handler.mvd.Archive.java

/**
 * Convert this archive to a resource, wrapped in JSON for storage
 * @param mvdName name of the MVD//from w w  w.  j  a v a2 s  .  c  o m
 * @return a string representation of the MVD as a JSON document
 * @throws MMLException 
 */
public String toResource(String mvdName) throws MMLException {
    try {
        String body;
        JSONObject doc = new JSONObject();
        if (size() == 1) {
            Set<String> keys = keySet();
            Iterator<String> iter = keys.iterator();
            String key = iter.next();
            char[] data = get(key);
            if (format.equals(Formats.MVD_STIL))
                format = Formats.STIL;
            else if (format.equals(Formats.MVD_TEXT))
                format = Formats.TEXT;
            body = new String(data);
            if (version1 == null)
                version1 = key;
            if (nameMap.containsKey(version1))
                description = nameMap.get(version1);
        } else {
            // more than 1 version: make an MVD 
            Set<String> keys = keySet();
            Iterator<String> iter = keys.iterator();
            MVD mvd = new MVD();
            mvd.setDescription(description);
            // go through the files, adding versions to the MVD
            short vId;
            long startTime = System.currentTimeMillis();
            while (iter.hasNext()) {
                String key = iter.next();
                String groups = getGroups(key);
                String shortKey = getKey(key);
                if (version1 == null)
                    version1 = "/" + groups + "/" + shortKey;
                char[] data = get(key);
                String longName = nameMap.get(key);
                if (longName == null) {
                    longName = "Version ";
                    longName += (groups.length() > 0) ? shortKey + " of " + groups : shortKey;
                }
                vId = (short) mvd.newVersion(shortKey, longName, groups, Version.NO_BACKUP, false);
                // tepmorary hack
                mvd.setDirectAlign(true);
                mvd.update(vId, data, true);
            }
            long diff = System.currentTimeMillis() - startTime;
            log.append("merged ");
            log.append(": ");
            log.append(mvdName);
            log.append(" in ");
            log.append(diff);
            log.append(" milliseconds\n");
            body = mvd.toString();
            if (body.length() == 0)
                throw new MMLException("failed to create MVD");
            if (format.equals(Formats.TEXT) || format.equals(Formats.STIL))
                format = "MVD/" + format;
        }
        doc.put(JSONKeys.VERSION1, version1);
        doc.put(JSONKeys.STYLE, style);
        doc.put(JSONKeys.FORMAT, format);
        doc.put(JSONKeys.BODY, body);
        return doc.toString();
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:importer.Archive.java

/**
 * Convert this archive to a resource, wrapped in JSON for storage
 * @param mvdName name of the MVD/*  w w w .  j a  v a2 s. c  o  m*/
 * @return a string representation of the MVD as a JSON document
 * @throws AeseException 
 */
public String toResource(String mvdName) throws AeseException {
    try {
        String body;
        JSONObject doc = new JSONObject();
        if (size() == 1) {
            Set<String> keys = keySet();
            Iterator<String> iter = keys.iterator();
            String key = iter.next();
            char[] data = get(key);
            if (format.equals(Formats.MVD_STIL))
                format = Formats.STIL;
            else if (format.equals(Formats.MVD_TEXT))
                format = Formats.TEXT;
            body = new String(data);
            if (version1 == null)
                version1 = key;
        } else {
            // more than 1 version: make an MVD 
            Set<String> keys = keySet();
            Iterator<String> iter = keys.iterator();
            MVD mvd = new MVD();
            mvd.setDescription(description);
            // go through the files, adding versions to the MVD
            short vId;
            long startTime = System.currentTimeMillis();
            while (iter.hasNext()) {
                String key = iter.next();
                String groups = getGroups(key);
                String shortKey = getKey(key);
                if (version1 == null) {
                    version1 = "/" + shortKey;
                    if (groups != null && groups.length() > 0)
                        version1 = "/" + groups + version1;
                }
                char[] data = get(key);
                vId = (short) mvd.newVersion(shortKey, getLongName(shortKey), groups, Version.NO_BACKUP, false);
                // tepmorary hack
                mvd.setDirectAlign(true);
                System.out.println("vid=" + vId + " shortKey=" + shortKey);
                mvd.update(vId, data, true);
            }
            long diff = System.currentTimeMillis() - startTime;
            log.append("merged ");
            log.append(title);
            log.append(": ");
            log.append(mvdName);
            log.append(" in ");
            log.append(diff);
            log.append(" milliseconds\n");
            body = mvd.toString();
            if (body.length() == 0)
                throw new AeseException("failed to create MVD");
            //format = Formats.MVD;
        }
        doc.put(JSONKeys.TITLE, title);
        doc.put(JSONKeys.VERSION1, version1);
        doc.put(JSONKeys.DESCRIPTION, description);
        doc.put(JSONKeys.AUTHOR, author);
        doc.put(JSONKeys.STYLE, style);
        doc.put(JSONKeys.FORMAT, format);
        doc.put(JSONKeys.BODY, body);
        //externalise(mvdName);
        return doc.toString();
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:de.dailab.plistacontest.client.ContestHandler.java

/**
 * Method to handle incoming messages from the server.
 * /*from  ww w .j  av  a2 s.c  o m*/
 * @param messageType
 *                the messageType of the incoming contest server message.
 * @param properties
 *                
 * @param entities
 * @return the response to the contest server
 */
@SuppressWarnings("unchecked")
private String handleIdomaarMessage(final String messageType, final String properties, final String entities) {
    // write all data from the server to a file
    // logger.info(messageType + "\t" + properties + "\t" + entities);

    // create an jSON object from the String
    final JSONObject jOP = (JSONObject) JSONValue.parse(properties);
    final JSONObject jOE = (JSONObject) JSONValue.parse(entities);

    // merge the different jsonObjects and correct missing itemIDs
    jOP.putAll(jOE);
    Object itemID = jOP.get("itemID");
    if (itemID == null) {
        jOP.put("itemID", 0);
    }

    // define a response object
    String response = null;

    if ("impression".equalsIgnoreCase(messageType) || "recommendation".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString());
        final String eventNotificationType = messageType;

        // impression refers to articles read by the user
        if ("impression".equalsIgnoreCase(eventNotificationType)
                || "recommendation".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                // new items shall be added to the list of items
                recommenderItemTable.handleItemUpdate(item);
                item.setNumberOfRequestedResults(6);

                response = "handle impression eventNotification successful";

                boolean recommendationExpected = false;
                if (properties.contains("\"event_type\": \"recommendation_request\"")) {
                    recommendationExpected = true;
                }
                if (recommendationExpected) {
                    List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item);
                    response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}";
                }

            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                // new items shall be added to the list of items
                recommenderItemTable.handleItemUpdate(item);

                response = "handle impression eventNotification successful";
            }
            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString());

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jOP.toString() + jOE.toJSONString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:hoot.services.controllers.osm.MapResource.java

@GET
@Path("/tags")
@Produces(MediaType.APPLICATION_JSON)// ww w.j  a  v a  2  s  .  com
public Response getTags(@QueryParam("mapid") String mapId) {
    JSONObject json = new JSONObject();
    try (Connection connection = DbUtils.createConnection()) {
        if (!StringUtils.isEmpty(mapId)) {
            long mapIdNum = -2;
            try {
                mapIdNum = Long.parseLong(mapId);
            } catch (NumberFormatException ignored) {
                // a map name string could also be passed in here
            }

            if (mapIdNum != -1) // not OSM API db
            {
                mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, connection, maps, maps.id,
                        maps.displayName);
                logger.info("Retrieving map tags for map with ID: {} ...", mapIdNum);

                try {
                    java.util.Map<String, String> tags = DbUtils.getMapsTableTags(mapIdNum, connection);
                    if (tags != null) {
                        logger.debug(tags.toString());
                    }
                    json.putAll(tags);
                    Object oInput1 = json.get("input1");
                    if (oInput1 != null) {
                        String dispName = DbUtils.getDisplayNameById(connection,
                                Long.valueOf(oInput1.toString()));
                        json.put("input1Name", dispName);
                    }

                    Object oInput2 = json.get("input2");
                    if (oInput2 != null) {
                        String dispName = DbUtils.getDisplayNameById(connection,
                                Long.valueOf(oInput2.toString()));
                        json.put("input2Name", dispName);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Error getting map tags. :" + e.getMessage(), e);
                }
            }
        }
    } catch (Exception e) {
        handleError(e, mapId, "");
    }

    return Response.ok(json.toString()).build();
}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

private String parsePost(String request) throws IOException, Exception {

    //FIX THE ERRORS AS JSONS!!!!!!!!!!!!!!!!!!!!!S
    request = request.replaceAll("POST", "");
    JSONObject jso = new JSONObject();

    if (request.contains("HTTP/1.1")) {
        request = request.replaceAll("HTTP/1.1", "");
    } else {/*from  w  w w .j a v  a 2 s.  c o  m*/
        return " not HTTP/1.1 header";
        //error msg
    }
    request = request.trim();
    String[] MethodAndParams = request.split("\\?");
    if (MethodAndParams.length > 1) { //if the request has ? or parameters
        String method = MethodAndParams[0].replaceAll("/", "");
        String query = MethodAndParams[1];
        Map<String, String> params = parseQuery(query);
        System.out.println("method " + method);
        for (String s : params.keySet()) {
            System.out.println(s + " value=" + params.get(s));
        }
        if (method.equalsIgnoreCase("CreateUser")) {
            CreateUser cu = new CreateUser(params.get("application_key"), this.properties);
            jso = cu.processRequest();
        } else if (method.equalsIgnoreCase("GetUserProfile")) {
            GetUserProfile gup = new GetUserProfile(params.get("application_key"), params.get("user_id"),
                    this.properties);
            jso = gup.processRequest();
        } else if (method.equalsIgnoreCase("CreateGroup")) {
            CreateGroup cg = new CreateGroup(params.get("application_key"), params.get("users_list"),
                    this.properties);
            jso = cg.processRequest();
        } else if (method.equalsIgnoreCase("SubmitCreativityExhibit")) {
            SubmitCreativityExhibit sce = new SubmitCreativityExhibit(params.get("application_key"),
                    params.get("user_id"), params.get("exhibit"), params.get("type"), params.get("language"),
                    this.properties);
            jso = sce.processRequest();
        } else if (method.equalsIgnoreCase("SubmitExhibitPreferenceList")) {
            SubmitExhibitPreferenceList sepl = new SubmitExhibitPreferenceList(params.get("application_key"),
                    params.get("user_id"), params.get("exhibit_list_id"), params.get("preference_list_id"),
                    this.properties);
            jso = sepl.processRequest();
        } else if (method.equalsIgnoreCase("SubmitUserFormalEvaluationList")) {
            SubmitUserFormalEvaluationList sufel = new SubmitUserFormalEvaluationList(
                    params.get("application_key"), params.get("users_list"), this.properties);
            jso = sufel.processRequest();
        } else if (method.equalsIgnoreCase("SubmitUserInformalEvaluationList")) {
            SubmitUserInformalEvaluationList suiel = new SubmitUserInformalEvaluationList(
                    params.get("application_key"), params.get("evaluator_id"), params.get("users_list"),
                    this.properties);
            jso = suiel.processRequest();
        } else {
            return "not known method";
        }

    } else {
        return "no parameters given";
    }
    return jso.toString(); //return the answer
}

From source file:gov.nih.nci.cma.web.ajax.RegHelper.java

public static String pReg(String ln, String fn, String em, String in, String ca, String ph, String de) {
    //look @ the captcha
    JSONObject jso = new JSONObject();
    String status = "pass";
    String msg = "";
    WebContext webContext = WebContextFactory.get();
    HttpSession session = webContext.getSession();

    String k = session.getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY) != null
            ? (String) session.getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY)
            : null;/*  w ww  . j a v  a  2 s.  c  om*/

    if (k != null && k.equals(ca.trim())) {

        try {
            //need to clean the generalFeedback field, also put this in the props as a template
            MailProps mp = new MailProps();

            //make sure its only 1 email
            em = em.replace(",", "").replace(";", "");
            //send the mail to APP support
            /*
            String fdbk = fn + " " + ln + " is requesting an account for the CMA Application. \n\n";
            fdbk += "Their email is: " + em + " \n";
            fdbk += "Their institution is: " + in + " \n";
            fdbk += "\n\nThis is an automated email sent from the CMA Application.\n";
            */
            //String fdbk = System.getProperty("cma.register.template.support");
            Map propsMap = (Map) ConfigurationHolder.getFlatConfig();
            String fdbk = (String) propsMap.get("cma.register.template.support");
            fdbk = fdbk.replace("{last_name}", (ln != null) ? ln : "None");
            fdbk = fdbk.replace("{first_name}", (fn != null) ? fn : "None");
            fdbk = fdbk.replace("{email}", (em != null) ? em : "None");
            fdbk = fdbk.replace("{phone}", (ph != null) ? ph : "None");
            fdbk = fdbk.replace("{department}", (de != null) ? de : "None");
            fdbk = fdbk.replace("{institution}", (in != null) ? in : "None");

            mp.setBody(fdbk);
            //the fields below should be in a props file
            mp.setSmtp((String) propsMap.get("cma.feedback.mailSMPT"));
            mp.setSubject((String) propsMap.get("cma.register.mailSubject.support"));
            mp.setMailTo((String) propsMap.get("cma.register.mailTo.support"));
            mp.setMailFrom((String) propsMap.get("cma.feedback.mailFrom"));

            Mail.sendMail(mp);

            //send the mail to the user
            mp = new MailProps();
            fdbk = (String) propsMap.get("cma.register.template.user");
            fdbk = fdbk.replace("{last_name}", (ln != null) ? ln : "None");
            fdbk = fdbk.replace("{first_name}", (fn != null) ? fn : "None");
            /*
             fdbk = "Dear " + fn + " " + ln + ",\n Thanks for registering for access to the CMA Application.  You will receive your official account information via email shortly.  Please contact ncicb@pop.nci.nih.gov for further assistance.\n";
            fdbk += "\n\nSincerely,\n-The CMA Team";
            */
            mp.setBody(fdbk);
            mp.setSmtp((String) propsMap.get("cma.feedback.mailSMPT"));
            mp.setSubject((String) propsMap.get("cma.register.mailSubject.user"));
            mp.setMailTo(em.trim());
            mp.setMailFrom((String) propsMap.get("cma.feedback.mailFrom"));

            Mail.sendMail(mp);
        }

        catch (ValidationException e) {
            logger.error("mail did not send from regHelper");
            logger.error(e);
            status = "failed";
            msg = "SEND_FAILED";
        } catch (Exception e) {
            logger.error("mail did not send from regHelper");
            logger.error(e);
            status = "failed";
            msg = "SEND_FAILED_GENERIC";
        }
    } else {
        status = "fail";
        msg = "BAD_CAPTCHA";
    }

    jso.put("status", status);
    jso.put("msg", msg);

    if (status.equals("pass")) {
        // Uncomment the two lines below to enable login after registration (more steps are needed).
        // Should change the login parameters too
        //jso.put("un", "RBTuser");
        //jso.put("ps", "RBTpass");
    }

    return jso.toString();
}

From source file:com.pinterest.rocksplicator.ConfigGenerator.java

private void generateShardConfig() {
    HelixAdmin admin = helixManager.getClusterManagmentTool();

    List<String> resources = admin.getResourcesInCluster(clusterName);

    Set<String> existingHosts = new HashSet<String>();

    // compose cluster config
    JSONObject config = new JSONObject();
    for (String resource : resources) {
        // Resources starting with PARTICIPANT_LEADER is for HelixCustomCodeRunner
        if (resource.startsWith("PARTICIPANT_LEADER")) {
            continue;
        }/*from   w ww.ja  v a  2  s.  c o  m*/

        ExternalView externalView = admin.getResourceExternalView(clusterName, resource);
        Set<String> partitions = externalView.getPartitionSet();

        // compose resource config
        JSONObject resourceConfig = new JSONObject();
        String partitionsStr = externalView.getRecord().getSimpleField("NUM_PARTITIONS");
        resourceConfig.put("num_shards", Integer.parseInt(partitionsStr));

        // build host to partition list map
        Map<String, List<String>> hostToPartitionList = new HashMap<String, List<String>>();
        for (String partition : partitions) {
            String[] parts = partition.split("_");
            String partitionNumber = String.format("%05d", Integer.parseInt(parts[parts.length - 1]));
            Map<String, String> hostToState = externalView.getStateMap(partition);
            for (Map.Entry<String, String> entry : hostToState.entrySet()) {
                existingHosts.add(entry.getKey());

                if (disabledHosts.contains(entry.getKey())) {
                    // exclude disabled hosts from the shard map config
                    continue;
                }

                String state = entry.getValue();
                if (!state.equalsIgnoreCase("ONLINE") && !state.equalsIgnoreCase("MASTER")
                        && !state.equalsIgnoreCase("SLAVE")) {
                    // Only ONLINE, MASTER and SLAVE states are ready for serving traffic
                    continue;
                }

                String hostWithDomain = getHostWithDomain(entry.getKey());
                List<String> partitionList = hostToPartitionList.get(hostWithDomain);
                if (partitionList == null) {
                    partitionList = new ArrayList<String>();
                    hostToPartitionList.put(hostWithDomain, partitionList);
                }

                if (state.equalsIgnoreCase("SLAVE")) {
                    partitionList.add(partitionNumber + ":S");
                } else if (state.equalsIgnoreCase("MASTER")) {
                    partitionList.add(partitionNumber + ":M");
                } else {
                    partitionList.add(partitionNumber);
                }
            }
        }

        // Add host to partition list map to the resource config
        for (Map.Entry<String, List<String>> entry : hostToPartitionList.entrySet()) {
            JSONArray jsonArray = new JSONArray();
            for (String p : entry.getValue()) {
                jsonArray.add(p);
            }

            resourceConfig.put(entry.getKey(), jsonArray);
        }

        // add the resource config to the cluster config
        config.put(resource, resourceConfig);
    }

    // remove host that doesn't exist in the ExternalView from hostToHostWithDomain
    hostToHostWithDomain.keySet().retainAll(existingHosts);

    String newContent = config.toString();
    if (lastPostedContent != null && lastPostedContent.equals(newContent)) {
        LOG.error("Identical external view observed, skip updating config.");
        return;
    }

    // Write the config to ZK
    LOG.error("Generating a new shard config...");

    this.dataParameters.remove("content");
    this.dataParameters.put("content", newContent);
    HttpPost httpPost = new HttpPost(this.postUrl);
    try {
        httpPost.setEntity(new StringEntity(this.dataParameters.toString()));
        HttpResponse response = new DefaultHttpClient().execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            lastPostedContent = newContent;
            LOG.error("Succeed to generate a new shard config, sleep for 2 seconds");
            TimeUnit.SECONDS.sleep(2);
        } else {
            LOG.error(response.getStatusLine().getReasonPhrase());
        }
    } catch (Exception e) {
        LOG.error("Failed to post the new config", e);
    }
}

From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java

/**
 * Method to handle incoming messages from the server.
 * /*from w  ww . j a va2s  .  co m*/
 * @param messageType
 *            the messageType of the incoming contest server message
 * @param _jsonString
 *            the incoming contest server message
 * @return the response to the contest server
 */
@SuppressWarnings("unused")
private String handleTraditionalMessage(final String messageType, final String _jsonMessageBody) {

    // write all data from the server to a file
    logger.info(messageType + "\t" + _jsonMessageBody);

    // create an jSON object from the String
    final JSONObject jObj = (JSONObject) JSONValue.parse(_jsonMessageBody);

    // define a response object
    String response = null;

    // TODO handle "item_create"

    // in a complex if/switch statement we handle the differentTypes of
    // messages
    if ("item_update".equalsIgnoreCase(messageType)) {

        // we extract itemID, domainID, text and the timeTime, create/update
        final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        // we mark this information in the article table
        if (recommenderItem.getItemID() != null) {
            recommenderItemTable.handleItemUpdate(recommenderItem);
        }

        response = ";item_update successfull";
    }

    else if ("recommendation_request".equalsIgnoreCase(messageType)) {
        final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        // we handle a recommendation request
        try {
            // parse the new recommender request
            RecommenderItem currentRequest = RecommenderItem.parseRecommendationRequest(_jsonMessageBody);

            // gather the items to be recommended
            List<Long> resultList = recommenderItemTable.getLastItems(currentRequest);
            if (resultList == null) {
                response = "[]";
                System.out.println("invalid resultList");
            } else {
                response = resultList.toString();
            }
            response = getRecommendationResultJSON(response);

            // TODO? might handle the the request as impressions
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } else if ("event_notification".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(_jsonMessageBody);
        final String eventNotificationType = item.getNotificationType();

        // impression refers to articles read by the user
        if ("impression".equalsIgnoreCase(eventNotificationType)
                || "impression_empty".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                // new items shall be added to the list of items
                recommenderItemTable.handleItemUpdate(item);

                response = "handle impression eventNotification successful";
            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + _jsonMessageBody);

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jObj.toString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:de.dailab.plistacontest.client.ContestHandlerOfflineCheating.java

/**
 * Method to handle incoming messages from the server.
 * /*from w  w w.  j  av a 2 s  . com*/
 * @param messageType
 *            the messageType of the incoming contest server message
 * @param _jsonMessageBody
 *            the incoming contest server message
 * @return the response to the contest server
 */
@SuppressWarnings("unused")
private String handleTraditionalMessage(final String messageType, final String _jsonMessageBody) {

    // write all data from the server to a file
    logger.info(messageType + "\t" + _jsonMessageBody);

    // create an jSON object from the String
    final JSONObject jObj = (JSONObject) JSONValue.parse(_jsonMessageBody);

    // define a response object
    String response = null;

    // TODO handle "item_create"

    // in a complex if/switch statement we handle the differentTypes of
    // messages
    if ("item_update".equalsIgnoreCase(messageType)) {

        // we extract itemID, domainID, text and the timeTime, create/update
        final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        response = ";item_update successfull";
    }

    else if ("recommendation_request".equalsIgnoreCase(messageType)) {
        // THIS ISN'T WORKING BECAUSE REQUEST HAS A DIFFRENT JSON FORMAT THEN ITEM UPDATE
        //final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody);

        // we handle a recommendation request
        try {
            // parse the new recommender request
            RecommenderItem currentRequest = RecommenderItem.parseRecommendationRequest(_jsonMessageBody);

            // gather the items to be recommended
            List<Long> resultList = recommenderItemTable.getFutureItems(currentRequest.getTimeStamp(),
                    currentRequest.getDomainID(), currentRequest.getUserID());
            if (resultList == null) {
                response = "[]";
                System.out.println("invalid resultList");
            } else {
                response = resultList.toString();
            }
            response = getRecommendationResultJSON(response);

            // TODO? might handle the the request as impressions
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } else if ("event_notification".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(_jsonMessageBody);
        final String eventNotificationType = item.getNotificationType();

        // impression refers to articles read by the user
        if ("impression".equalsIgnoreCase(eventNotificationType)
                || "impression_empty".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                response = "handle impression eventNotification successful";
            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + _jsonMessageBody);

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jObj.toString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:gov.nih.nci.caintegrator.application.lists.UserListBeanHelper.java

public String getDetailsFromList(String listName) {
    JSONObject listDetails = new JSONObject();
    if (userListBean != null) {
        UserList userList = userListBean.getList(listName);

        listDetails.put("listName", userList.getName());
        listDetails.put("listType", userList.getListType().toString());

        /**/*w  ww  .  j  av a 2 s.  c o  m*/
         * new way of retrieving details from lists. Each
         * listItem is treated as such, and NOT just a string.*/

        //        if(userList.getListItems()!=null && !userList.getListItems().isEmpty()){
        //            JSONArray listItems = new JSONArray();             
        //            
        //            String itemDescription = "";
        //            for(ListItem listItem:userList.getListItems()){
        //                String name = listItem.getName();
        //                itemDescription = name;
        //                if(listItem.getNotes()!=null && listItem.getNotes().trim().length()>=1){
        //                    itemDescription += " notes: " + listItem.getNotes();
        //                }
        //                if(listItem.getRank()!=null){
        //                    itemDescription += " rank: " + Double.toString(listItem.getRank());
        //                }
        //                
        //                listItems.add(itemDescription);
        //            }
        //            listDetails.put("validItems", listItems );
        //        }

        if (userList.getListItems() != null && !userList.getListItems().isEmpty()) {
            JSONArray listItems = new JSONArray();

            for (ListItem listItem : userList.getListItems()) {
                String name = listItem.getName();
                JSONObject itemDescription = new JSONObject();
                itemDescription.put("name", name);
                if (listItem.getNotes() != null && listItem.getNotes().trim().length() >= 1) {
                    itemDescription.put("notes", listItem.getNotes());
                }
                if (listItem.getRank() != null) {
                    itemDescription.put("rank", Long.toString(listItem.getRank()));
                }

                listItems.add(itemDescription);
            }
            listDetails.put("validItems", listItems);
        }

        /** if(userList.getList()!=null && !userList.getList().isEmpty()){
             JSONArray item = new JSONArray();             
             for(String i : userList.getList()){
        //Element item = list.addElement("item");
        //item.addText(i);
        item.add(i);
             }
             listDetails.put("validItems", item );
         }
         */

        if (userList.getInvalidList() != null && !userList.getInvalidList().isEmpty()) {
            JSONArray item = new JSONArray();
            for (String v : userList.getInvalidList()) {
                //Element item = list.addElement("invalidItem");
                //item.addText(v);
                item.add(v);
            }
            listDetails.put("invalidItems", item);
        }
    }
    return listDetails.toString();
}