org.json.simple.JSONValue Java Examples

The following examples show how to use org.json.simple.JSONValue. 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: NPM.java    From wisdom with 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 #2
Source File: GithubUser.java    From teamcity-oauth with 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 #3
Source File: JSONUtils.java    From BiglyBT with 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 #4
Source File: SubscriptionServiceFollowsPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: URITemplate.java    From carbon-apimgt with 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 #6
Source File: Chat.java    From desktopclient-java with 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 #7
Source File: FlowReporter.java    From nomulus with 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 #8
Source File: MarkupEngine.java    From jbake with 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 #9
Source File: RestJSONResponseParser.java    From netbeans with 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 #10
Source File: RestJSONResponseParser.java    From netbeans with 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 #11
Source File: PhysicalTopologyParser.java    From cloudsimsdn with GNU General Public License v2.0 6 votes vote down vote up
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 #12
Source File: IOSDebugTransport.java    From netbeans with 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 #13
Source File: ResponseUtil.java    From singleton with 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 #14
Source File: JointSpaceBinding.java    From openhab1-addons with 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 #15
Source File: NetworkUtil.java    From seppuku with 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 #16
Source File: Performance.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: UltimateFancy.java    From UltimateChat with 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 #18
Source File: JsUtils.java    From jolie with 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 #19
Source File: Utils.java    From leaf-snowflake with 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 #20
Source File: GitHubImporter.java    From scava with 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 #21
Source File: MesosSupervisor.java    From storm with Apache License 2.0 5 votes vote down vote up
@Override
public void registered(ExecutorDriver driver, ExecutorInfo executorInfo, FrameworkInfo frameworkInfo, SlaveInfo slaveInfo) {
  LOG.info("Received executor data <{}>", executorInfo.getData().toStringUtf8());
  Map ids = (Map) JSONValue.parse(executorInfo.getData().toStringUtf8());
  _executorId = executorInfo.getExecutorId().getValue();
  _supervisorId = (String) ids.get(MesosCommon.SUPERVISOR_ID);
  _assignmentId = (String) ids.get(MesosCommon.ASSIGNMENT_ID);
  LOG.info("Registered supervisor with Mesos: {}, {} ", _supervisorId, _assignmentId);

  // Completed registration, let anything waiting for us to do so continue
  _registeredLatch.countDown();
}
 
Example #22
Source File: Page.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public Page(String navTimings, int index) {
    super();
    Gson gson = new Gson();
    //parse string(json) result form timings api to #PerformanceTimings.class
    pt = gson.fromJson(navTimings, PerformanceTimings.class);
    put("startedDateTime", getMillstoDate(pt.navigationStart));
    put("id", "page_" + index);
    put("title", pt.url == null ? "" : pt.url);
    put("pageTimings", new PageTimings(pt));
    put("raw",JSONValue.parse(navTimings));        
}
 
Example #23
Source File: CLI.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
static void exe(String key) {
    String data = exe.rmJSVar(exe.read(true, latest.exe.data.FN));
    if (data.startsWith("{") && data.endsWith("}")) {
        JSONObject res = (JSONObject) JSONValue.parse(data);
        if (res.containsKey(key)) {
            System.out.println((String) res.get(key));
        } else {
            LOG.log(Level.INFO, "ERROR:Key '{0}' not exist", key);
        }
    } else {
        System.out.println(data);
    }

}
 
Example #24
Source File: FParserTest.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
/**
 * Test of evaljs method, of class FParser.
 */
@Test(invocationCount = 10)
public void testEvaljs() {
    System.out.println("Evaljs");
    String script = "floor(100 + random() * 900)";
    String result = FParser.evaljs(script);
    assertTrue(result.matches("[0-9]{3}"),
            "Test random ");
    script = "'test'+ floor(100 + random() * 900)+'[email protected]'";
    result = (String) JSONValue.parse(FParser.evaljs(script));
    assertTrue(result.matches("test[0-9]{3}[email protected]"),
            "Test random email ");

}
 
Example #25
Source File: JSONWriter.java    From The-5zig-Mod with 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 #26
Source File: JsonSerializer.java    From jstorm with Apache License 2.0 5 votes vote down vote up
private Object readMessage() throws IOException, NoOutputException {
    String string = readString();
    Object msg = JSONValue.parse(string);
    if (msg != null) {
        return msg;
    } else {
        throw new IOException("unable to parse: " + string);
    }
}
 
Example #27
Source File: IMSJSONRequest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
public static String doErrorJSON(HttpServletRequest request,HttpServletResponse response, 
		IMSJSONRequest json, String message, Exception e) 
	throws java.io.IOException 
{
	response.setContentType(APPLICATION_JSON);
	response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
	Map<String, Object> jsonResponse = new TreeMap<String, Object>();

	Map<String, String> status = null;
	if ( json == null ) {
		status = IMSJSONRequest.getStatusFailure(message);
	} else {
		status = json.getStatusFailure(message);
		if ( json.base_string != null ) {
			jsonResponse.put("base_string", json.base_string);
		}
		if ( json.errorMessage != null ) {
			jsonResponse.put("error_message", json.errorMessage);
		}
	}
	jsonResponse.put(IMSJSONRequest.STATUS, status);
	if ( e != null ) {
		jsonResponse.put("exception", e.getLocalizedMessage());
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			log.error("{}", pw);
			pw.flush();
			sw.flush();
			jsonResponse.put("traceback", sw.toString() );
		} catch ( Exception f ) {
			jsonResponse.put("traceback", f.getLocalizedMessage());
		}
	}
	String jsonText = JSONValue.toJSONString(jsonResponse);
	PrintWriter out = response.getWriter();
	out.println(jsonText);
	return jsonText;
}
 
Example #28
Source File: Request.java    From metrics_publish_java with MIT License 5 votes vote down vote up
/**
 * Get status message by parsing JSON response body.
 * Will return null if no status is present.
 * @param responseBody
 * @return String the status message
 */
private String getStatusMessage(String responseBody) {
    Object jsonObj = JSONValue.parse(responseBody);
    JSONObject json = (JSONObject) jsonObj;
    if (json != null) {
        return (String) json.get(STATUS);
    } else {
        return null;  
    }
}
 
Example #29
Source File: Utils.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public static Object from_json(String json) {
    if (json == null) {
        return null;
    } else {
        // return JSON.parse(json);
        return JSONValue.parse(json);
    }
}
 
Example #30
Source File: UltimateFancy.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
public UltimateFancy appendAtEnd(String json) {
    Object obj = JSONValue.parse(json);
    if (obj instanceof JSONObject) {
        appendAtEnd((JSONObject) obj);
    }
    if (obj instanceof JSONArray) {
        for (Object object : ((JSONArray) obj)) {
            if (object.toString().isEmpty()) continue;
            appendAtEnd((JSONObject) JSONValue.parse(object.toString()));
        }
    }
    return this;
}