下面列出了org.json.simple.parser.ContainerFactory#org.json.simple.JSONValue 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String resolveUsername(UUID id) {
final String url = "https://api.mojang.com/user/profiles/" + id.toString().replace("-", "") + "/names";
try {
final String nameJson = IOUtils.toString(new URL(url));
if (nameJson != null && nameJson.length() > 0) {
final JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(nameJson);
if (jsonArray != null) {
final JSONObject latestName = (JSONObject) jsonArray.get(jsonArray.size() - 1);
if (latestName != null) {
return latestName.get("name").toString();
}
}
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
public static void parseNdJsonIntoValue( BufferedReader reader, Value value, boolean strictEncoding )
throws IOException {
List< String > stringItemVector = reader.lines().collect( Collectors.toList() );
for( String stringItem : stringItemVector ) {
StringReader itemReader = new StringReader( stringItem );
try {
Value itemValue = Value.create();
Object obj = JSONValue.parseWithException( itemReader );
if( obj instanceof JSONArray ) {
itemValue.children().put( JSONARRAY_KEY,
jsonArrayToValueVector( (JSONArray) obj, strictEncoding ) );
} else if( obj instanceof JSONObject ) {
jsonObjectToValue( (JSONObject) obj, itemValue, strictEncoding );
} else {
objectToBasicValue( obj, itemValue );
}
value.getChildren( "item" ).add( itemValue );
} catch( ParseException | ClassCastException e ) {
throw new IOException( e );
}
}
}
public static Object getMessagesFromResponse(String responseStr, String node) {
Object msgObject = null;
if (responseStr == null || responseStr.equalsIgnoreCase(""))
return msgObject;
try {
JSONObject responseObj = (JSONObject) JSONValue
.parseWithException(responseStr);
if (responseObj != null) {
JSONObject dataObj = (JSONObject) responseObj
.get(ConstantsForTest.DATA);
if (dataObj != null) {
msgObject = dataObj.get(node);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgObject;
}
void storeHeaderValue(String inputKey, String inputValue, Map<String, Object> content) {
String key = sanitize(inputKey);
String value = sanitize(inputValue);
if (key.equalsIgnoreCase(Crawler.Attributes.DATE)) {
DateFormat df = new SimpleDateFormat(configuration.getDateFormat());
try {
Date date = df.parse(value);
content.put(key, date);
} catch (ParseException e) {
LOGGER.error("unable to parse date {}", value);
}
} else if (key.equalsIgnoreCase(Crawler.Attributes.TAGS)) {
content.put(key, getTags(value));
} else if (isJson(value)) {
content.put(key, JSONValue.parse(value));
} else {
content.put(key, value);
}
}
/** Records information about the current flow execution in the GAE request logs. */
public void recordToLogs() {
// Explicitly log flow metadata separately from the EPP XML itself so that it stays compact
// enough to be sure to fit in a single log entry (the XML part in rare cases could be long
// enough to overflow into multiple log entries, breaking routine parsing of the JSON format).
String singleTargetId = eppInput.getSingleTargetId().orElse("");
ImmutableList<String> targetIds = eppInput.getTargetIds();
logger.atInfo().log(
"%s: %s",
METADATA_LOG_SIGNATURE,
JSONValue.toJSONString(
new ImmutableMap.Builder<String, Object>()
.put("serverTrid", trid.getServerTransactionId())
.put("clientId", clientId)
.put("commandType", eppInput.getCommandType())
.put("resourceType", eppInput.getResourceType().orElse(""))
.put("flowClassName", flowClass.getSimpleName())
.put("targetId", singleTargetId)
.put("targetIds", targetIds)
.put("tld", eppInput.isDomainType() ? extractTld(singleTargetId).orElse("") : "")
.put("tlds", eppInput.isDomainType() ? extractTlds(targetIds).asList() : EMPTY_LIST)
.put("icannActivityReportField", extractActivityReportField(flowClass))
.build()));
}
public String getResourceMap(){
Map verbs = new LinkedHashMap();
int i = 0;
for (String method : httpVerbs) {
Map verb = new LinkedHashMap();
verb.put("auth_type",authTypes.get(i));
verb.put("throttling_tier",throttlingTiers.get(i));
//Following parameter is not required as it not need to reflect UI level. If need please enable it.
// /verb.put("throttling_conditions", throttlingConditions.get(i));
try{
Scope tmpScope = scopes.get(i);
if(tmpScope != null){
verb.put("scope",tmpScope.getKey());
}
}catch(IndexOutOfBoundsException e){
//todo need to rewrite to prevent this type of exceptions
}
verbs.put(method,verb);
i++;
}
//todo this is a hack to make key validation service stub from braking need to rewrite.
return JSONValue.toJSONString(verbs);
}
/**
* Parse JSON response.
* <p/>
* @param in {@link InputStream} to read.
* @return Response returned by REST administration service.
*/
@Override
public RestActionReport parse(InputStream in) {
RestActionReport report = new RestActionReport();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
copy(in, out);
String respMsg = out.toString("UTF-8");
JSONObject json = (JSONObject)JSONValue.parseWithException(respMsg);
parseReport(report, json);
} catch (IOException ex) {
throw new PayaraIdeException("Unable to copy JSON response.", ex);
} catch (ParseException e) {
throw new PayaraIdeException("Unable to parse JSON response.", e);
}
return report;
}
/**
* Parse JSON response.
* <p/>
* @param in {@link InputStream} to read.
* @return Response returned by REST administration service.
*/
@Override
public RestActionReport parse(InputStream in) {
RestActionReport report = new RestActionReport();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
copy(in, out);
String respMsg = out.toString("UTF-8");
JSONObject json = (JSONObject)JSONValue.parseWithException(respMsg);
parseReport(report, json);
} catch (IOException ex) {
throw new GlassFishIdeException("Unable to copy JSON response.", ex);
} catch (ParseException e) {
throw new GlassFishIdeException("Unable to parse JSON response.", e);
}
return report;
}
private JSONObject extractResponse(NSObject r) throws Exception {
if (r == null) {
return null;
}
if (!(r instanceof NSDictionary)) {
return null;
}
NSDictionary root = (NSDictionary) r;
NSDictionary argument = (NSDictionary) root.objectForKey("__argument"); // NOI18N
if (argument == null) {
return null;
}
NSData data = (NSData) argument.objectForKey("WIRMessageDataKey"); // NOI18N
if (data == null) {
return null;
}
byte[] bytes = data.bytes();
String s = new String(bytes);
JSONObject o = (JSONObject) JSONValue.parseWithException(s);
return o;
}
/**
* Function to query the TV Volume
*
* @param host
* @return struct containing all given information about current volume
* settings (volume, mute, min, max) @see volumeConfig
*/
private volumeConfig getTVVolume(String host) {
volumeConfig conf = new volumeConfig();
String url = "http://" + host + "/1/audio/volume";
String volume_json = HttpUtil.executeUrl("GET", url, IOUtils.toInputStream(""), CONTENT_TYPE_JSON, 1000);
if (volume_json != null) {
try {
Object obj = JSONValue.parse(volume_json);
JSONObject array = (JSONObject) obj;
conf.mute = Boolean.parseBoolean(array.get("muted").toString());
conf.volume = Integer.parseInt(array.get("current").toString());
conf.min = Integer.parseInt(array.get("min").toString());
conf.max = Integer.parseInt(array.get("max").toString());
} catch (NumberFormatException ex) {
logger.warn("Exception while interpreting volume json return");
} catch (Throwable t) {
logger.warn("Could not parse JSON String for volume value. Error: {}", t.toString());
}
}
return conf;
}
@SuppressWarnings("rawtypes")
private void createHar(String pt, String rt) {
Har<String, Log> har = new Har<>();
Page p = new Page(pt, har.pages());
har.addPage(p);
for (Object res : (JSONArray) JSONValue.parse(rt)) {
JSONObject jse = (JSONObject) res;
if (jse.size() > 14) {
Entry e = new Entry(jse.toJSONString(), p);
har.addEntry(e);
}
}
har.addRaw(pt, rt);
Control.ReportManager.addHar(har, (TestCaseReport) Report,
escapeName(Data));
}
private ViewSettings(String json) {
Object obj = JSONValue.parse(json);
Color color;
String imagePath;
try {
Map<?, ?> map = (Map) obj;
color = map.containsKey(JSON_BG_COLOR) ?
new Color(((Long) map.get(JSON_BG_COLOR)).intValue()) :
null;
imagePath = map.containsKey(JSON_IMAGE_PATH) ?
(String) map.get(JSON_IMAGE_PATH) :
"";
} catch (NullPointerException | ClassCastException ex) {
LOGGER.log(Level.WARNING, "can't parse JSON view settings", ex);
color = null;
imagePath = "";
}
mColor = color;
mImagePath = imagePath;
}
@SuppressWarnings("unchecked")
public JSONArray executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
ParseException
{
JSONArray jsonUsers = (JSONArray) JSONValue.parseWithException(req.getContent().getContent());
JSONArray result = new JSONArray();
for (Object o : jsonUsers)
{
String user = (o == null ? null : o.toString());
if (user != null)
{
JSONObject item = new JSONObject();
item.put(user, subscriptionService.follows(userId, user));
result.add(item);
}
}
return result;
}
private Set<String> fetchUserOrganizations() {
String response = organizationSupplier.get();
log.debug("Fetched user org data: " + response);
Object parsedResponse = JSONValue.parse(response);
if (parsedResponse instanceof JSONArray) {
return ((List<Object>) parsedResponse)
.stream()
.filter(item -> item instanceof JSONObject)
.map(item -> ((JSONObject) item).get("login"))
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toSet());
} else {
String message = ((JSONObject) parsedResponse).getOrDefault("message", "Incorrect response:" + response ).toString();
throw new IllegalStateException(message);
}
}
/**
* decodes JSON formatted text into a map.
*
* @return Map parsed from a JSON formatted string
* <p>
* If the json text is not a map, a map with the key "value" will be returned.
* the value of "value" will either be an List, String, Number, Boolean, or null
* <p>
* if the String is formatted badly, null is returned
*/
public static Map decodeJSON(String json) {
try {
Object object = JSONValue.parse(json);
if (object instanceof Map) {
return (Map) object;
}
// could be : ArrayList, String, Number, Boolean
Map map = new HashMap();
map.put("value", object);
return map;
} catch (Throwable t) {
Debug.out("Warning: Bad JSON String: " + json, t);
return null;
}
}
public Map<String, String> parseDatacenters() {
HashMap<String, String> dcNameType = new HashMap<String, String>();
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(this.filename));
JSONArray datacenters = (JSONArray) doc.get("datacenters");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter = datacenters.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String dcName = (String) node.get("name");
String type = (String) node.get("type");
dcNameType.put(dcName, type);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return dcNameType;
}
private void waitApiRate() {
String url = "https://api.github.com/rate_limit" + authString;
boolean sleep = true;
logger.info("API rate limit exceeded. Waiting to restart the importing...");
while (sleep) {
try {
InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject obj = (JSONObject) JSONValue.parse(jsonText);
JSONObject rate = (JSONObject) ((JSONObject) obj.get("rate"));
Integer remaining = new Integer(rate.get("remaining").toString());
if (remaining > 0) {
sleep = false;
}
} catch (IOException e) {
logger.error("Having difficulties to connect, retrying...");
continue;
}
}
}
public static Map readCommandLineOpts() {
Map ret = new HashMap();
String commandOptions = System.getProperty("leaf.options");
if (commandOptions != null) {
String[] configs = commandOptions.split(",");
for (String config : configs) {
config = URLDecoder.decode(config);
String[] options = config.split("=", 2);
if (options.length == 2) {
Object val = JSONValue.parse(options[1]);
if (val == null) {
val = options[1];
}
ret.put(options[0], val);
}
}
}
return ret;
}
public UltimateFancy appendString(String jsonObject) {
Object obj = JSONValue.parse(jsonObject);
if (obj instanceof JSONObject) {
workingGroup.add((JSONObject) obj);
}
if (obj instanceof JSONArray) {
for (Object object : ((JSONArray) obj)) {
if (object.toString().isEmpty()) continue;
if (object instanceof JSONArray) {
appendString(object.toString());
} else {
workingGroup.add((JSONObject) JSONValue.parse(object.toString()));
}
}
}
return this;
}
/**
* Utility method to extract the version from a NPM by reading its 'package.json' file.
*
* @param npmDirectory the directory in which the NPM is installed
* @param log the logger object
* @return the read version, "0.0.0" if there are not 'package.json' file, {@code null} if this file cannot be
* read or does not contain the "version" metadata
*/
public static String getVersionFromNPM(File npmDirectory, Log log) {
File packageFile = new File(npmDirectory, PACKAGE_JSON);
if (!packageFile.isFile()) {
return "0.0.0";
}
FileReader reader = null;
try {
reader = new FileReader(packageFile); //NOSONAR
JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
return (String) json.get("version");
} catch (IOException | ParseException e) {
log.error("Cannot extract version from " + packageFile.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(reader);
}
return null;
}
public void writeObject(Object obj) throws IOException {
if ((obj instanceof JSONObject)) {
JSONObject jObj = (JSONObject) obj;
writeJsonObject(jObj);
return;
}
if ((obj instanceof JSONArray)) {
JSONArray jArr = (JSONArray) obj;
writeJsonArray(jArr);
return;
}
this.writer.write(JSONValue.toJSONString(obj));
}
private void writeJsonObject(JSONObject jObj) throws IOException {
writeLine("{");
indentAdd();
Set keys = jObj.keySet();
int keyNum = keys.size();
int count = 0;
for (Iterator it = keys.iterator(); it.hasNext(); ) {
String key = (String) it.next();
Object val = jObj.get(key);
writeIndent();
this.writer.write(JSONValue.toJSONString(key));
this.writer.write(": ");
writeObject(val);
count++;
if (count < keyNum) {
writeLine(",");
} else {
writeLine("");
}
}
indentRemove();
writeIndent();
this.writer.write("}");
}
public static JSONObject jsonJwtHeader(String id_token) {
String headerStr = rawJwtHeader(id_token);
if ( headerStr == null ) return null;
Object headerObj = JSONValue.parse(headerStr);
if ( headerObj == null ) return null;
if ( ! ( headerObj instanceof JSONObject) ) return null;
return (JSONObject) headerObj;
}
private void writeJsonObject(JSONObject jObj) throws IOException {
writeLine("{");
indentAdd();
Set keys = jObj.keySet();
int keyNum = keys.size();
int count = 0;
for (Iterator it = keys.iterator(); it.hasNext(); ) {
String key = (String) it.next();
Object val = jObj.get(key);
writeIndent();
this.writer.write(JSONValue.toJSONString(key));
this.writer.write(": ");
writeObject(val);
count++;
if (count < keyNum) {
writeLine(",");
} else {
writeLine("");
}
}
indentRemove();
writeIndent();
this.writer.write("}");
}
private String extractServerResponse(String response) {
Map<String, Object> responseMap = toMap(JSONValue.parse(stripJsonPrefix(response)));
// TODO(user): consider using jart's FormField Framework.
// See: j/c/g/d/r/ui/server/RegistrarFormFields.java
String status = (String) responseMap.get("status");
Verify.verify(!status.equals("error"), "Server error: %s", responseMap.get("error"));
return String.format("Successfully saved premium list %s\n", name);
}
/**
* Provide the external jars that the IDF depends on
* @return set of jars
*/
public Set<String> getJars() {
Set<String> jars = new HashSet<String>();
// Add JODA classes for IDF date/time handling
jars.add(ClassUtils.jarForClass(LocalDate.class));
jars.add(ClassUtils.jarForClass(LocalDateTime.class));
jars.add(ClassUtils.jarForClass(DateTime.class));
jars.add(ClassUtils.jarForClass(LocalTime.class));
// Add JSON parsing jar
jars.add(ClassUtils.jarForClass(JSONValue.class));
return jars;
}
/**
*
* @param destination A valid JCo Destination
* @return json Representation of the JCo Function call
* @throws JCoException
*/
public String execute(JCoDestination destination) throws JCoException
{
LinkedHashMap resultList = new LinkedHashMap();
try
{
function.execute(destination);
}
catch(AbapException e)
{
resultList.put(e.getKey(),e);
}
catch (JCoException ex)
{
resultList.put(ex.getKey(),ex);
}
//Export Parameters
if(function.getExportParameterList()!= null)
{
getFields(function.getExportParameterList().getFieldIterator(),resultList);
}
//Changing parameters
if(function.getChangingParameterList()!= null)
{
getFields(function.getChangingParameterList().getFieldIterator(),resultList);
}
//Table Parameters
if(function.getTableParameterList()!= null)
{
getFields(function.getTableParameterList().getFieldIterator(),resultList);
}
return JSONValue.toJSONString(resultList);
}
public String toString(){
Map<Object, Object> jsonData = new LinkedHashMap<>();
jsonData.put("op", OpCode.code(op).name());
jsonData.put("pc", Long.toString(pc));
jsonData.put("gas", gas.value().toString());
jsonData.put("stack", stack);
jsonData.put("memory", memory == null ? "" : Hex.toHexString(memory));
jsonData.put("storage", new JSONObject(storage) );
return JSONValue.toJSONString(jsonData);
}
static ServerError fromJSON(String jsonContent) {
Object obj = JSONValue.parse(jsonContent);
Map<?, ?> map = (Map) obj;
if (map == null) return new ServerError();
String condition = EncodingUtils.getJSONString(map, JSON_COND);
String text = EncodingUtils.getJSONString(map, JSON_TEXT);
return new ServerError(condition, text);
}
private static void filterJson(FileObject fo, String name) throws IOException {
Path path = FileUtil.toFile(fo).toPath();
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replace("${project.name}", JSONValue.escape(name)); // NOI18N
Files.write(path, content.getBytes(charset));
}