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:org.powertac.hamweather.Parser.java

public void processFiles() {
    try {//  ww w .ja  v a  2s  . c o m
        BufferedReader in = new BufferedReader(new FileReader(inputFile));
        Pattern observation = Pattern.compile("^-- observation: ([SMTWF][a-z]+ [A-Za-z]+ \\d+ [-0-9: ]+)");
        Pattern loc = Pattern.compile("^-- location: " + location);
        String line;
        State state = State.OBS;
        Matcher m;
        JSONParser jparser = new JSONParser();
        DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM d HH:mm:ss Z YYYY");
        iso = ISODateTimeFormat.dateTimeNoMillis();
        DateTime lastObs = null;
        DateTime obsHour = null;
        while (true) {
            line = in.readLine();
            if (null == line || 0 == line.length())
                break;
            switch (state) {
            case OBS:
                m = observation.matcher(line);
                if (m.matches()) {
                    DateTime obsTime = dtf.parseDateTime(m.group(1));
                    if (null == lastObs) {
                        lastObs = obsTime;
                    } else if (obsTime.isAfter(lastObs.plus(MAX_INTERVAL))) {
                        System.out.println("Missed obs - last = " + iso.print(lastObs) + ", current = "
                                + iso.print(obsTime));
                    }
                    lastObs = obsTime;
                    obsHour = obsTime.plus(HOUR / 2).withMillisOfSecond(0).withSecondOfMinute(0)
                            .withMinuteOfHour(0);
                    state = State.LOC;
                }
                break;
            case LOC:
                m = loc.matcher(line);
                if (m.matches()) {
                    //System.out.println("Location: " + location);
                    state = State.JSON_OB;
                }
                break;
            case JSON_OB:
                // process new observation
                JSONObject obs = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success = (Boolean) obs.get("success");
                if (!success) {
                    System.out.println("Observation retrieval failed at " + iso.print(obsHour));
                    state = State.OBS;
                } else {
                    JSONObject err = (JSONObject) obs.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Observation error: " + msg + " at " + iso.print(obsHour));
                        state = State.OBS;
                    } else {
                        try {
                            JSONObject response = (JSONObject) obs.get("response");
                            JSONObject ob = (JSONObject) response.get("ob");
                            extractObservation(ob);
                            state = State.JSON_FCST;
                        } catch (ClassCastException cce) {
                            System.out.println("Faulty observation " + obs.toString());
                            state = State.OBS;
                        }
                    }
                }
                break;
            case JSON_FCST:
                // process new forecast
                JSONObject fcst = (JSONObject) jparser.parse(line);
                // check for errors
                Boolean success1 = (Boolean) fcst.get("success");
                if (!success1) {
                    // could not retrieve forecast
                    System.out.println("Forecast retrieval failed at " + iso.print(obsHour));
                    output.forecastMissing();
                } else {
                    JSONObject err = (JSONObject) fcst.get("error");
                    if (null != err) {
                        // error at server end
                        String msg = (String) err.get("description");
                        System.out.println("Forecast error: " + msg + " at " + iso.print(obsHour));
                        output.forecastMissing();
                    } else {
                        JSONArray response = (JSONArray) fcst.get("response");
                        if (response.size() == 0) {
                            // should never get here
                            System.out.println("Empty forecast at " + iso.print(obsHour));
                        }
                        JSONObject periods = (JSONObject) response.get(0);
                        JSONArray fcsts = (JSONArray) periods.get("periods");
                        if (fcsts.size() != FORECAST_HORIZON) {
                            System.out.println(
                                    "Missing forecasts (" + fcsts.size() + ") at " + iso.print(lastObs));
                        }
                        for (int i = 0; i < fcsts.size(); i++) {
                            JSONObject forecast = (JSONObject) fcsts.get(i);
                            extractForecast(forecast, i + 1, obsHour);
                        }
                    }
                }
                state = State.OBS;
                break;
            }
        }
        output.write();
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.basiclti.util.SakaiBLTIUtil.java

/**
 * An LTI 2.0 ContentItemSelectionRequest launch
 *
 * This must return an HTML message as the [0] in the array
 * If things are successful - the launch URL is in [1]
 *///w  ww. j  a v  a 2s .  c o m
public static String[] postContentItemSelectionRequest(Long toolKey, Map<String, Object> tool,
        ResourceLoader rb, String contentReturn, Properties dataProps) {
    if (tool == null) {
        return postError(
                "<p>" + getRB(rb, "error.tool.missing", "Tool is missing or improperly configured.") + "</p>");
    }

    String launch_url = (String) tool.get("launch");
    if (launch_url == null)
        return postError("<p>" + getRB(rb, "error.tool.noreg", "This tool is has no launch url.") + "</p>");

    String consumerkey = (String) tool.get(LTIService.LTI_CONSUMERKEY);
    String secret = (String) tool.get(LTIService.LTI_SECRET);

    // If secret is encrypted, decrypt it
    secret = decryptSecret(secret);

    if (secret == null || consumerkey == null) {
        return postError("<p>"
                + getRB(rb, "error.tool.partial", "Tool is incomplete, missing a key and secret.") + "</p>");
    }

    // Start building up the properties
    Properties ltiProps = new Properties();

    setProperty(ltiProps, BasicLTIConstants.LTI_VERSION, BasicLTIConstants.LTI_VERSION_1);
    setProperty(ltiProps, BasicLTIUtil.BASICLTI_SUBMIT,
            getRB(rb, "launch.button", "Press to Launch External Tool"));
    setProperty(ltiProps, BasicLTIConstants.LTI_MESSAGE_TYPE, LTI2Messages.CONTENT_ITEM_SELECTION_REQUEST);

    setProperty(ltiProps, ContentItem.ACCEPT_MEDIA_TYPES, ContentItem.MEDIA_LTILINKITEM);
    setProperty(ltiProps, BasicLTIConstants.ACCEPT_PRESENTATION_DOCUMENT_TARGETS, "iframe,window"); // Nice to add overlay
    setProperty(ltiProps, BasicLTIConstants.ACCEPT_UNSIGNED, "true");
    setProperty(ltiProps, BasicLTIConstants.ACCEPT_MULTIPLE, "false");
    setProperty(ltiProps, BasicLTIConstants.ACCEPT_COPY_ADVICE, "false"); // ???
    setProperty(ltiProps, BasicLTIConstants.AUTO_CREATE, "true");
    setProperty(ltiProps, BasicLTIConstants.CAN_CONFIRM, "false");
    // setProperty(ltiProps, BasicLTIConstants.TITLE, "");
    // setProperty(ltiProps, BasicLTIConstants.TEXT, "");

    // Pull in additonal data
    JSONObject dataJSON = new JSONObject();
    Enumeration en = dataProps.keys();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        String value = dataProps.getProperty(key);
        if (value == null)
            continue;

        // Allow overrides
        if (BasicLTIConstants.ACCEPT_MEDIA_TYPES.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.ACCEPT_MEDIA_TYPES, value);
            continue;
        } else if (BasicLTIConstants.ACCEPT_PRESENTATION_DOCUMENT_TARGETS.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.ACCEPT_PRESENTATION_DOCUMENT_TARGETS, value);
            continue;
        } else if (BasicLTIConstants.ACCEPT_UNSIGNED.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.ACCEPT_UNSIGNED, value);
            continue;
        } else if (BasicLTIConstants.AUTO_CREATE.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.AUTO_CREATE, value);
            continue;
        } else if (BasicLTIConstants.CAN_CONFIRM.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.CAN_CONFIRM, value);
            continue;
        } else if (BasicLTIConstants.TITLE.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.TITLE, value);
            continue;
        } else if (BasicLTIConstants.TEXT.equals(key)) {
            setProperty(ltiProps, BasicLTIConstants.TEXT, value);
            continue;
        }

        // Pass in data for use to get back.
        dataJSON.put(key, value);
    }
    setProperty(ltiProps, BasicLTIConstants.DATA, dataJSON.toString());

    setProperty(ltiProps, BasicLTIConstants.CONTENT_ITEM_RETURN_URL, contentReturn);

    // This must always be there
    String context = (String) tool.get(LTIService.LTI_SITE_ID);
    Site site = null;
    try {
        site = SiteService.getSite(context);
    } catch (Exception e) {
        dPrint("No site/page associated with Launch context=" + context);
        return postError("<p>" + getRB(rb, "error.site.missing", "Cannot load site.") + context + "</p>");
    }

    Properties lti2subst = new Properties();

    addGlobalData(site, ltiProps, lti2subst, rb);
    addSiteInfo(ltiProps, lti2subst, site);
    addRoleInfo(ltiProps, lti2subst, context, (String) tool.get("rolemap"));
    addUserInfo(ltiProps, lti2subst, tool);

    int debug = getInt(tool.get(LTIService.LTI_DEBUG));
    debug = 1;

    String customstr = toNull((String) tool.get(LTIService.LTI_CUSTOM));
    parseCustom(ltiProps, customstr);

    Map<String, String> extra = new HashMap<String, String>();
    ltiProps = BasicLTIUtil.signProperties(ltiProps, launch_url, "POST", consumerkey, secret, null, null, null,
            extra);

    M_log.debug("signed ltiProps=" + ltiProps);

    boolean dodebug = debug == 1;
    String postData = BasicLTIUtil.postLaunchHTML(ltiProps, launch_url, dodebug, extra);

    String[] retval = { postData, launch_url };
    return retval;
}

From source file:org.sakaiproject.lti2.LTI2Service.java

public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    Map<String, Object> deploy = ltiService.getDeployForConsumerKeyDao(profile_id);
    if (deploy == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*from w  w w .  ja v a 2s  .  c  o  m*/
    }
    Long deployKey = foorm.getLong(deploy.get(LTIService.LTI_ID));

    // See if we can even register...
    Long reg_state = foorm.getLong(deploy.get(LTIService.LTI_REG_STATE));
    String key = null;
    String secret = null;
    if (reg_state == 0) {
        key = (String) deploy.get(LTIService.LTI_REG_KEY);
        secret = (String) deploy.get(LTIService.LTI_REG_PASSWORD);
    } else {
        key = (String) deploy.get(LTIService.LTI_CONSUMERKEY);
        secret = (String) deploy.get(LTIService.LTI_SECRET);
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }
    // System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Blank out the new shared secret
    security_contract.put(LTI2Constants.SHARED_SECRET, "*********");

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = getToolConsumerProfile(deploy, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Passed all the tests, lets commit this...
    Map<String, Object> deployUpdate = new TreeMap<String, Object>();
    shared_secret = SakaiBLTIUtil.encryptSecret(shared_secret);
    deployUpdate.put(LTIService.LTI_SECRET, shared_secret);

    // Indicate ready to validate and kill the interim info
    deployUpdate.put(LTIService.LTI_REG_STATE, LTIService.LTI_REG_STATE_REGISTERED);
    deployUpdate.put(LTIService.LTI_REG_KEY, "");
    deployUpdate.put(LTIService.LTI_REG_PASSWORD, "");
    if (default_custom != null)
        deployUpdate.put(LTIService.LTI_SETTINGS, default_custom.toString());
    deployUpdate.put(LTIService.LTI_REG_PROFILE, providerProfile.toString());

    M_log.debug("deployUpdate=" + deployUpdate);

    Object obj = ltiService.updateDeployDao(deployKey, deployUpdate);
    boolean success = (obj instanceof Boolean) && ((Boolean) obj == Boolean.TRUE);
    if (!success) {
        M_log.warn(
                "updateDeployDao fail deployKey=" + deployKey + "\nretval=" + obj + "\ndata=" + deployUpdate);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Failed update of deployment=" + deployKey, null);
        return;
    }

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    String serverUrl = ServerConfigurationService.getServerUrl();
    jsonResponse.put(LTI2Constants.JSONLD_ID, resourceUrl + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            resourceUrl + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.debug(jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:org.sakaiproject.lti2.LTI2Service.java

public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {
    String allowSettings = ServerConfigurationService.getString(SakaiBLTIUtil.BASICLTI_SETTINGS_ENABLED,
            SakaiBLTIUtil.BASICLTI_SETTINGS_ENABLED_DEFAULT);
    if (!"true".equals(allowSettings)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, null, "Tool settings not available", null);
        return;/*www.j av a  2s. c  o  m*/
    }

    String URL = SakaiBLTIUtil.getOurServletPath(request);
    String scope = parts[4];

    // Check to see if we are doing the bubble
    String bubbleStr = request.getParameter("bubble");
    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    System.out.println("accept=" + acceptHdr + " bubble=" + bubbleStr);

    if (bubbleStr != null && bubbleStr.equals("all")
            && acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) < 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Simple format does not allow bubble=all", null);
        return;
    }

    boolean bubble = bubbleStr != null && "GET".equals(request.getMethod());
    boolean distinct = bubbleStr != null && "distinct".equals(bubbleStr) && "GET".equals(request.getMethod());
    boolean bubbleAll = bubbleStr != null && "all".equals(bubbleStr) && "GET".equals(request.getMethod());

    // Check our input and output formats
    boolean acceptSimple = acceptHdr == null
            || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT) >= 0;
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;
    boolean inputSimple = contentHdr == null
            || contentHdr.indexOf(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT) >= 0;
    boolean inputComplex = contentHdr != null && contentHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;
    System.out.println(
            "as=" + acceptSimple + " ac=" + acceptComplex + " is=" + inputSimple + " ic=" + inputComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = null;
    String siteId = null;
    String placement_id = null;

    Map<String, Object> content = null;
    Long contentKey = null;
    Map<String, Object> tool = null;
    Long toolKey = null;
    Map<String, Object> proxyBinding = null;
    Long proxyBindingKey = null;
    Map<String, Object> deploy = null;
    Long deployKey = null;

    if (LTI2Util.SCOPE_LtiLink.equals(scope) || LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) {
        placement_id = parts[5];
        System.out.println("placement_id=" + placement_id);
        String contentStr = placement_id.substring(8);
        contentKey = SakaiBLTIUtil.getLongKey(contentStr);
        if (contentKey >= 0) {
            // Leave off the siteId - bypass all checking - because we need to 
            // find the siteId from the content item
            content = ltiService.getContentDao(contentKey);
            if (content != null)
                siteId = (String) content.get(LTIService.LTI_SITE_ID);
        }

        if (content == null || siteId == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Bad content item", null);
            return;
        }

        toolKey = SakaiBLTIUtil.getLongKey(content.get(LTIService.LTI_TOOL_ID));
        if (toolKey >= 0) {
            tool = ltiService.getToolDao(toolKey, siteId);
        }

        if (tool == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Bad tool item", null);
            return;
        }

        // Adjust the content items based on the tool items
        ltiService.filterContent(content, tool);

        // Check settings to see if we are allowed to do this 
        if (foorm.getLong(content.get(LTIService.LTI_ALLOWOUTCOMES)) > 0
                || foorm.getLong(tool.get(LTIService.LTI_ALLOWOUTCOMES)) > 0) {
            // Good news 
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            doErrorJSON(request, response, jsonRequest, "Item does not allow tool settings", null);
            return;
        }

    }

    if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope) || LTI2Util.SCOPE_LtiLink.equals(scope)) {
        proxyBinding = ltiService.getProxyBindingDao(toolKey, siteId);
        if (proxyBinding != null) {
            proxyBindingKey = SakaiBLTIUtil.getLongKey(proxyBinding.get(LTIService.LTI_ID));
        }
    }

    // Retrieve the deployment if needed
    if (LTI2Util.SCOPE_ToolProxy.equals(scope)) {
        consumer_key = parts[5];
        deploy = ltiService.getDeployForConsumerKeyDao(consumer_key);
        if (deploy == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Bad deploy item", null);
            return;
        }
        deployKey = SakaiBLTIUtil.getLongKey(deploy.get(LTIService.LTI_ID));
    } else {
        if (tool == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Bad tool item", null);
            return;
        }
        deployKey = SakaiBLTIUtil.getLongKey(tool.get(LTIService.LTI_DEPLOYMENT_ID));
        if (deployKey >= 0) {
            deploy = ltiService.getDeployDao(deployKey);
        }
        if (deploy == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Bad deploy item", null);
            return;
        }
        consumer_key = (String) deploy.get(LTIService.LTI_CONSUMERKEY);
    }

    // Check settings to see if we are allowed to do this 
    if (deploy != null) {
        if (foorm.getLong(deploy.get(LTIService.LTI_ALLOWOUTCOMES)) > 0) {
            // Good news 
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            doErrorJSON(request, response, jsonRequest, "Deployment does not allow tool settings", null);
            return;
        }
    }

    // The URLs for the various settings resources
    String settingsUrl = SakaiBLTIUtil.getOurServerUrl() + LTI2_PATH + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + placement_id;
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + placement_id;

    // Load and parse the old settings...
    JSONObject link_settings = new JSONObject();
    JSONObject binding_settings = new JSONObject();
    JSONObject proxy_settings = new JSONObject();
    if (content != null) {
        link_settings = LTI2Util.parseSettings((String) content.get(LTIService.LTI_SETTINGS));
    }
    if (proxyBinding != null) {
        binding_settings = LTI2Util.parseSettings((String) proxyBinding.get(LTIService.LTI_SETTINGS));
    }
    if (deploy != null) {
        proxy_settings = LTI2Util.parseSettings((String) deploy.get(LTIService.LTI_SETTINGS));
    }

    /*
          if ( distinct && link_settings != null && scope.equals(LTI2Util.SCOPE_LtiLink) ) {
             Iterator i = link_settings.keySet().iterator();
             while ( i.hasNext() ) {
    String key = (String) i.next();
    if ( binding_settings != null ) binding_settings.remove(key);
    if ( proxy_settings != null ) proxy_settings.remove(key);
             }
          }
            
          if ( distinct && binding_settings != null && scope.equals(LTI2Util.SCOPE_ToolProxyBinding) ) {
             Iterator i = binding_settings.keySet().iterator();
             while ( i.hasNext() ) {
    String key = (String) i.next();
    if ( proxy_settings != null ) proxy_settings.remove(key);
             }
          }
    */

    // Get the secret for the request...
    String oauth_secret = null;
    if (LTI2Util.SCOPE_LtiLink.equals(scope)) {
        oauth_secret = (String) content.get(LTIService.LTI_SECRET);
        if (oauth_secret == null || oauth_secret.length() < 1) {
            oauth_secret = (String) tool.get(LTIService.LTI_SECRET);
        }
    } else if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) {
        oauth_secret = (String) tool.get(LTIService.LTI_SECRET);
    } else if (LTI2Util.SCOPE_ToolProxy.equals(scope)) {
        oauth_secret = (String) deploy.get(LTIService.LTI_SECRET);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Bad Setttings Scope=" + scope, null);
        return;
    }

    // Make sure we have a key and secret
    if (oauth_secret == null || consumer_key == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Key or secret is null, key=" + consumer_key, null);
        return;
    }

    // Validate the incoming message
    Object retval = SakaiBLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }

        retval = null;
        if (LTI2Util.SCOPE_LtiLink.equals(scope)) {
            content.put(LTIService.LTI_SETTINGS, settings);
            retval = ltiService.updateContentDao(contentKey, content, siteId);
        } else if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) {
            if (proxyBinding != null) {
                proxyBinding.put(LTIService.LTI_SETTINGS, settings);
                retval = ltiService.updateProxyBindingDao(proxyBindingKey, proxyBinding);
            } else {
                Properties proxyBindingNew = new Properties();
                proxyBindingNew.setProperty(LTIService.LTI_SITE_ID, siteId);
                proxyBindingNew.setProperty(LTIService.LTI_TOOL_ID, toolKey + "");
                proxyBindingNew.setProperty(LTIService.LTI_SETTINGS, settings);
                retval = ltiService.insertProxyBindingDao(proxyBindingNew);
                M_log.info("inserted ProxyBinding setting=" + proxyBindingNew);
            }
        } else if (LTI2Util.SCOPE_ToolProxy.equals(scope)) {
            deploy.put(LTIService.LTI_SETTINGS, settings);
            retval = ltiService.updateDeployDao(deployKey, deploy);
        }
        if (retval instanceof String || (retval instanceof Boolean && ((Boolean) retval != Boolean.TRUE))) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) retval, null);
            return;
        }
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:org.sample.whiteboardapp.MyWhiteboard.java

@OnMessage
public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
    System.out.println("broadcastFigure: " + figure);
    JSONObject coordinates = new JSONObject();
    JSONArray lat_json = new JSONArray();
    JSONArray long_json = new JSONArray();
    try {/*ww w.j ava  2 s. c o m*/
        /*   FileInputStream in = new FileInputStream("C:\\Users\\Nirmit Shah\\Desktop\\mapsapp_ec504\\location.txt");
           BufferedReader br = new BufferedReader(new InputStreamReader(in));*/
        //sample values
        try {
            double latitude = figure.getJson().getJsonObject("coords").getJsonNumber("Latitude").doubleValue();
            double longitude = figure.getJson().getJsonObject("coords").getJsonNumber("Longitude")
                    .doubleValue();
            double[] coord = { latitude, longitude };
            coordinates = findKNN(coord, root, 1000);
        } catch (NullPointerException e) {
            double max_lat = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lat").doubleValue();
            double max_lng = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lng").doubleValue();
            double min_lat = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lat").doubleValue();
            double min_lng = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lng").doubleValue();
            double[] max = { max_lat, min_lng };
            double[] min = { min_lat, max_lng };
            System.out.println(max_lat + " " + min_lng);
            Vector<Node> v = new Vector();
            rsearch(min, max, root, v);
            for (int i = 0; i < v.size(); i++) {
                Node x = v.get(i);
                // System.out.println(x.point[0] + " "+ x.point[1]);
                lat_json.add(x.point[0]);
                long_json.add(x.point[1]);
            }
            coordinates.put("latitude", lat_json);
            coordinates.put("longitude", long_json);
        }
        /*   String strLine;
           LinkedHashMap<Area, Double> newmap = new LinkedHashMap<Area, Double>();
           while ((strLine = br.readLine()) != null) {
        String[] line = strLine.split("\t");
        double lat = Math.abs(Double.valueOf(line[2])) - latitude;
        double lon = Math.abs(Double.valueOf(line[3])) - longitude;
        double radius = Math.sqrt((Math.pow(lat, 2) + (Math.pow(lon, 2))));
        if (radius != 0) {
            if (!map.isEmpty()) {
                Iterator it = map.entrySet().iterator();
                Boolean found = false;
                newmap.clear();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    if ((Double) pair.getValue() >= radius && radius != 0) {
                        found = true;
                        newmap.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                        if (newmap.size() < 10) {
                            newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            while (it.hasNext() && newmap.size() < 10) {
                                pair = (Map.Entry) it.next();
                                newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            }
                        }
                        map = (LinkedHashMap<Area, Double>) newmap.clone();
                        break;
                    } else {
                        newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                    }
                }
                if (!found && map.size() < 10) {
                    map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                }
            } else {
                map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
            }
        }
           }
           in.close();
           Iterator it = map.entrySet().iterator();
           while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        String[] latlong = pair.getKey().toString().split(":") ;
        String lat1 = latlong[1];
        String long1 = latlong[3];
        lat_json.add(lat1);
        long_json.add(long1);                
           }
           coordinates.put("latitude", lat_json);
           coordinates.put("longitude", long_json);*/
        figure.setJson(Json.createReader(new StringReader(coordinates.toString())).readObject());
        RemoteEndpoint.Basic other = session.getBasicRemote();
        other.sendObject(figure);
        System.out.println("sent");
    } catch (Exception e) {
        System.out.println("here");
        e.printStackTrace();
    }

}

From source file:org.semispace.Tuple.java

public String getJSON() {
    if (this.json == null) {
        synchronized (searchMap) {
            JSONObject jobj = new JSONObject(this.searchMap);
            json = jobj.toString();
        }/*from  w w  w . ja  v a 2s.c om*/
    }
    return this.json;
}

From source file:org.servalproject.maps.indexgenerator.IndexWriter.java

/**
 * write the index json file/*from w  ww  . j a v a  2 s. co m*/
 * @param outputFile the path to the output file
 * @param mapInfoList a list of MapInfo objects contained in the index
 * @return true if the file is 
 */
@SuppressWarnings("unchecked")
public static boolean writeJsonIndex(File outputFile, ArrayList<MapInfo> mapInfoList) {

    //build the json object
    JSONObject jsonObject = new JSONObject();

    jsonObject.put("version", VERSION);
    jsonObject.put("generated", System.currentTimeMillis());
    jsonObject.put("author", AUTHOR);
    jsonObject.put("DataSource", DATA_SOURCE);
    jsonObject.put("DataFormat", DATA_FORMAT);
    jsonObject.put("DataFormatInfo", DATA_FORMAT_INFO);
    jsonObject.put("DataFormatVersion", DATA_FORMAT_VERSION);
    jsonObject.put("moreInfo", MORE_INFO);

    // build the json array of objects
    JSONArray jsonArray = new JSONArray();

    jsonArray.addAll(mapInfoList);

    // add list of objects
    jsonObject.put("mapFiles", jsonArray);

    // write the file
    try {
        PrintWriter writer = new PrintWriter(outputFile);
        writer.print(jsonObject.toString());
        writer.close();
    } catch (FileNotFoundException e) {
        System.err.println("ERROR: unable to write output file. " + e.getMessage());
        return false;
    }

    return true;
}

From source file:org.springfield.mojo.linkedtv.GAIN.java

public void sendContextRequest(String context, String videoTime) {
    this.videoTime = videoTime;
    JSONParser parser = new JSONParser();

    try {//from www .  j a  va  2s.  c o  m
        JSONObject json = (JSONObject) parser.parse(context);
        json.put("accountId", accountId);
        json.put("applicationId", applicationId);
        json.put("userId", userId);
        json.put("mediaresourceId", mediaresourceId);
        json.put("objectId", objectId);

        //add object information
        JSONObject object = new JSONObject();
        object.put("objectId", objectId);

        //add entities array
        JSONArray entities = new JSONArray();

        for (Iterator<GAINObjectEntity> it = this.entities.iterator(); it.hasNext();) {
            GAINObjectEntity ent = it.next();

            JSONObject entity = new JSONObject();
            entity.put("source", ent.source);
            entity.put("lod", ent.lod);
            entity.put("type", ent.type);
            entity.put("label", ent.label);
            entity.put("typeLabel", ent.typeLabel);
            entity.put("entityType", ent.entityType);
            entity.put("confidence", ent.confidence);
            entity.put("relevance", ent.relevance);

            entities.add(entity);
        }

        object.put("entities", entities);
        json.put("object", object);

        JSONObject attributes = (JSONObject) json.get("attributes");
        if (attributes != null) {
            attributes.put("location", videoTime);
        }

        String body = json.toString();

        sendRequest(body);
    } catch (ParseException e) {
        System.out.println("Could not parse context json " + context);
    }
}

From source file:org.springfield.mojo.linkedtv.GAIN.java

public void sendKeepAliveRequest(String videoTime) {
    this.videoTime = videoTime;

    JSONObject json = new JSONObject();
    json.put("accountId", accountId);
    json.put("applicationId", applicationId);
    json.put("screenId", screenId);
    json.put("userId", userId);
    json.put("mediaresourceId", mediaresourceId);
    json.put("type", type);
    json.put("objectId", objectId);

    //add object information
    JSONObject object = new JSONObject();
    object.put("objectId", objectId);

    //add entities array
    JSONArray entities = new JSONArray();

    for (Iterator<GAINObjectEntity> it = this.entities.iterator(); it.hasNext();) {
        GAINObjectEntity ent = it.next();

        JSONObject entity = new JSONObject();
        entity.put("source", ent.source);
        entity.put("lod", ent.lod);
        entity.put("type", ent.type);
        entity.put("label", ent.label);
        entity.put("typeLabel", ent.typeLabel);
        entity.put("entityType", ent.entityType);
        entity.put("confidence", ent.confidence);
        entity.put("relevance", ent.relevance);

        entities.add(entity);/*from  w w w .j a v a2  s  . com*/
    }

    object.put("entities", entities);
    json.put("object", object);

    //attach the keep alive attribute
    JSONObject attributes = new JSONObject();
    attributes.put("action", "keepalive");

    json.put("attributes", attributes);

    String body = json.toString();

    sendRequest(body);
}

From source file:org.springfield.mojo.linkedtv.GAIN.java

private void sendEventRequest() {
    JSONObject json = new JSONObject();
    json.put("accountId", accountId);
    json.put("applicationId", applicationId);
    json.put("screenId", screenId);
    json.put("userId", userId);
    json.put("mediaresourceId", mediaresourceId);
    json.put("type", type);
    json.put("objectId", objectId);

    //add object information
    JSONObject object = new JSONObject();
    object.put("objectId", objectId);

    //add entities array
    JSONArray entities = new JSONArray();

    for (Iterator<GAINObjectEntity> it = this.entities.iterator(); it.hasNext();) {
        GAINObjectEntity ent = it.next();

        JSONObject entity = new JSONObject();
        entity.put("source", ent.source);
        entity.put("lod", ent.lod);
        entity.put("type", ent.type);
        entity.put("label", ent.label);
        entity.put("typeLabel", ent.typeLabel);
        entity.put("entityType", ent.entityType);
        entity.put("confidence", ent.confidence);
        entity.put("relevance", ent.relevance);

        entities.add(entity);//from  w w w  .  ja v a2s . c o  m
    }

    object.put("entities", entities);
    json.put("object", object);

    JSONObject attributes = new JSONObject();
    attributes.put("category", category);
    attributes.put("action", action);

    //screen orientation specific
    if (category.equals("screen") && action.equals("orientation")) {
        attributes.put("orientation", orientation);
    }

    //player event specific
    if (category.equals("player")) {
        attributes.put("location", videoTime);
    }

    //user viewtime specific
    if (category.equals("user") && action.equals("viewtime")) {
        attributes.put("viewtime", viewtime);
    }

    JSONObject client = new JSONObject();
    client.put("type", CLIENT_TYPE);
    client.put("version", CLIENT_VERSION);

    attributes.put("client", client);
    json.put("attributes", attributes);

    String body = json.toString();

    sendRequest(body);
}