Java Code Examples for net.minidev.json.JSONObject#get()

The following examples show how to use net.minidev.json.JSONObject#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitHubConnector.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected SsoAuthenticated processTokenResponse(OIDCAccessTokenResponse tokenSuccessResponse) {
	BearerAccessToken accessToken = (BearerAccessToken) tokenSuccessResponse.getAccessToken();

	try {
		UserInfoRequest userInfoRequest = new UserInfoRequest(
				new URI(getCachedProviderMetadata().getUserInfoEndpoint()), accessToken);
		HTTPResponse httpResponse = userInfoRequest.toHTTPRequest().send();

		if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
			JSONObject json = httpResponse.getContentAsJSONObject();
			String userName = (String) json.get("login");
			String email = (String) json.get("email");
			if (StringUtils.isBlank(email))
				throw new AuthenticationException("A public email is required");
			String fullName = (String) json.get("name");
			
			return new SsoAuthenticated(userName, userName, email, fullName, null, null, this);
		} else {
			throw buildException(UserInfoErrorResponse.parse(httpResponse).getErrorObject());
		}
	} catch (SerializeException | ParseException | URISyntaxException | IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
Source File: ModelConverter.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Build nodes from a key.
 *
 * @param mo  the model to build
 * @param o   the object that contains the node
 * @param key the key associated to the nodes
 * @return the resulting set of nodes
 * @throws JSONConverterException if at least one of the parsed node already exists
 */
private static Set<Node> newNodes(Model mo, JSONObject o, String key) throws JSONConverterException {
    checkKeys(o, key);
    Object x = o.get(key);
    if (!(x instanceof JSONArray)) {
        throw new JSONConverterException("array expected at key '" + key + "'");
    }
    Set<Node> s = new HashSet<>(((JSONArray) x).size());
    for (Object i : (JSONArray) x) {
        int id = (Integer) i;
        Node n = mo.newNode(id);
        if (n == null) {
            throw JSONConverterException.nodeAlreadyDeclared(id);
        }
        s.add(n);
    }
    return s;
}
 
Example 3
Source File: StaticRoutingConverter.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public StaticRouting fromJSON(Model mo, JSONObject o) throws JSONConverterException {
    Network v = Network.get(mo);
    TIntObjectMap<Link> idToLink = new TIntObjectHashMap<>();
    for (Link l : v.getLinks()) {
        idToLink.put(l.id(), l);
    }
    StaticRouting r = new StaticRouting();
    checkKeys(o, ROUTES_LABEL);
    JSONArray a = (JSONArray) o.get(ROUTES_LABEL);
    for (Object ao : a) {
        StaticRouting.NodesMap nm = nodesMapFromJSON(mo, (JSONObject) ((JSONObject) ao).get("nodes_map"));
        Map<Link, Boolean> links = new LinkedHashMap<>();
        JSONArray aoa = (JSONArray) ((JSONObject) ao).get("links");
        for (Object aoao : aoa) {
            links.put(idToLink.get(requiredInt((JSONObject)aoao, "link")),
                    Boolean.valueOf(requiredString((JSONObject) aoao, "direction")));
        }
        r.setStaticRoute(nm, links);
    }
    return r;
}
 
Example 4
Source File: PicaReaderTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private Map<String, List<PicaTagDefinition>> readSchema(JSONParser parser, String fileName) throws IOException, URISyntaxException, ParseException {
  Map<String, List<PicaTagDefinition>> map = new HashMap<>();

  Path tagsFile = FileUtils.getPath(fileName);
  Object obj = parser.parse(new FileReader(tagsFile.toString()));
  JSONObject jsonObject = (JSONObject) obj;
  JSONObject fields = (JSONObject) jsonObject.get("fields");
  for (String name : fields.keySet()) {
    JSONObject field = (JSONObject) fields.get(name);
    // System.err.println(field);
    PicaTagDefinition tag = new PicaTagDefinition(
      (String) field.get("pica3"),
      name,
      (boolean) field.get("repeatable"),
      false,
      (String) field.get("label")
    );
    addTag(map, tag);
  }

  return map;
}
 
Example 5
Source File: MosaicIdSupplyPairTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void canSerializePair() {
	// Arrange:
	final MosaicIdSupplyPair pair = new MosaicIdSupplyPair(Utils.createMosaicId(5), Supply.fromValue(12345));

	// Act:
	final JSONObject jsonObject = JsonSerializer.serializeToJson(pair);

	// Assert:
	final JSONObject mosaicIdJsonObject = (JSONObject)jsonObject.get("mosaicId");
	Assert.assertThat(mosaicIdJsonObject.get("namespaceId"), IsEqual.equalTo("id5"));
	Assert.assertThat(mosaicIdJsonObject.get("name"), IsEqual.equalTo("name5"));
	Assert.assertThat(jsonObject.get("supply"), IsEqual.equalTo(12345L));
}
 
Example 6
Source File: EleCheck.java    From jelectrum with MIT License 5 votes vote down vote up
public static void checkBlockchainHeadersSubscribe(EleConn conn)
  throws Exception
{
  JSONArray params = new JSONArray();
  
  JSONObject msg = conn.request("blockchain.headers.subscribe");
  JSONObject result = (JSONObject) msg.get("result");

  int height = (int)result.get("height");
  String hex = (String)result.get("hex");

  Assert.assertEquals(160, hex.length());
}
 
Example 7
Source File: KeyValueDatabase.java    From QuickKV with Apache License 2.0 5 votes vote down vote up
public boolean sync(boolean merge) {
    try {
        if (!merge) {
            this.dMap.clear();
        }

        File kvdbFile = new File(pInstance.getStorageManager().getWorkspace(), dbAlias == null ? QKVConfig.KVDB_FILE_NAME : dbAlias);
        String rawData = kvdbFile.length() < 256 * 1000 ? MaglevReader.IO.fileToString(kvdbFile.getAbsolutePath()) : MaglevReader.NIO.MappedBFR.fileToString(kvdbFile.getAbsolutePath());
        if (rawData.length() > 0) {
            JSONObject treeRoot = (JSONObject) JSONValue.parse(rawData);
            JSONObject properties = (JSONObject) treeRoot.get(KVDBProperties.C_PROP);
            boolean gzip = (Boolean) properties.get(KVDBProperties.P_PROP_GZIP);
            if (gzip) {
                String rawDataBody = CompressHelper.decompress(
                        DataProcessor.Basic.hexToBytes((String) treeRoot.get(KVDBProperties.P_DATA))
                );
                if (parseKVJS((JSONObject) JSONValue.parse(rawDataBody))) return true;
                else return false;
            } else {
                if (parseKVJS((JSONObject) treeRoot.get(KVDBProperties.P_DATA))) return true;
                else return false;
            }
        }
        return true;

    } catch (Exception e) {
        QKVLogger.ex(e);
        return false;
    }
}
 
Example 8
Source File: KeyValueDatabase.java    From QuickKV with Apache License 2.0 5 votes vote down vote up
public boolean persist() {
    if (this.dMap.size() > 0) {
        try {
            JSONObject treeRoot = new JSONObject();
            treeRoot.put(KVDBProperties.C_PROP, new JSONObject());
            JSONObject propRoot = (JSONObject) treeRoot.get(KVDBProperties.C_PROP);
            propRoot.put(KVDBProperties.P_PROP_STRUCT_VER, QKVConfig.STRUCT_VER_STRING);
            propRoot.put(KVDBProperties.P_PROP_GZIP, isGZipEnabled);
            propRoot.put(KVDBProperties.P_PROP_ENCRYPTION, (this.pKey != null && this.pKey.length() > 0));
            treeRoot.put(KVDBProperties.P_DATA, new JSONObject());
            JSONObject dataRoot = (JSONObject) treeRoot.get(KVDBProperties.P_DATA);
            Iterator iter = this.dMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if (DataProcessor.Persistable.isValidDataType(key)
                        && DataProcessor.Persistable.isValidDataType(val)) {
                    if (this.pKey != null && this.pKey.length() > 0)
                        dataRoot.put(AES256.encode(this.pKey, DataProcessor.Persistable.addPrefix(key)), AES256.encode(this.pKey, DataProcessor.Persistable.addPrefix(val)));
                    else
                        dataRoot.put(DataProcessor.Persistable.addPrefix(key), DataProcessor.Persistable.addPrefix(val));
                }
            }
            if (isGZipEnabled) {
                String compressedData = DataProcessor.Basic.bytesToHex(CompressHelper.compress(dataRoot.toString().getBytes()));
                treeRoot.remove(KVDBProperties.P_DATA);
                treeRoot.put(KVDBProperties.P_DATA, compressedData);
            }
            String fName = dbAlias == null ? QKVConfig.KVDB_FILE_NAME : dbAlias;
            File fTarget = new File(pInstance.getStorageManager().getWorkspace(), fName);
            MaglevWriter.NIO.MappedBFR.writeBytesToFile(treeRoot.toString().getBytes(),
                    fTarget.getAbsolutePath());
            return true;
        } catch (Exception e) {
            QKVLogger.ex(e);
            return false;
        }
    } else return true;
}
 
Example 9
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read an expected integer.
 *
 * @param o  the object to parse
 * @param id the key in the map that points to an integer
 * @return the int
 * @throws JSONConverterException if the key does not point to a int
 */
public static int requiredInt(JSONObject o, String id) throws JSONConverterException {
    checkKeys(o, id);
    try {
        return (Integer) o.get(id);
    } catch (ClassCastException e) {
        throw new JSONConverterException("Unable to read a int from string '" + id + "'", e);
    }
}
 
Example 10
Source File: NamingServiceConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public NamingService<? extends Element> fromJSON(Model mo, JSONObject o) throws JSONConverterException {
    String id = requiredString(o, ModelViewConverter.IDENTIFIER);
    if (!id.equals(getJSONId())) {
        return null;
    }

    NamingService ns;
    String type = requiredString(o, "type");
    switch (type) {
        case VM.TYPE:
            ns = NamingService.newVMNS();
            break;
        case Node.TYPE:
            ns = NamingService.newNodeNS();
            break;
        default:
            throw new JSONConverterException("Unsupported type of element '" + type + "'");
    }

    checkKeys(o, "map");
    JSONObject map = (JSONObject) o.get("map");
    for (Map.Entry<String, Object> e : map.entrySet()) {
        String n = e.getKey();
        int v = Integer.parseInt(e.getValue().toString());
        Element el = VM.TYPE.equals(type) ? getVM(mo, v) : getNode(mo, v);
        if (!ns.register(el, n)) {
            throw new JSONConverterException("Duplicated name '" + n + "'");
        }
    }
    return ns;
}
 
Example 11
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static long getDate( JWSObject jwsObject )
{
    try
    {
        Payload payload = parseToken( jwsObject );
        JSONObject obj = payload.toJSONObject();
        return ( long ) obj.get( "exp" );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
        return 0;
    }
}
 
Example 12
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read partitions of VMs.
 *
 * @param mo the associated model to browse
 * @param o  the object to parse
 * @param id the key in the map that points to the partitions
 * @return the parsed partition
 * @throws JSONConverterException if the key does not point to partitions of VMs
 */
public static Set<Collection<VM>> requiredVMPart(Model mo, JSONObject o, String id) throws JSONConverterException {
    Set<Collection<VM>> vms = new HashSet<>();
    Object x = o.get(id);
    if (!(x instanceof JSONArray)) {
        throw new JSONConverterException("Set of identifiers sets expected at key '" + id + "'");
    }
    for (Object obj : (JSONArray) x) {
        vms.add(vmsFromJSON(mo, (JSONArray) obj));
    }
    return vms;
}
 
Example 13
Source File: TestUtf8.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testReader() throws Exception {
	for (String nonLatinText : nonLatinTexts) {
		String s = "{\"key\":\"" + nonLatinText + "\"}";
		StringReader reader = new StringReader(s);
		JSONObject obj = (JSONObject) JSONValue.parse(reader);

		String v = (String) obj.get("key"); // result is incorrect
		assertEquals(v, nonLatinText);
	}
}
 
Example 14
Source File: MCDownloadOnlineVersionList.java    From mclauncher-api with MIT License 5 votes vote down vote up
@Override
public LatestVersionInformation getLatestVersionInformation() throws Exception {
    String jsonString = HttpUtils.httpGet(JSONVERSION_LIST_URL);
    JSONObject versionInformation = (JSONObject) JSONValue.parse(jsonString);
    JSONObject latest = (JSONObject)versionInformation.get("latest");
    LatestVersionInformation result = new LatestVersionInformation(latest.get("release").toString(), latest.get("snapshot").toString());
    return result;
}
 
Example 15
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read an expected double.
 *
 * @param o  the object to parse
 * @param id the key in the map that points to the double
 * @return the double
 * @throws JSONConverterException if the key does not point to a double
 */
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException {
    checkKeys(o, id);
    Object x = o.get(id);
    if (!(x instanceof Number)) {
        throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'.");
    }
    return ((Number) x).doubleValue();
}
 
Example 16
Source File: Argument.java    From mclauncher-api with MIT License 5 votes vote down vote up
static Argument fromJson(JSONObject json) {
    RuleList rules = RuleList.fromJson((JSONArray) json.get("rules"));
    Object value = json.get("value");
    List<String> values = new ArrayList<>();
    if (value instanceof JSONArray) {
        JSONArray arr = (JSONArray) value;
        for (Object s : arr) {
            values.add(s.toString());
        }
    } else if(value instanceof String) {
        values.add(value.toString());
    }
    return new Argument(values, rules);
}
 
Example 17
Source File: OpenIdConnector.java    From onedev with MIT License 4 votes vote down vote up
@Override
public SsoAuthenticated processLoginResponse() {
	HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
	try {
		AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(
				new URI(request.getRequestURI() + "?" + request.getQueryString()));
		if (authenticationResponse instanceof AuthenticationErrorResponse) {
			throw buildException(((AuthenticationErrorResponse)authenticationResponse).getErrorObject()); 
		} else {
			AuthenticationSuccessResponse authenticationSuccessResponse = 
					(AuthenticationSuccessResponse)authenticationResponse;
			
			String state = (String) Session.get().getAttribute(SESSION_ATTR_STATE);
			
			if (state == null || !state.equals(authenticationSuccessResponse.getState().getValue()))
				throw new AuthenticationException("Unsolicited OIDC authentication response");
			
			AuthorizationGrant codeGrant = new AuthorizationCodeGrant(
					authenticationSuccessResponse.getAuthorizationCode(), getCallbackUri());

			ClientID clientID = new ClientID(getClientId());
			Secret clientSecret = new Secret(getClientSecret());
			ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
			TokenRequest tokenRequest = new TokenRequest(
					new URI(getCachedProviderMetadata().getTokenEndpoint()), clientAuth, codeGrant);
			HTTPResponse httpResponse = tokenRequest.toHTTPRequest().send();
			if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
				JSONObject jsonObject = httpResponse.getContentAsJSONObject();
				if (jsonObject.get("error") != null) 
					throw buildException(TokenErrorResponse.parse(jsonObject).getErrorObject());
				else 
					return processTokenResponse(OIDCAccessTokenResponse.parse(jsonObject));
			} else {
				ErrorObject error = TokenErrorResponse.parse(httpResponse).getErrorObject();
				if (error != null) {
					throw buildException(error);
				} else {
					String message = String.format("Error requesting OIDC token: http status: %d", 
							httpResponse.getStatusCode());
					throw new AuthenticationException(message);
				}
			}
		}
	} catch (ParseException | URISyntaxException|SerializeException|IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 18
Source File: EleCheck.java    From jelectrum with MIT License 3 votes vote down vote up
public static void checkBlockHeaderCheckPoint(EleConn conn)
  throws Exception
{
  
  //int blk_n = 109;
  //int cp = 32911;
  Random rnd = new Random();

  for(int i=0; i<20; i++)
  {
    JSONArray params = new JSONArray();
    int cp = rnd.nextInt(630000)+10;
    int blk_n = rnd.nextInt(cp);
    //cp = 5;
    //blk_n = 2;

    params.add(blk_n);
    params.add(cp);

    JSONObject msg = conn.request("blockchain.block.header", params);
    JSONObject result = (JSONObject) msg.get("result");

    String header = (String) result.get("header");
    
    if (header.length() != 160) throw new Exception("Header not 160 chars"); 
    JSONArray branch = (JSONArray) result.get("branch");

    String header_hex = (String) result.get("header");

    
    String root = (String) result.get("root");
    validateMerkle(HexUtil.hexStringToBytes(header_hex), branch, blk_n, cp, root);

  }
  

  
}
 
Example 19
Source File: EleCheck.java    From jelectrum with MIT License 3 votes vote down vote up
public static void checkBlockHeader(EleConn conn)
  throws Exception
{
  JSONArray params = new JSONArray();
  
  params.add(100000);

  JSONObject msg = conn.request("blockchain.block.header", params);
  String header = (String) msg.get("result");

  if (header.length() != 160) throw new Exception("Header not 160 chars"); 

  
  
}
 
Example 20
Source File: ConstraintConverter.java    From scheduler with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Check if the JSON object can be converted using this converter.
 * For being convertible, the key 'id' must be equals to {@link #getJSONId()}.
 *
 * @param o the object to test
 * @throws JSONConverterException if the object is not compatible
 */
default void checkId(JSONObject o) throws JSONConverterException {
  Object id = o.get(ConstraintConverter.IDENTIFIER);
    if (id == null || !id.toString().equals(getJSONId())) {
        throw new JSONConverterException("Incorrect converter for " + o.toJSONString() + ". Expecting a constraint id '" + id + "'");
    }
}