Java Code Examples for org.json.simple.JSONValue

The following examples show how to use org.json.simple.JSONValue. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: seppuku   Source File: NetworkUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 2
Source Project: jolie   Source File: JsUtils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 );
		}

	}

}
 
Example 3
Source Project: singleton   Source File: ResponseUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: jbake   Source File: MarkupEngine.java    License: MIT License 6 votes vote down vote up
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);
    }
}
 
Example 5
Source Project: nomulus   Source File: FlowReporter.java    License: Apache License 2.0 6 votes vote down vote up
/** 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()));
}
 
Example 6
Source Project: carbon-apimgt   Source File: URITemplate.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 7
Source Project: netbeans   Source File: RestJSONResponseParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source Project: netbeans   Source File: RestJSONResponseParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source Project: netbeans   Source File: IOSDebugTransport.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 10
Source Project: openhab1-addons   Source File: JointSpaceBinding.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
@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));
}
 
Example 12
Source Project: desktopclient-java   Source File: Chat.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 13
@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;
}
 
Example 14
Source Project: teamcity-oauth   Source File: GithubUser.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 15
Source Project: BiglyBT   Source File: JSONUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 16
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;		
}
 
Example 17
Source Project: scava   Source File: GitHubImporter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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;
			}
		}
	}
 
Example 18
Source Project: leaf-snowflake   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 19
Source Project: UltimateChat   Source File: UltimateFancy.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 20
Source Project: wisdom   Source File: NPM.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Source Project: The-5zig-Mod   Source File: JSONWriter.java    License: GNU General Public License v3.0 5 votes vote down vote up
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));
}
 
Example 22
Source Project: The-5zig-Mod   Source File: JSONWriter.java    License: GNU General Public License v3.0 5 votes vote down vote up
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("}");
}
 
Example 23
Source Project: sakai   Source File: LTI13JwtUtil.java    License: Educational Community License v2.0 5 votes vote down vote up
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;
}
 
Example 24
Source Project: The-5zig-Mod   Source File: JSONWriter.java    License: MIT License 5 votes vote down vote up
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("}");
}
 
Example 25
Source Project: nomulus   Source File: CreateOrUpdatePremiumListCommand.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 26
Source Project: sqoop-on-spark   Source File: IntermediateDataFormat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 27
Source Project: jcoSon   Source File: jcoSon.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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);
}
 
Example 28
Source Project: ethereumj   Source File: Op.java    License: MIT License 5 votes vote down vote up
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);
    }
 
Example 29
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);
}
 
Example 30
Source Project: netbeans   Source File: NewSampleWizardIterator.java    License: Apache License 2.0 5 votes vote down vote up
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));
}