org.json.simple.JSONArray Java Examples

The following examples show how to use org.json.simple.JSONArray. 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: 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 #2
Source File: VersionBean.java    From sqoop-on-spark with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public JSONObject extract(boolean skipSensitive) {
  JSONObject result = new JSONObject();
  result.put(BUILD_VERSION, buildVersion);
  result.put(SOURCE_REVISION, sourceRevision);
  result.put(BUILD_DATE, buildDate);
  result.put(SYSTEM_USER_NAME, systemUser);
  result.put(SOURCE_URL, sourceUrl);
  JSONArray apiVersionsArray = new JSONArray();
  for (String version : supportedRestAPIVersions) {
    apiVersionsArray.add(version);
  }
  result.put(SUPPORTED_API_VERSIONS, apiVersionsArray);
  return result;
}
 
Example #3
Source File: Metrics.java    From skript-yaml with MIT License 6 votes vote down vote up
@Override
protected JSONObject getChartData() throws Exception {
    JSONObject data = new JSONObject();
    JSONObject values = new JSONObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JSONArray categoryValues = new JSONArray();
        categoryValues.add(entry.getValue());
        values.put(entry.getKey(), categoryValues);
    }
    data.put("values", values);
    return data;
}
 
Example #4
Source File: JSONUtil.java    From Indra with MIT License 6 votes vote down vote up
private static JSONObject toJSONObject(Map<String, Object> map) {
    JSONObject object = new JSONObject();

    for (String key : map.keySet()) {
        Object content = map.get(key);
        if (content instanceof Collection) {
            JSONArray array = new JSONArray();
            array.addAll((Collection<?>) content);
            object.put(key, array);
        } else if (content instanceof Map) {
            object.put(key, toJSONObject((Map<String, Object>) content));
        } else {
            object.put(key, content);
        }
    }

    return object;
}
 
Example #5
Source File: DockerAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<DockerContainer> getContainers() {
    try {
        JSONArray value = (JSONArray) doGetRequest("/containers/json?all=1",
                Collections.singleton(HttpURLConnection.HTTP_OK));
        List<DockerContainer> ret = new ArrayList<>(value.size());
        for (Object o : value) {
            JSONObject json = (JSONObject) o;
            String id = (String) json.get("Id");
            String image = (String) json.get("Image");
            String name = null;
            JSONArray names = (JSONArray) json.get("Names");
            if (names != null && !names.isEmpty()) {
                name = (String) names.get(0);
            }
            DockerContainer.Status status = DockerUtils.getContainerStatus((String) json.get("Status"));
            ret.add(new DockerContainer(instance, id, image, name, status));
        }
        return ret;
    } catch (DockerException ex) {
        LOGGER.log(Level.INFO, null, ex);
    }
    return Collections.emptyList();
}
 
Example #6
Source File: AuditEntry.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static ListResponse<AuditEntry> parseAuditEntries(JSONObject jsonObject)
{
    List<AuditEntry> entries = new ArrayList<>();

    JSONObject jsonList = (JSONObject) jsonObject.get("list");
    assertNotNull(jsonList);

    JSONArray jsonEntries = (JSONArray) jsonList.get("entries");
    assertNotNull(jsonEntries);

    for (int i = 0; i < jsonEntries.size(); i++)
    {
        JSONObject jsonEntry = (JSONObject) jsonEntries.get(i);
        JSONObject entry = (JSONObject) jsonEntry.get("entry");
        entries.add(parseAuditEntry(entry));
    }

    ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList);
    ListResponse<AuditEntry> resp = new ListResponse<AuditEntry>(paging, entries);
    return resp;
}
 
Example #7
Source File: AuthenticationElasticsearch.java    From sepia-assist-server with MIT License 6 votes vote down vote up
@Override
public JSONArray listUsers(Collection<String> keys, int from, int size){
	//validate keys
	keys.retainAll(ACCOUNT.allowedToShowAdmin);
	if (keys.isEmpty()){
		errorCode = 2;
		return null;
	}
	JSONObject response = getDB().getDocuments(DB.USERS, "all", from, size, keys);
	if (response == null){
		errorCode = 4;
		return null;
	}
	JSONArray hits = JSON.getJArray(response, new String[]{"hits", "hits"});
	if (hits != null && !hits.isEmpty()){
		JSONArray res = new JSONArray();
		for (Object o : hits){
			JSON.add(res, JSON.getJObject((JSONObject) o, "_source"));
		}
		return res;
	}else{
		errorCode = 4;
		return new JSONArray();
	}
}
 
Example #8
Source File: BStats.java    From TabooLib with MIT License 6 votes vote down vote up
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JSONObject getPluginData() {
    JSONObject data = new JSONObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.put("pluginName", pluginName); // Append the name of the plugin
    data.put("pluginVersion", pluginVersion); // Append the version of the plugin
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);

    return data;
}
 
Example #9
Source File: BStats.java    From FunnyGuilds with Apache License 2.0 6 votes vote down vote up
@Override
protected JSONObject getChartData() {
    JSONObject data = new JSONObject();
    JSONObject values = new JSONObject();
    HashMap<String, Integer> map = getValues(new HashMap<>());
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JSONArray categoryValues = new JSONArray();
        categoryValues.add(entry.getValue());
        values.put(entry.getKey(), categoryValues);
    }
    data.put("values", values);
    return data;
}
 
Example #10
Source File: StatusRecorder.java    From SB_Elsinore_Server with MIT License 6 votes vote down vote up
/**
 * Check to see if the JSONArrays are different.
 *
 * @param previous The first JSONArray to check
 * @param current The second JSONArray to check.
 * @return True if the JSONArrays are different
 */
protected final boolean isDifferent(final JSONArray previous,
        final JSONArray current) {

    if (previous.size() != current.size()) {
        return true;
    }

    for (int x = 0; x < previous.size(); x++) {
        Object previousValue = previous.get(x);
        Object currentValue = current.get(x);

        if (compare(previousValue, currentValue)) {
            return true;
        }
    }
    return false;
}
 
Example #11
Source File: TEDUpdaterRYU.java    From netphony-topology with Apache License 2.0 6 votes vote down vote up
private void parseNodes(String response, Hashtable<String,RouterInfoPM> routerInfoList, String ip, String port)
{	
	try
	{
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(response);
	
		JSONArray msg = (JSONArray) obj;
		Iterator<JSONObject> iterator = msg.iterator();
		while (iterator.hasNext()) 
		{	
			JSONObject jsonObject = (JSONObject) iterator.next();
			
			log.info("(String)jsonObject.get(dpid)::"+(String)jsonObject.get("dpid"));
			
			RouterInfoPM rInfo = new RouterInfoPM();

			rInfo.setRouterID(RYUtoFloodlight((String)jsonObject.get("dpid")));
			rInfo.setConfigurationMode("Openflow");
			rInfo.setControllerType(TEDUpdaterRYU.controllerName);
			
			rInfo.setControllerIdentifier(ip, port);
			rInfo.setControllerIP(ip);
			rInfo.setControllerPort(port);
			
			routerInfoList.put(rInfo.getRouterID(),rInfo);
							
			((SimpleTEDB)TEDB).getNetworkGraph().addVertex(rInfo);
		}
	}
	catch (Exception e)
	{
		log.info(e.toString());
	}
}
 
Example #12
Source File: CSS.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns meta-information of all stylesheets.
 *
 * @return meta-information of all stylesheets.
 */
public List<StyleSheetHeader> getAllStyleSheets() {
    List<StyleSheetHeader> sheets = new ArrayList<StyleSheetHeader>();
    Response response = transport.sendBlockingCommand(new Command("CSS.getAllStyleSheets")); // NOI18N
    if (response != null) {
        JSONObject result = response.getResult();
        if (result == null) {
            // CSS.getAllStyleSheets is not in the latest versions of the protocol
            sheets = Collections.unmodifiableList(styleSheetHeaders);
        } else {
            JSONArray headers = (JSONArray)result.get("headers"); // NOI18N
            for (Object o : headers) {
                JSONObject header = (JSONObject)o;
                sheets.add(new StyleSheetHeader(header));
            }
        }
    }
    return sheets;
}
 
Example #13
Source File: Metrics.java    From AnimatedFrames with MIT License 6 votes vote down vote up
@Override
protected JSONObject getChartData() {
	JSONObject data = new JSONObject();
	JSONObject values = new JSONObject();
	HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
	if (map == null || map.isEmpty()) {
		// Null = skip the chart
		return null;
	}
	for (Map.Entry<String, Integer> entry : map.entrySet()) {
		JSONArray categoryValues = new JSONArray();
		categoryValues.add(entry.getValue());
		values.put(entry.getKey(), categoryValues);
	}
	data.put("values", values);
	return data;
}
 
Example #14
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsProductionEndpointsInvalidJSON() throws Exception {
    Log log = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);

    API api = Mockito.mock(API.class);

    Mockito.when(api.getEndpointConfig()).thenReturn("</SomeXML>");

    Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists("</SomeXML>"));

    JSONObject productionEndpoints = new JSONObject();
    productionEndpoints.put("url", "https:\\/\\/localhost:9443\\/am\\/sample\\/pizzashack\\/v1\\/api\\/");
    productionEndpoints.put("config", null);
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(productionEndpoints);

    Mockito.when(api.getEndpointConfig()).thenReturn(jsonArray.toJSONString());

    Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists(jsonArray.toJSONString()));
}
 
Example #15
Source File: ParserASTJSON.java    From soltix with Apache License 2.0 6 votes vote down vote up
protected void processPragmaDirective(long id, AST ast, JSONObject attributes) throws Exception {
    JSONArray literals = (JSONArray)attributes.get("literals");
    if (literals == null) {
        throw new Exception("Pragma directive without literals attribute");
    }
    if (literals.size() < 1) {
        throw new Exception("Pragma directive with empty literals list");
    }
    String type = (String)literals.get(0);
    String args = null;
    if (literals.size() > 1) {
        args = "";
        for (int i = 1; i < literals.size(); ++i) {
            args += (String)literals.get(i);
        }
    }
    ast.addInnerNode(new ASTPragmaDirective(id, type, args));
}
 
Example #16
Source File: JsonSimpleConfigParser.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
private List<Group> parseGroups(JSONArray groupJson) {
    List<Group> groups = new ArrayList<Group>(groupJson.size());

    for (Object obj : groupJson) {
        JSONObject groupObject = (JSONObject) obj;
        String id = (String) groupObject.get("id");
        String policy = (String) groupObject.get("policy");
        List<Experiment> experiments = parseExperiments((JSONArray) groupObject.get("experiments"), id);
        List<TrafficAllocation> trafficAllocations =
            parseTrafficAllocation((JSONArray) groupObject.get("trafficAllocation"));

        groups.add(new Group(id, policy, experiments, trafficAllocations));
    }

    return groups;
}
 
Example #17
Source File: DateManagerServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public JSONArray getSignupMeetingsForContext(String siteId) {
	JSONArray jsonMeetings = new JSONArray();
	Collection<SignupMeeting> meetings = signupService.getAllSignupMeetings(siteId, getCurrentUserId());
	String url = getUrlForTool(DateManagerConstants.COMMON_ID_SIGNUP);
	String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_SIGNUP).getTitle();
	for(SignupMeeting meeting : meetings) {
		JSONObject mobj = new JSONObject();
		mobj.put("id", meeting.getId());
		mobj.put("title", meeting.getTitle());
		mobj.put("due_date", formatToUserDateFormat(meeting.getEndTime()));
		mobj.put("open_date", formatToUserDateFormat(meeting.getStartTime()));
		mobj.put("tool_title", toolTitle);
		mobj.put("url", url);
		mobj.put("extraInfo", "false");
		jsonMeetings.add(mobj);
	}
	return jsonMeetings;
}
 
Example #18
Source File: JSONBasicRollupOutputSerializerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void setTimers() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(
            FakeMetricDataGenerator.generateFakeTimerRollups(),
            "unknown");
    
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_TIMER);
    final JSONArray data = (JSONArray)metricDataJSON.get("values");
    
    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject)data.get(i);
        
        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertNotNull(dataJSON.get("average"));
        Assert.assertNotNull(dataJSON.get("rate"));
        
        // bah. I'm too lazy to check equals.
    }
}
 
Example #19
Source File: UserDataListFilterTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * filterクエリに複数の括弧を指定してフィルタリング後に特定のプロパティのみが取得できること.
 */
@Test
public final void filterクエリに複数の括弧を指定してフィルタリング後に特定のプロパティのみが取得できること() {
    final String entity = "filterlist";
    String query = "?\\$top=3&\\$skip=4&\\$select=datetime&"
            + "\\$filter=%28substringof%28%27string%27%2Cstring%29+and+%28boolean+eq+false"
            + "%29%29+or+%28int32+le+5000%29&\\$inlinecount=allpages&\\$orderby=__id+asc";
    TResponse res = UserDataUtils.list(Setup.TEST_CELL_FILTER, "box", "odata", entity,
            query, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK);
    // レスポンスボディーが昇順に並んでいることのチェック
    JSONObject jsonResp = res.bodyAsJson();
    ArrayList<String> urilist = new ArrayList<String>();
    int[] ids = {4, 5, 7 };
    for (int idx : ids) {
        urilist.add(UrlUtils.userData(Setup.TEST_CELL_FILTER, "box", "odata",
                entity + String.format("('id_%04d')", idx)));
    }
    ODataCommon.checkCommonResponseUri(jsonResp, urilist);
    JSONArray array = (JSONArray) ((JSONObject) jsonResp.get("d")).get("results");
    for (Object element : array) {
        JSONObject json = (JSONObject) element;
        assertTrue(json.containsKey("datetime"));
        assertFalse(json.containsKey("int32"));

    }
}
 
Example #20
Source File: TranslationProductAction.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
private JSONObject getBundle(String component, String locale, TranslationDTO allTranslationDTO) {
    
    JSONArray array = allTranslationDTO.getBundles();
    @SuppressWarnings("unchecked")
   Iterator<JSONObject> objectIterator =  array.iterator();
    
    while(objectIterator.hasNext()) {
        JSONObject object = objectIterator.next();
        String fileLocale = (String) object.get(ConstantsKeys.lOCALE);
        String fileComponent = (String) object.get(ConstantsKeys.COMPONENT);
        if(locale.equals(fileLocale)&& component.equals(fileComponent)) {    
            return object;
        }
    }
    
   return null; 
}
 
Example #21
Source File: AerospikeJavaRDDFT.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
/**
 * Imports dataset.
 *
 * @throws java.io.IOException
 */
private static void dataSetImport() throws IOException, ParseException {
    URL url = Resources.getResource(DATA_SET_NAME);
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(url.getFile()));
    JSONObject jsonObject = (JSONObject) obj;

    String id = (String) jsonObject.get("id");
    JSONObject metadata = (JSONObject) jsonObject.get("metadata");
    JSONArray cantos = (JSONArray) jsonObject.get("cantos");

    Key key = new Key(NAMESPACE_ENTITY, SET_NAME, id);
    Bin binId = new Bin("id", id);
    Bin binMetadata = new Bin("metadata", metadata);
    Bin binCantos = new Bin("cantos", cantos);
    aerospike.put(null, key, binId, binMetadata, binCantos);
    aerospike.createIndex(null, NAMESPACE_ENTITY, SET_NAME, "id_idx", "id", IndexType.STRING);

    Key key2 = new Key(NAMESPACE_CELL, SET_NAME, 3);
    Bin bin_id = new Bin("_id", "3");
    Bin bin_number = new Bin("number", 3);
    Bin bin_text = new Bin("message", "new message test");
    aerospike.put(null, key2, bin_id, bin_number, bin_text);
    aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "num_idx", "number", IndexType.NUMERIC);
    aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "_id_idx", "_id", IndexType.STRING);
}
 
Example #22
Source File: Style.java    From netbeans with Apache License 2.0 6 votes vote down vote up
Style(JSONObject style, String preferredId) {
    if (preferredId != null) {
        id = new StyleId(preferredId);
    } else {
        if (style.containsKey("styleId")) { // NOI18N
            id = new StyleId((JSONObject)style.get("styleId")); // NOI18N
        } else if (style.containsKey("styleSheetId")) { // NOI18N
            id = new StyleId((String)style.get("styleSheetId")); // NOI18N
        } else {
            id = null;
        }
    }
    JSONArray cssProperties = (JSONArray)style.get("cssProperties"); // NOI18N
    properties = new ArrayList<Property>(cssProperties.size());
    for (Object o : cssProperties) {
        JSONObject cssProperty = (JSONObject)o;
        Property property = new Property(cssProperty);
        properties.add(property);
    }
    text = (String)style.get("cssText"); // NOI18N
    if (style.containsKey("range")) { // NOI18N
        range = new SourceRange((JSONObject)style.get("range")); // NOI18N
    }
}
 
Example #23
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-entries" into a list of {@link ParsedLogEntry} objects.
 *
 * @param response Log response to pars.
 * @return list of Log's entries.
 */
@SuppressWarnings("unchecked")
private List<ParsedLogEntry> parseLogEntries(String response) {
  Preconditions.checkNotNull(response, "Log entries response from Log should not be null.");

  JSONObject responseJson = (JSONObject) JSONValue.parse(response);
  JSONArray arr = (JSONArray) responseJson.get("entries");
  return Lists.transform(arr, jsonToLogEntry);
}
 
Example #24
Source File: Metrics.java    From WildernessTp with MIT License 5 votes vote down vote up
@Override
protected JSONObject getChartData() {
    JSONObject data = new JSONObject();
    JSONObject values = new JSONObject();
    HashMap<String, int[]> map = getValues(new HashMap<String, int[]>());
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JSONArray categoryValues = new JSONArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(categoryValue);
        }
        values.put(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.put("values", values);
    return data;
}
 
Example #25
Source File: ModelVisualizationJson.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
public UUID addFrameJsonObject(PhysicalFrame bdy, 
        JSONObject geometryJson,
        JSONObject materialJson,
        JSONObject sceneGraphObjectJson){
    UUID obj_uuid = UUID.randomUUID();
    json_geometries.add(geometryJson);
    json_materials.add(materialJson);
    JSONObject bodyJson = mapBodyIndicesToJson.get(bdy.getMobilizedBodyIndex());
    if (bodyJson.get("children")==null)
        bodyJson.put("children", new JSONArray());
    ((JSONArray)bodyJson.get("children")).add(sceneGraphObjectJson);
    return obj_uuid;
}
 
Example #26
Source File: TagServiceEntityProvider.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@EntityCustomAction(action = "getPaginatedTagCollections", viewKey = EntityView.VIEW_LIST)
public JSONObject getTagCollections(EntityView view, Map<String, Object> params) {
    try {
        WrappedParams wp = new WrappedParams(params);
        int maxPageSize = tagService().getMaxPageSize();
        int page= wp.getInteger("page",TAGSERVICE_FIRST_PAGE_DEFAULT);
        int pageLimit= wp.getInteger("pagelimit",TAGSERVICE_PAGE_LIMIT_DEFAULT);

        if (pageLimit > maxPageSize) {
            pageLimit = maxPageSize;
        }

        List<TagCollection> tagCollections = tagService().getTagCollections().getTagCollectionsPaginated(page,pageLimit);
        int tagCollectionsCount = tagService().getTagCollections().getTotalTagCollections();

        JSONObject responseDetailsJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        for(TagCollection p : tagCollections) {
            JSONObject formDetailsJson = new JSONObject();
            formDetailsJson.put("tagCollectionId", p.getTagCollectionId());
            formDetailsJson.put("name", p.getName());
            formDetailsJson.put("description", p.getDescription());
            formDetailsJson.put("externalsourcename", p.getExternalSourceName());
            formDetailsJson.put("externalsourcedescription", p.getExternalSourceDescription());
            jsonArray.add(formDetailsJson);
        }
        responseDetailsJson.put("total",tagCollectionsCount );
        responseDetailsJson.put("tagCollections", jsonArray);//Here you can see the data in json format

        return responseDetailsJson;

    } catch (Exception e) {
        log.error("Error calling getTagCollections:",e);
        return null;
    }
}
 
Example #27
Source File: JSONReader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static V8Scope[] getScopes(JSONArray array, Long frameIndex) {
    int n = array.size();
    V8Scope[] scopes = new V8Scope[n];
    for (int i = 0; i < n; i++) {
        scopes[i] = getScope((JSONObject) array.get(i), frameIndex);
    }
    return scopes;
}
 
Example #28
Source File: BukkitPlayerInfo.java    From AntiVPN with MIT License 5 votes vote down vote up
private static String nameExpensive(UUID uuid) throws IOException {
    // Currently-online lookup
    Player player = Bukkit.getPlayer(uuid);
    if (player != null) {
        nameCache.put(player.getName(), uuid);
        return player.getName();
    }

    // Network lookup
    HttpURLConnection conn = JSONWebUtil.getConnection(new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names"), "GET", 5000, "egg82/PlayerInfo", headers);;
    int status = conn.getResponseCode();

    if (status == 204) {
        // No data exists
        return null;
    } else if (status == 200) {
        try {
            JSONArray json = getJSONArray(conn, status);
            JSONObject last = (JSONObject) json.get(json.size() - 1);
            String name = (String) last.get("name");
            nameCache.put(name, uuid);
            return name;
        } catch (ParseException | ClassCastException ex) {
            throw new IOException(ex.getMessage(), ex);
        }
    }

    throw new IOException("Could not load player data from Mojang (rate-limited?)");
}
 
Example #29
Source File: FromJSONLogic.java    From EchoSim with Apache License 2.0 5 votes vote down vote up
public static List<TransactionBean> fromJSONTransactions(JSONArray jtranss, ApplicationBean context)
{
    List<TransactionBean> transs = new ArrayList<TransactionBean>();
    for (Object jtrans : jtranss)
        transs.add(fromJSONTransaction(new TransactionBean(), (JSONObject)jtrans, context));
    return transs;
}
 
Example #30
Source File: ReferenceTests.java    From teku with Apache License 2.0 5 votes vote down vote up
@MustBeClosed
static Stream<Arguments> getExpandMessageTestCases() {
  final JSONParser parser = new JSONParser();
  final ArrayList<Arguments> argumentsList = new ArrayList<>();

  try {
    final Reader reader = new FileReader(pathToExpandMessageTests.toFile(), US_ASCII);
    final JSONObject refTests = (JSONObject) parser.parse(reader);

    final Bytes dst = Bytes.wrap(((String) refTests.get("DST")).getBytes(US_ASCII));

    final JSONArray tests = (JSONArray) refTests.get("tests");
    int idx = 0;
    for (Object o : tests) {
      JSONObject test = (JSONObject) o;
      Bytes message = Bytes.wrap(((String) test.get("msg")).getBytes(US_ASCII));
      int length = Integer.parseInt(((String) test.get("len_in_bytes")).substring(2), 16);
      Bytes uniformBytes = Bytes.fromHexString((String) test.get("uniform_bytes"));
      argumentsList.add(
          Arguments.of(
              pathToExpandMessageTests.toString(), idx++, dst, message, length, uniformBytes));
    }
  } catch (IOException | ParseException e) {
    throw new RuntimeException(e);
  }

  return argumentsList.stream();
}