Java Code Examples for org.json.simple.JSONValue#parse()

The following examples show how to use org.json.simple.JSONValue#parse() . 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: OssmeterImporter.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private List<Stargazers> getStargazers(String artId) {
	List<Stargazers> result = new ArrayList<>();
	try {

		URL url = new URL(ossmeterUrl2 + "raw/projects/p/" + artId + "/m/stars");
		URLConnection connection = url.openConnection();
		InputStream is = connection.getInputStream();
		BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is, Charset.forName(UTF8)));
		String jsonText = readAll(bufferReader);
		JSONArray array = (JSONArray) JSONValue.parse(jsonText);

		for (Object object : array) {
			Stargazers s = new Stargazers();
			s.setDatestamp((String) ((JSONObject) object).get("datestamp"));
			s.setLogin((String) ((JSONObject) object).get("login"));
			result.add(s);
		}
		is.close();
		bufferReader.close();
		return result;
	} catch (Exception e) {
		logger.error(e.getMessage());
	}
	return result;
}
 
Example 2
Source File: UltimateFancy.java    From RedProtect 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 3
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 4
Source File: NodeJsDataProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NbBundle.Messages({"NodeJsDataprovider.lbl.name=Name:", "NodeJsDataprovider.lbl.version=Version:"}) //NOI18N
public String getDocForLocalModule(final FileObject moduleFolder) {
    FileObject packageFO = moduleFolder.getFileObject(NodeJsUtils.PACKAGE_NAME, NodeJsUtils.JSON_EXT);
    if (packageFO != null) {
        String content = null;
        try {
            content = getFileContent(FileUtil.toFile(packageFO));
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        if (content != null && !content.isEmpty()) {
            JSONObject root = (JSONObject) JSONValue.parse(content);
            if (root != null) {
                StringBuilder sb = new StringBuilder();
                sb.append(Bundle.NodeJsDataprovider_lbl_name()).append(" <b>").append(getJSONStringProperty(root, NAME)).append("</b><br/>");
                sb.append(Bundle.NodeJsDataprovider_lbl_version()).append(" ").append(getJSONStringProperty(root, MODULE_VERSION)).append("<br/><br/>");
                sb.append(getJSONStringProperty(root, MODULE_DESCRIPTION));
                return sb.toString();
            }
        }
    }
    return null;
}
 
Example 5
Source File: TestOozieResourceSensitivityDataJoiner.java    From eagle with Apache License 2.0 5 votes vote down vote up
private List<CoordinatorJob> getCoordinatorJobs() {
    List<CoordinatorJob> coordinatorJobs;
    InputStream jsonstream = this.getClass().getResourceAsStream("/coordinatorJob.json");
    JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(jsonstream));
    JSONArray jobs = (JSONArray) json.get(JsonTags.COORDINATOR_JOBS);
    coordinatorJobs = JsonToBean.createCoordinatorJobList(jobs);
    return coordinatorJobs;
}
 
Example 6
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;
}
 
Example 7
Source File: MessageContent.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static Preview fromJSONOrNull(String json) {
    Object obj = JSONValue.parse(json);
    try {
        Map<?, ?> map = (Map) obj;
        String mimeType = EncodingUtils.getJSONString(map, JSON_MIME_TYPE);
        return new Preview(mimeType);
    }  catch (NullPointerException | ClassCastException ex) {
        LOGGER.log(Level.WARNING, "can't parse JSON preview", ex);
        return null;
    }
}
 
Example 8
Source File: HostFromPropertiesFileAdapterTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitializeAdapter() {
    Map<String, JSONObject> mapKnownHosts = new HashMap<>();
    HostFromPropertiesFileAdapter hfa = new HostFromPropertiesFileAdapter(mapKnownHosts);
    assertFalse(hfa.initializeAdapter(null));
    JSONArray jsonArray = (JSONArray) JSONValue.parse(expectedKnownHostsString);
    Iterator jsonArrayIterator = jsonArray.iterator();
    while(jsonArrayIterator.hasNext()) {
        JSONObject jsonObject = (JSONObject) jsonArrayIterator.next();
        String host = (String) jsonObject.remove("ip");
        mapKnownHosts.put(host, jsonObject);
    }
    hfa = new HostFromPropertiesFileAdapter(mapKnownHosts);
    assertTrue(hfa.initializeAdapter(null));
}
 
Example 9
Source File: RepoService.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Map<String, Object> parseActivitySummary(ActivityFeedEntity entity)
{
	String activityType = entity.getActivityType();
	String activitySummary = entity.getActivitySummary();
	JSONObject json = (JSONObject)JSONValue.parse(activitySummary);
	return Activity.getActivitySummary(json, activityType);
}
 
Example 10
Source File: UltimateFancy.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
public UltimateFancy appendAtFirst(String json) {
    Object obj = JSONValue.parse(json);
    if (obj instanceof JSONObject) {
        appendAtFirst((JSONObject) obj);
    }
    if (obj instanceof JSONArray) {
        for (Object object : ((JSONArray) obj)) {
            if (object.toString().isEmpty()) continue;
            appendAtFirst((JSONObject) JSONValue.parse(object.toString()));
        }
    }
    return this;
}
 
Example 11
Source File: LTI13Servlet.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
protected Object getJSONFromPOST(HttpServletRequest request, HttpServletResponse response)
{
	String jsonString = getPostData(request, response);
	if ( jsonString == null ) return null; // Error already set

	Object js = JSONValue.parse(jsonString);
	if (js == null || !(js instanceof JSONObject)) {
		log.error("Badly formatted JSON");
		LTI13Util.return400(response, "Badly formatted JSON");
		return null;
	}
	return js;
}
 
Example 12
Source File: CheckApiActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> getCheckResponse(String domain) {
  CheckApiAction action = new CheckApiAction();
  action.domain = domain;
  action.response = new FakeResponse();
  FakeClock fakeClock = new FakeClock(START_TIME);
  action.clock = fakeClock;
  action.metricBuilder = CheckApiMetric.builder(fakeClock);
  action.checkApiMetrics = checkApiMetrics;
  fakeClock.advanceOneMilli();
  endTime = fakeClock.nowUtc();

  action.run();
  return (Map<String, Object>) JSONValue.parse(((FakeResponse) action.response).getPayload());
}
 
Example 13
Source File: HarCompareHandler.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
public static JSONObject getRefData(JSONObject req) {
    try {
        String data = Tools.readFile(new File(DashBoardData.refHars(), req.get("name").toString() + ".har.ref"));
        return (JSONObject) JSONValue.parse(data);
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Error while reading har ref file", ex);
    }
    return null;
}
 
Example 14
Source File: DynamicBrokersReader.java    From storm-kafka-0.8-plus with Apache License 2.0 5 votes vote down vote up
/**
 * [zk: localhost:2181(CONNECTED) 56] get /brokers/ids/0
 * { "host":"localhost", "jmx_port":9999, "port":9092, "version":1 }
 *
 * @param contents
 * @return
 */
private Broker getBrokerHost(byte[] contents) {
    try {
        Map<Object, Object> value = (Map<Object, Object>) JSONValue.parse(new String(contents, "UTF-8"));
        String host = (String) value.get("host");
        Integer port = ((Long) value.get("port")).intValue();
        return new Broker(host, port);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: HttpLogClient.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses CT log's response for "get-sth" into a proto object.
 *
 * @param sthResponse Log response to parse
 * @return a proto object of SignedTreeHead type.
 */
SignedTreeHead parseSTHResponse(String sthResponse) {
  Preconditions.checkNotNull(
      sthResponse, "Sign Tree Head response from a CT log should not be null");

  JSONObject response = (JSONObject) JSONValue.parse(sthResponse);
  long treeSize = (Long) response.get("tree_size");
  long timestamp = (Long) response.get("timestamp");
  if (treeSize < 0 || timestamp < 0) {
    throw new CertificateTransparencyException(
        String.format(
            "Bad response. Size of tree or timestamp cannot be a negative value. "
                + "Log Tree size: %d Timestamp: %d",
            treeSize, timestamp));
  }
  String base64Signature = (String) response.get("tree_head_signature");
  String sha256RootHash = (String) response.get("sha256_root_hash");

  SignedTreeHead sth = new SignedTreeHead(Ct.Version.V1);
  sth.treeSize = treeSize;
  sth.timestamp = timestamp;
  sth.sha256RootHash = Base64.decodeBase64(sha256RootHash);
  sth.signature =
      Deserializer.parseDigitallySignedFromBinary(
          new ByteArrayInputStream(Base64.decodeBase64(base64Signature)));

  if (sth.sha256RootHash.length != 32) {
    throw new CertificateTransparencyException(
        String.format(
            "Bad response. The root hash of the Merkle Hash Tree must be 32 bytes. "
                + "The size of the root hash is %d",
            sth.sha256RootHash.length));
  }
  return sth;
}
 
Example 16
Source File: HttpLogClient.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses CT log's response for the "get-sth-consistency" request.
 *
 * @param response JsonObject containing an array of Merkle Tree nodes.
 * @return A list of base64 decoded Merkle Tree nodes serialized to ByteString objects.
 */
private List<ByteString> parseConsistencyProof(String response) {
  Preconditions.checkNotNull(response, "Merkle Consistency response should not be null.");

  JSONObject responseJson = (JSONObject) JSONValue.parse(response);
  JSONArray arr = (JSONArray) responseJson.get("consistency");

  List<ByteString> proof = new ArrayList<ByteString>();
  for (Object node : arr) {
    proof.add(ByteString.copyFrom(Base64.decodeBase64((String) node)));
  }
  return proof;
}
 
Example 17
Source File: DcosSeedProvider.java    From dcos-cassandra-service with Apache License 2.0 4 votes vote down vote up
public List<InetAddress> getRemoteSeeds() throws IOException {

        HttpURLConnection connection =
                (HttpURLConnection) new URL(seedsUrl).openConnection();
        connection.setConnectTimeout(1000);
        connection.setReadTimeout(10000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() != 200)
            throw new RuntimeException("Unable to get data for URL " + seedsUrl);

        byte[] b = new byte[2048];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataInputStream responseStream = new DataInputStream((FilterInputStream)
                connection
                        .getContent());
        int c = 0;
        while ((c = responseStream.read(b, 0, b.length)) != -1)
            bos.write(b, 0, c);
        String response = new String(bos.toByteArray(), Charsets.UTF_8);
        LOGGER.info("Retrieved response {} from URL {}", response, seedsUrl);
        connection.disconnect();


        JSONObject json = (JSONObject) JSONValue.parse(response);

        boolean isSeed = (Boolean) json.get("isSeed");

        List<String> seedStrings = (json.containsKey("seeds"))
                ? (List<String>) json.get("seeds") : Collections.emptyList();

        List<InetAddress> addresses;

        if (isSeed) {
            addresses = new ArrayList<>(seedStrings.size() + 1);
            addresses.add(getLocalAddress());
        } else {

            addresses = new ArrayList<>(seedStrings.size());
        }

        for (String seed : seedStrings) {

            addresses.add(InetAddress.getByName(seed));
        }

        LOGGER.info("Retrieved remote seeds {}", addresses);

        return addresses;
    }
 
Example 18
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public Map JSONParse(String s) {
    return (JSONObject)JSONValue.parse(s);
}
 
Example 19
Source File: JStormUtils.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public static Map parseJson(String json) {
    if (json == null)
        return new HashMap();
    else
        return (Map) JSONValue.parse(json);
}
 
Example 20
Source File: ZybezItemListing.java    From osrsclient with GNU General Public License v2.0 4 votes vote down vote up
private void setItemData() {
    
    try {
        listingJsonString = getJsonString();
        JSONObject o = (JSONObject) JSONValue.parse(listingJsonString);
        
        itemName = o.get("name").toString();
        imageURL = o.get("image").toString();
        averagePrice = o.get("average").toString();
        
        
    } catch (IOException ex) {
        Logger.getLogger(ZybezItemListing.class.getName()).log(Level.SEVERE, null, ex);
    }

}