Example usage for org.json.simple JSONObject putAll

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

Introduction

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

Prototype

void putAll(Map<? extends K, ? extends V> m);

Source Link

Document

Copies all of the mappings from the specified map to this map (optional operation).

Usage

From source file:org.basket3.filesystem.dao.GAEBucketDao.java

private void toJSONStringPrint(DBObject obj) {
    JSONObject json = new JSONObject();
    json.putAll(obj.toMap());
    logger.info(json.toJSONString());//from  w  ww. j ava2  s  .c  o m
}

From source file:org.imsglobal.lti2.LTI2Util.java

@SuppressWarnings({ "unchecked", "unused" })
public static Object getSettings(HttpServletRequest request, String scope, JSONObject link_settings,
        JSONObject binding_settings, JSONObject proxy_settings, String link_url, String binding_url,
        String proxy_url) {//from   ww w  .j  av a 2  s  .c  om
    // Check to see if we are doing the bubble
    String bubbleStr = request.getParameter("bubble");
    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();

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

    if (SCOPE_LtiLink.equals(scope) || SCOPE_ToolProxyBinding.equals(scope) || SCOPE_ToolProxy.equals(scope)) {
        // All good
    } else {
        return "Bad Setttings Scope=" + scope;
    }

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

    // Check our output format
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    if (distinct && link_settings != null && scope.equals(SCOPE_LtiLink)) {
        Iterator<String> 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(SCOPE_ToolProxyBinding)) {
        Iterator<String> i = binding_settings.keySet().iterator();
        while (i.hasNext()) {
            String key = (String) i.next();
            if (proxy_settings != null)
                proxy_settings.remove(key);
        }
    }

    // Lets get this party started...
    JSONObject jsonResponse = null;
    if ((distinct || bubbleAll) && acceptComplex) {
        jsonResponse = new JSONObject();
        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLSETTINGS_CONTEXT);
        JSONArray graph = new JSONArray();
        boolean started = false;
        if (link_settings != null && SCOPE_LtiLink.equals(scope)) {
            JSONObject cjson = new JSONObject();
            cjson.put(LTI2Constants.JSONLD_ID, link_url);
            cjson.put(LTI2Constants.TYPE, SCOPE_LtiLink);
            cjson.put(LTI2Constants.CUSTOM, link_settings);
            graph.add(cjson);
            started = true;
        }
        if (binding_settings != null && (started || SCOPE_ToolProxyBinding.equals(scope))) {
            JSONObject cjson = new JSONObject();
            cjson.put(LTI2Constants.JSONLD_ID, binding_url);
            cjson.put(LTI2Constants.TYPE, SCOPE_ToolProxyBinding);
            cjson.put(LTI2Constants.CUSTOM, binding_settings);
            graph.add(cjson);
            started = true;
        }
        if (proxy_settings != null && (started || SCOPE_ToolProxy.equals(scope))) {
            JSONObject cjson = new JSONObject();
            cjson.put(LTI2Constants.JSONLD_ID, proxy_url);
            cjson.put(LTI2Constants.TYPE, SCOPE_ToolProxy);
            cjson.put(LTI2Constants.CUSTOM, proxy_settings);
            graph.add(cjson);
        }
        jsonResponse.put(LTI2Constants.GRAPH, graph);

    } else if (distinct) { // Simple format output
        jsonResponse = proxy_settings;
        if (SCOPE_LtiLink.equals(scope)) {
            jsonResponse.putAll(binding_settings);
            jsonResponse.putAll(link_settings);
        } else if (SCOPE_ToolProxyBinding.equals(scope)) {
            jsonResponse.putAll(binding_settings);
        }
    } else { // bubble not specified
        jsonResponse = new JSONObject();
        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLSETTINGS_CONTEXT);
        JSONObject theSettings = null;
        String endpoint = null;
        if (SCOPE_LtiLink.equals(scope)) {
            endpoint = link_url;
            theSettings = link_settings;
        } else if (SCOPE_ToolProxyBinding.equals(scope)) {
            endpoint = binding_url;
            theSettings = binding_settings;
        }
        if (SCOPE_ToolProxy.equals(scope)) {
            endpoint = proxy_url;
            theSettings = proxy_settings;
        }
        if (acceptComplex) {
            JSONArray graph = new JSONArray();
            JSONObject cjson = new JSONObject();
            cjson.put(LTI2Constants.JSONLD_ID, endpoint);
            cjson.put(LTI2Constants.TYPE, scope);
            cjson.put(LTI2Constants.CUSTOM, theSettings);
            graph.add(cjson);
            jsonResponse.put(LTI2Constants.GRAPH, graph);
        } else {
            jsonResponse = theSettings;
        }
    }
    return jsonResponse;
}

From source file:org.springframework.ide.eclipse.internal.uaa.UaaManager.java

@SuppressWarnings("unchecked")
private byte[] mergeData(byte[] existingData, byte[] data) {
    // Quick sanity check to prevent doing too much in case no new data has been presented
    if (data == null || data.length == 0) {
        return existingData;
    }/*  w  ww.j a va 2 s.  co m*/

    // Load existing feature data
    JSONObject existingFeatureData = new JSONObject();
    if (existingData != null && existingData.length > 0) {
        Object existingJson = JSONValue.parse(new String(existingData));
        if (existingJson instanceof JSONObject) {
            existingFeatureData.putAll(((JSONObject) existingJson));
        }
    }

    // Load new data into JSON object
    Map<String, String> featureData = new JSONObject();
    if (data != null && data.length > 0) {
        Object json = JSONValue.parse(new String(data));
        if (json instanceof JSONObject) {
            featureData.putAll((JSONObject) json);
        }
    }

    // Merge feature data: merge those values whose keys already exist
    featureData = new HashMap<String, String>(featureData);
    for (Map.Entry<String, Object> existingEntry : new HashMap<String, Object>(existingFeatureData)
            .entrySet()) {
        if (featureData.containsKey(existingEntry.getKey())) {
            String newValue = featureData.get(existingEntry.getKey());
            Object existingValue = existingEntry.getValue();
            if (!newValue.equals(existingValue)) {
                if (existingValue instanceof List) {
                    List<String> existingValues = (List<String>) existingValue;
                    if (!existingValues.contains(newValue)) {
                        existingValues.add(newValue);
                    }
                } else {
                    List<String> value = new ArrayList<String>();
                    value.add((String) existingValue);
                    value.add(featureData.get(existingEntry.getKey()));
                    existingFeatureData.put(existingEntry.getKey(), value);
                }
            }
            featureData.remove(existingEntry.getKey());
        }
    }

    // Merge the remaining new values
    existingFeatureData.putAll(featureData);

    try {
        return existingFeatureData.toJSONString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

From source file:org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil.java

/**
 * used to convert yaml to json// w  w w . j a  v  a  2 s  .co  m
 *
 * @param yamlString yaml String
 * @return  Json string
 */
public static String convertYmlToJson(String yamlString) {
    Yaml yaml = new Yaml();
    Map map = (Map) yaml.load(yamlString);
    JSONObject jsonObject = new JSONObject();
    jsonObject.putAll(map);
    return jsonObject.toJSONString();
}

From source file:org.wso2.carbon.apimgt.sciquest.keymanager.APIManagerOAuthClient.java

/**
 * This method validates the access token with external OAuth Server
 *
 * @param accessToken - the token which need to be validated
 * @return an {@code AccessTokenInfo} having token validation meta data
 * @throws APIManagementException/*from  w  w w.  ja v a 2 s  . co  m*/
 */

public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken(accessToken);

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(ClientConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(ClientConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(ClientConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("HTTP Response code for Token Validation from external OAuth Server: " + responseCode);
        }

        // Response Format from OAuth 2 Server

        /*{
        "audience":"MappedClient",
            "scopes":[
                "test"
            ],
            "principal":{
                "name":"mappedclient",
                "roles":[
                
                ],
                "groups":[
                
                ],
                "adminPrincipal":false,
                "attributes":{
                
                }
            },
            "expires_in":1433059160531
        }*/

        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            //pass bufferReader object  and get read it and retrieve  the parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {
                Object principal = parsedObject.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) parsedObject.get("expires_in");

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    JSONArray scopesArray = (JSONArray) parsedObject.get("scopes");

                    if (log.isDebugEnabled()) {
                        StringBuilder tokens = new StringBuilder("[");
                        Iterator iterator = scopesArray.iterator();
                        while (iterator.hasNext()) {
                            tokens.append(iterator.next());
                            if (iterator.hasNext()) {
                                tokens.append(", ");
                            }
                        }
                        tokens.append("]");

                        log.debug("Tokens " + tokens);
                    }

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }

                    JSONObject jso = new JSONObject();
                    jso.putAll(principalMap);
                    tokenInfo.setEndUserName(jso.toString());

                    if (log.isDebugEnabled()) {
                        log.debug("Token Response Principle : " + jso.toJSONString());
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

            } else {
                log.error("Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } //for other HTTP error codes we just pass generic message.
        else {
            log.error("Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return tokenInfo;
}

From source file:press.gfw.Config.java

/**
 * ??/*from w  ww  .ja v a  2s . c  om*/
 *
 * @param json
 * @return
 */
@SuppressWarnings("unchecked")
public boolean saveClientConfig(JSONObject json) {

    if (json == null) {

        return false;

    }

    JSONObject _json = getClientConfig();

    if (_json == null) {

        _json = json;

    } else {

        _json.putAll(json);

    }

    return save(clientFile, _json.toJSONString());

}

From source file:press.gfw.Config.java

/**
 * ???/*from  w w  w .j  av a 2  s.  c om*/
 *
 * @param json
 * @return
 */
@SuppressWarnings("unchecked")
public boolean saveServerConfig(JSONObject json) {

    if (json == null) {

        return false;

    }

    JSONObject _json = getServerConfig();

    if (_json == null) {

        _json = json;

    } else {

        _json.putAll(json);

    }

    return save(serverFile, _json.toJSONString());

}

From source file:services.Adapter.java

@GET
@Path("/userProfile")
@Consumes("text/plain")
@Produces("application/json")
public Response roleGeral(@QueryParam("useragent") String useragent, @QueryParam("upref") String upref) {
    useragent = useragent.replaceAll(" ", "%20");
    Capabilities cap;//from  www. ja  v a  2  s . c o m
    JSONObject saida = new JSONObject();
    JSONObject virtual = new JSONObject();
    JSONObject entrada;
    JSONObject virtualAux;
    JSONParser parser = new JSONParser();
    try {
        cap = new DevicesSO();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        cap = new Browser();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        cap = new Display();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        saida.put("virtual", virtual);

        // Alterar capacidades virtuais incluindo o perfil do usurio
        UserProfile user = new Multimodality();
        virtualAux = (JSONObject) parser.parse(user.userPreference(saida.toJSONString(), upref));
        saida.put("virtual", virtualAux);

        System.out.println(saida.toJSONString());
        return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(saida.toJSONString())
                .build();
    } catch (Exception ex) {
        Logger.getLogger(Adapter.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:services.Adapter.java

@GET
@Path("/capabilities")
@Consumes("text/plain")
@Produces("application/json")
public Response roleGeral(@QueryParam("useragent") String useragent) {
    useragent = useragent.replaceAll(" ", "%20");
    Capabilities cap;/*  www.  j  a v a 2s  .c  o m*/
    JSONObject saida = new JSONObject();
    JSONObject virtual = new JSONObject();
    JSONObject entrada;
    JSONObject virtualAux;
    JSONParser parser = new JSONParser();
    try {
        cap = new DevicesSO();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        cap = new Browser();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        cap = new Display();
        entrada = (JSONObject) parser.parse(cap.adaptRole(cap.dbSearch(useragent)));
        virtualAux = (JSONObject) entrada.remove("virtual");
        virtual.putAll(virtualAux);
        saida.putAll(entrada);

        saida.put("virtual", virtual);

        return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(saida.toJSONString())
                .build();
    } catch (Exception ex) {
        Logger.getLogger(Adapter.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:services.Adapter.java

@GET
@Path("/consultdb")
@Consumes("text/plain")
@Produces("application/json")
public Response consultaGeral(@QueryParam("useragent") String useragent) {
    useragent = useragent.replaceAll(" ", "%20");
    Capabilities cap;//w  w  w .ja  v a 2 s .  co m
    JSONObject saida = new JSONObject();
    JSONObject entrada;
    JSONParser parser = new JSONParser();
    try {
        cap = new DevicesSO();
        entrada = (JSONObject) parser.parse(cap.dbSearch(useragent));
        saida.putAll(entrada);

        cap = new Browser();
        entrada = (JSONObject) parser.parse(cap.dbSearch(useragent));
        saida.putAll(entrada);

        cap = new Display();
        entrada = (JSONObject) parser.parse(cap.dbSearch(useragent));
        saida.putAll(entrada);

        return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(saida.toJSONString())
                .build();
    } catch (Exception ex) {
        Logger.getLogger(Adapter.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}