List of usage examples for org.json.simple.parser JSONParser JSONParser
JSONParser
From source file:TestBufferStreamGenomicsDBImporter.java
/** * Sample driver code for testing Java VariantContext write API for GenomicsDB * The code shows two ways of using the API * (a) Iterator<VariantContext>/* w ww .j av a 2 s.co m*/ * (b) Directly adding VariantContext objects * If "-iterators" is passed as the second argument, method (a) is used. */ public static void main(final String[] args) throws IOException, GenomicsDBException, ParseException { if (args.length < 2) { System.err.println("For loading: [-iterators] <loader.json> " + "<stream_name_to_file.json> [bufferCapacity rank lbRowIdx ubRowIdx useMultiChromosomeIterator]"); System.exit(-1); } int argsLoaderFileIdx = 0; if (args[0].equals("-iterators")) argsLoaderFileIdx = 1; //Buffer capacity long bufferCapacity = (args.length >= argsLoaderFileIdx + 3) ? Integer.parseInt(args[argsLoaderFileIdx + 2]) : 1024; //Specify rank (or partition idx) of this process int rank = (args.length >= argsLoaderFileIdx + 4) ? Integer.parseInt(args[argsLoaderFileIdx + 3]) : 0; //Specify smallest row idx from which to start loading. // This is useful for incremental loading into existing array long lbRowIdx = (args.length >= argsLoaderFileIdx + 5) ? Long.parseLong(args[argsLoaderFileIdx + 4]) : 0; //Specify largest row idx up to which loading should be performed - for completeness long ubRowIdx = (args.length >= argsLoaderFileIdx + 6) ? Long.parseLong(args[argsLoaderFileIdx + 5]) : Long.MAX_VALUE - 1; //Boolean to use MultipleChromosomeIterator boolean useMultiChromosomeIterator = (args.length >= argsLoaderFileIdx + 7) ? Boolean.parseBoolean(args[argsLoaderFileIdx + 6]) : false; //<loader.json> first arg String loaderJSONFile = args[argsLoaderFileIdx]; GenomicsDBImporter loader = new GenomicsDBImporter(loaderJSONFile, rank, lbRowIdx, ubRowIdx); //<stream_name_to_file.json> - useful for the driver only //JSON file that contains "stream_name": "vcf_file_path" entries FileReader mappingReader = new FileReader(args[argsLoaderFileIdx + 1]); JSONParser parser = new JSONParser(); LinkedHashMap streamNameToFileName = (LinkedHashMap) parser.parse(mappingReader, new LinkedHashFactory()); ArrayList<VCFFileStreamInfo> streamInfoVec = new ArrayList<VCFFileStreamInfo>(); long rowIdx = 0; for (Object currObj : streamNameToFileName.entrySet()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) currObj; VCFFileStreamInfo currInfo = new VCFFileStreamInfo(entry.getValue(), loaderJSONFile, rank, useMultiChromosomeIterator); /** The following 2 lines are not mandatory - use initializeSampleInfoMapFromHeader() * iff you know for sure that sample names in the VCF header are globally unique * across all streams/files. If not, you have 2 options: * (a) specify your own mapping from sample index in the header to SampleInfo object * (unique_name, rowIdx) OR * (b) specify the mapping in the callset_mapping_file (JSON) and pass null to * addSortedVariantContextIterator() */ LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo> sampleIndexToInfo = new LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo>(); rowIdx = GenomicsDBImporter.initializeSampleInfoMapFromHeader(sampleIndexToInfo, currInfo.mVCFHeader, rowIdx); int streamIdx = -1; if (args[0].equals("-iterators")) streamIdx = loader.addSortedVariantContextIterator(entry.getKey(), currInfo.mVCFHeader, currInfo.mIterator, bufferCapacity, VariantContextWriterBuilder.OutputType.BCF_STREAM, sampleIndexToInfo); //pass sorted VC iterators else //use buffers - VCs will be provided by caller streamIdx = loader.addBufferStream(entry.getKey(), currInfo.mVCFHeader, bufferCapacity, VariantContextWriterBuilder.OutputType.BCF_STREAM, sampleIndexToInfo); currInfo.mStreamIdx = streamIdx; streamInfoVec.add(currInfo); } if (args[0].equals("-iterators")) { //Much simpler interface if using Iterator<VariantContext> loader.importBatch(); assert loader.isDone(); } else { //Must be called after all iterators/streams added - no more iterators/streams // can be added once this function is called loader.setupGenomicsDBImporter(); //Counts and tracks buffer streams for which new data must be supplied //Initialized to all the buffer streams int numExhaustedBufferStreams = streamInfoVec.size(); int[] exhaustedBufferStreamIdxs = new int[numExhaustedBufferStreams]; for (int i = 0; i < numExhaustedBufferStreams; ++i) exhaustedBufferStreamIdxs[i] = i; while (!loader.isDone()) { //Add data for streams that were exhausted in the previous round for (int i = 0; i < numExhaustedBufferStreams; ++i) { VCFFileStreamInfo currInfo = streamInfoVec.get(exhaustedBufferStreamIdxs[i]); boolean added = true; while (added && (currInfo.mIterator.hasNext() || currInfo.mNextVC != null)) { if (currInfo.mNextVC != null) added = loader.add(currInfo.mNextVC, currInfo.mStreamIdx); if (added) if (currInfo.mIterator.hasNext()) currInfo.mNextVC = currInfo.mIterator.next(); else currInfo.mNextVC = null; } } loader.importBatch(); numExhaustedBufferStreams = (int) loader.getNumExhaustedBufferStreams(); for (int i = 0; i < numExhaustedBufferStreams; ++i) exhaustedBufferStreamIdxs[i] = loader.getExhaustedBufferStreamIndex(i); } } }
From source file:iracing.webapi.LicenseParser.java
public static List<License> parse(String json) { JSONParser parser = new JSONParser(); List<License> output = null; try {/* w w w . jav a 2 s .c o m*/ JSONArray root = (JSONArray) parser.parse(json); output = new ArrayList<License>(); for (int i = 0; i < root.size(); i++) { JSONObject o = (JSONObject) root.get(i); License license = new License(); license.setId(getInt(o, "id")); license.setShortName(getString(o, "shortname")); license.setFullName(getString(o, "name", true)); output.add(license); } } catch (ParseException ex) { Logger.getLogger(LicenseParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:iracing.webapi.TrackParser.java
public static List<Track> parse(String json) { JSONParser parser = new JSONParser(); List<Track> output = null; try {/*from www. j a va 2 s . c o m*/ //[{"config":"Legends+Oval","priority":3,"pkgid":36,"skuname":"Atlanta+Motor+Speedway","retired":0,"price":14.95,"hasNightLighting":false,"name":"Atlanta+Motor+Speedway","lowername":"atlanta+motor+speedway","nominalLapTime":15.5574207,"lowerNameAndConfig":"atlanta+motor+speedway+legends+oval","catid":1,"priceDisplay":"14.95","id":52,"sku":10039},{"config":"Road+Course","priority":2,"pkgid":36,"skuname":"Atlanta+Motor+Speedway","retired":0,"price":14.95,"hasNightLighting":false,"name":"Atlanta+Motor+Speedway","lowername":"atlanta+motor+speedway","nominalLapTime":82.5555344,"lowerNameAndConfig":"atlanta+motor+speedway+road+course","catid":2,"priceDisplay":"14.95","id":51,"sku":10039}] JSONArray root = (JSONArray) parser.parse(json); output = new ArrayList<Track>(); for (int i = 0; i < root.size(); i++) { JSONObject o = (JSONObject) root.get(i); Track track = new Track(); track.setId(getInt(o, "id")); track.setPackageId(getInt(o, "pkgid")); track.setCategoryId(getInt(o, "catid")); track.setPriority(getInt(o, "priority")); track.setSku(getLong(o, "sku")); track.setSkuName(getString(o, "skuname", true)); track.setRetired((getInt(o, "retired")) == 1); track.setName(getString(o, "name", true)); track.setConfigName(getString(o, "config", true)); track.setHasNightLighting((Boolean) o.get("hasNightLighting")); track.setPrice(getDouble(o, "price")); track.setPriceDisplay(getString(o, "priceDisplay")); track.setNominalLapTime(getDouble(o, "nominalLapTime")); output.add(track); } } catch (ParseException ex) { Logger.getLogger(LicenseParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:iracing.webapi.LicenseGroupParser.java
public static List<LicenseGroup> parse(String json) { JSONParser parser = new JSONParser(); List<LicenseGroup> output = null; try {//from w w w . j a v a 2 s.c o m JSONArray rootArray = (JSONArray) parser.parse(json); output = new ArrayList<LicenseGroup>(); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); LicenseGroup lg = new LicenseGroup(); lg.setId(getInt(r, "group")); lg.setName(getString(r, "name", true)); // NOTE: the following aren't specified if not applicable Object o = r.get("minNumTT"); if (o != null) lg.setMinimumNumberOfTimeTrials(((Long) o).intValue()); o = r.get("minNumRaces"); if (o != null) lg.setMinimumNumberOfRaces(((Long) o).intValue()); output.add(lg); } } catch (ParseException ex) { Logger.getLogger(LicenseGroupParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:authorship.verification.ReadJSON.java
public static String readJson(String file) { JSONParser parser = new JSONParser(); try {/*from w w w.jav a2 s . c o m*/ FileReader fileReader = new FileReader(file); JSONObject json = (JSONObject) parser.parse(fileReader); language = (String) json.get("language"); //System.out.println("Language: " + language); JSONArray filenames = (JSONArray) json.get("problems"); Iterator i = filenames.iterator(); /*System.out.println("Filenames: "); while (i.hasNext()) { System.out.println(" " + i.next()); } */ } catch (Exception ex) { ex.printStackTrace(); } return language; }
From source file:iracing.webapi.DriverStatsParser.java
static DriverStats parse(String json, boolean includeApiUserTopRow) { JSONParser parser = new JSONParser(); DriverStats output = null;//from w w w . j a va 2 s .c o m try { JSONObject root = (JSONObject) parser.parse(json); JSONObject root2 = (JSONObject) root.get("d"); output = new DriverStats(); output.setApiUserRow(getLong(root2, "24")); output.setTotalRecords(getLong(root2, "33")); JSONArray arrayRoot = (JSONArray) root2.get("r"); List<DriverStat> statList = new ArrayList<DriverStat>(); for (int i = 0; i < arrayRoot.size(); i++) { JSONObject r = (JSONObject) arrayRoot.get(i); long recordNumber = getLong(r, "37"); if (!includeApiUserTopRow && recordNumber == 0) continue; DriverStat ds = new DriverStat(); ds.setClubName(getString(r, "1", true)); ds.setCountryCode(getString(r, "2", true)); ds.setLicenseSubLevel(getInt(r, "3")); ds.setIratingRank(getLong(r, "4")); ds.setAverageFinishingPosition(getInt(r, "5")); ds.setIrating(getInt(r, "6")); ds.setLicenseGroupName(getString(r, "7", true)); IracingCustomer driver = new IracingCustomer(); driver.setName(getString(r, "8", true)); driver.setId(getLong(r, "29")); ds.setDriver(driver); ds.setTimeTrialRatingRank(getLong(r, "9")); ds.setAverageIncidentsPerRace(getDouble(r, "10")); ds.setTotalTop25PercentFinishes(getLong(r, "11")); ds.setClubId(getInt(r, "12")); ds.setTotalStarts(getLong(r, "13")); ds.setLicenseClassRank(getLong(r, "15")); ds.setTotalLapsLed(getLong(r, "16")); ds.setTotalWins(getLong(r, "17")); ds.setTotalClubPoints(getLong(r, "18")); ds.setTimeTrialRating(getInt(r, "19")); ds.setLicenseGroupId(getInt(r, "20")); ds.setLicenseLevelId(getInt(r, "21")); ds.setTotalChampionshipPoints(getLong(r, "22")); ds.setLicenseGroupLetter(getString(r, "23", true)); ds.setAverageFieldSize(getInt(r, "25")); ds.setRank(getLong(r, "26")); ds.setRegionName(getString(r, "31", true)); ds.setAveragePointsPerRace(getInt(r, "32")); ds.setTotalLaps(getLong(r, "34")); ds.setLicenseClass(getString(r, "35", true)); ds.setAverageStartingPosition(getInt(r, "36")); ds.setRecordNumber(recordNumber); statList.add(ds); } output.setStats(statList); } catch (ParseException ex) { Logger.getLogger(DriverStatsParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:iracing.webapi.SeasonParser.java
public static List<Season> parse(String json) { JSONParser parser = new JSONParser(); List<Season> output = null; try {//from w w w . j a v a2s .c om JSONArray rootArray = (JSONArray) parser.parse(json); output = new ArrayList<Season>(); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); Season season = new Season(); season.setId(getInt(r, "seasonid")); season.setPrefImage(getString(r, "prefimg", true)); season.setSeriesName(getString(r, "seriesname", true)); season.setSeasonShortName(getString(r, "seasonshortname", true)); season.setWhatsHotImage(getString(r, "whatshotimg", true)); season.setCautionTypeRoad(getInt(r, "cautionTypeRoad")); season.setCautionTypeOval(getInt(r, "cautionTypeOval")); season.setRaceWeeks(getInt(r, "raceweek")); season.setActive((Boolean) r.get("active")); season.setMinimumSafetyRating(getString(r, "minsr")); season.setMinimumLicenseLevel(getInt(r, "minlicenselevel")); season.setMaximumLicenseLevel(getInt(r, "maxlicenselevel")); JSONArray array = (JSONArray) r.get("tracks"); List<Season.Track> trackList = new ArrayList<Season.Track>(); // to work around a website bug where tracks are listed 3 times each, // we only add ones that have different raceweek values int lastRaceWeek = -1; for (int j = 0; j < array.size(); j++) { //{"config":"","priority":0,"raceweek":0,"pkgid":90,"night":0,"name":"Mosport+International+Raceway","id":144,"lowername":"mosport+international+raceway"} JSONObject o = (JSONObject) array.get(j); int raceWeek = getInt(o, "raceweek"); if (raceWeek != lastRaceWeek) { Season.Track track = new Season.Track(); track.setId(getInt(o, "id")); track.setNightMode((getInt(o, "night")) == 1); trackList.add(track); lastRaceWeek = raceWeek; } } season.setTracks(trackList); //"carclasses":[{"carsinclass":[{"name":"Cadillac+CTS-V+Racecar","id":41}],"shortname":"Cadillac+CTS-VR","name":"Cadillac+CTS-VR","id":45,"lowername":"cadillac+cts-vr"}] List<Integer> carClasses = new ArrayList<Integer>(); array = (JSONArray) r.get("carclasses"); for (int j = 0; j < array.size(); j++) { JSONObject o = (JSONObject) array.get(j); //JSONArray array2 = (JSONArray)o.get("carsinclass"); carClasses.add(getInt(o, "id")); } season.setCarClasses(carClasses); season.setApiUserClubAllowed((Boolean) r.get("isClubAllowed")); season.setSeriesLicenseGroupId(getInt(r, "serieslicgroupid")); season.setCurrentTrack(getInt(r, "currentTrack")); season.setSeriesId(getInt(r, "seriesid")); season.setLicenseGroupId(getInt(r, "licgroupid")); season.setLicenseIgnoredForPractice((Boolean) r.get("ignoreLicenseForPractice")); season.setWorldCupEvent((Boolean) r.get("isWorldCup")); season.setStartDate(new Date(getLong(r, "start"))); season.setEndDate(new Date(getLong(r, "end"))); array = (JSONArray) r.get("cars"); List<Integer> carList = new ArrayList<Integer>(); for (int j = 0; j < array.size(); j++) { JSONObject o = (JSONObject) array.get(j); carList.add(getInt(o, "id")); } season.setCars(carList); season.setMultiClass((Boolean) r.get("multiclass")); season.setRegionalCompetitionEvent((Boolean) r.get("isRegionCompetition")); season.setQuarter(getInt(r, "quarter")); season.setYear(getInt(r, "year")); season.setSeriesShortName(getString(r, "seriesshortname", true)); season.setCategoryId(getInt(r, "catid")); // also stored under 'category' season.setOfficial((Boolean) r.get("isOfficial")); season.setApiUserLicenseEligible((Boolean) r.get("licenseEligible")); season.setComplete((Boolean) r.get("complete")); output.add(season); } } catch (ParseException ex) { Logger.getLogger(SeasonParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:iracing.webapi.SpectatorSessionParser.java
static List<SpectatorSession> parse(String json) { JSONParser parser = new JSONParser(); List<SpectatorSession> output = null; try {//from w ww. j av a 2s .c om JSONArray rootArray = (JSONArray) parser.parse(json); output = new ArrayList<SpectatorSession>(); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); SpectatorSession o = new SpectatorSession(); o.setSubSessionStatus(getString(r, "subses_status")); o.setSessionStatus(getString(r, "ses_status")); JSONObject b = (JSONObject) r.get("broadcast"); SpectatorSession.BroadcastInfo bi = new SpectatorSession.BroadcastInfo(); bi.setCanBroadcast((Boolean) b.get("canBroadcast")); bi.setSubSessionId(getLong(b, "subSessionId")); bi.setBroadcaster((Boolean) b.get("isBroadcaster")); bi.setMaximumUsers(getInt(b, "maxUsers")); bi.setAvailableSpectatorSlots(getInt(b, "availSpectatorSlots")); bi.setNumberOfDrivers(getInt(b, "numDrivers")); bi.setNumberOfDriverSlots(getInt(b, "numDriverSlots")); bi.setNumberOfSpectators(getInt(b, "numSpectators")); bi.setNumberOfBroadcasters(getInt(b, "numBroadcasters")); bi.setNumberOfSpectatorSlots(getInt(b, "numSpectatorSlots")); bi.setAvailableReservedBroadcasterSlots(getInt(b, "availReservedBCasterSlots")); bi.setCanWatch((Boolean) b.get("canWatch")); o.setBroadcastInfo(bi); o.setSubSessionId(getLong(r, "subsessionid")); o.setSessionId(getLong(r, "sessionid")); o.setSeriesId(getInt(r, "seriesid")); o.setTrackId(getInt(r, "trackid")); JSONObject h = (JSONObject) r.get("hosted"); if (h != null) { SpectatorSession.HostedInfo hi = new SpectatorSession.HostedInfo(); hi.setHeatFilterAmount(getInt(h, "heatFilterAmount")); hi.setPracticeLength(getInt(h, "practiceLength")); JSONArray a = (JSONArray) h.get("admins"); List<SpectatorSession.DriverInfo> driverList = new ArrayList<SpectatorSession.DriverInfo>(); for (int j = 0; j < a.size(); j++) { JSONObject ar = (JSONObject) a.get(j); if (ar != null) { SpectatorSession.DriverInfo di = new SpectatorSession.DriverInfo(); di.setCustomerId(getLong(ar, "custId")); di.setName(getString(ar, "displayName", true)); driverList.add(di); } } hi.setAdministrators(driverList); hi.setOrderId(getLong(h, "orderId")); hi.setMaximumIrating(getInt(h, "maxIR")); hi.setMinimumLicenseLevel(getInt(h, "minLicLevel")); hi.setRootPrivateSessionId(getLong(h, "rootPrivateSessionId")); hi.setDescription(getString(h, "desc", true)); hi.setFastTows(getInt(h, "fastTows")); hi.setQualifyingLength(getInt(h, "qualLength")); hi.setRaceLength(getInt(h, "raceLength")); hi.setRestrictResults((getInt(h, "restrictResults")) == 1); hi.setHardcoreLevelId(getInt(h, "hardcoreLevel")); hi.setId(getLong(h, "id")); hi.setMaximumLicenseLevel(getInt(h, "maxLicLevel")); hi.setQualifyingLaps(getInt(h, "qualLaps")); hi.setHostName(getString(h, "host", true)); // TODO: handle allowed clubs/leagues/teams hi.setRaceLaps(getInt(h, "raceLaps")); hi.setNumberOfServers(getInt(h, "numServers")); hi.setCustomerId(getLong(h, "custid")); // TODO: handle league info hi.setHeatGridType(getInt(h, "heatGridType")); hi.setExpires(new Date(getLong(h, "expires"))); hi.setHeatAddedDrivers(getInt(h, "heatAddedDrivers")); hi.setNumberOfServersFinished(getInt(h, "numServersFinished")); hi.setMultiClass((getInt(h, "multiClass")) == 1); hi.setRestrictViewing((getInt(h, "restrictViewing")) == 1); hi.setSessionName(getString(h, "sessionName", true)); List<Integer> carList = new ArrayList<Integer>(); JSONArray ca = (JSONArray) h.get("carIds"); for (int j = 0; j < ca.size(); j++) { carList.add(((Long) ca.get(j)).intValue()); } hi.setCars(carList); hi.setReason(getString(h, "reason", true)); hi.setTrackId(getInt(h, "trackId")); hi.setLaunchAt(new Date(getLong(h, "launchAt"))); hi.setMaximumDrivers(getInt(h, "maxDrivers")); hi.setSessionId(getLong(h, "sessionId")); hi.setHeatGridsId(getInt(h, "heatGridsId")); hi.setParentPrivateSessionId(getLong(h, "parentPrivateSessionId")); hi.setNightMode((getInt(h, "nightMode")) == 1); hi.setHeatSessionType(getInt(h, "heatSessionType")); hi.setHeatFilterType(getInt(h, "heatFilterType")); hi.setHeatFinal((getInt(h, "heatFinal")) == 1); hi.setCreated(new Date(getLong(h, "created"))); hi.setCautions((getInt(h, "cautions")) == 1); hi.setFixedSetup((getInt(h, "fixedSetup")) == 1); hi.setRestartType(getInt(h, "restartType")); hi.setTimeLimit(getInt(h, "timeLimit")); hi.setPasswordProtected((Boolean) h.get("pwdProtected")); hi.setFarmId(getInt(h, "farmId")); hi.setStatus(getInt(h, "status")); hi.setLoneQualifying((getInt(h, "loneQualify")) == 1); hi.setRollingStart((getInt(h, "rollingStarts")) == 1); hi.setNumberOfServersStarted(getInt(h, "numServersStarted")); JSONArray ff = (JSONArray) h.get("maxPercentFuelFills"); List<Integer> fuelList = new ArrayList<Integer>(); for (int j = 0; j < ff.size(); j++) { fuelList.add(((Long) ff.get(j)).intValue()); } // TODO: finish handling % fuel fills hi.setMinimumIrating(getInt(h, "minIR")); o.setHostedInfo(hi); } o.setStartTime(new Date(getLong(r, "start_time"))); o.setEventTypeId(getInt(r, "evttype")); o.setPrivateSessionId(getLong(r, "privatesessionid")); o.setSeasonId(getInt(r, "seasonid")); output.add(o); } } catch (ParseException ex) { Logger.getLogger(SpectatorSessionParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:gessi.ossecos.graph.GraphModel.java
public static void IStarJsonToGraphFile(String iStarModel, String layout, String typeGraph) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(iStarModel); JSONArray jsonArrayNodes = (JSONArray) jsonObject.get("nodes"); JSONArray jsonArrayEdges = (JSONArray) jsonObject.get("edges"); String modelType = jsonObject.get("modelType").toString(); // System.out.println(modelType); // System.out.println(jsonArrayNodes.toJSONString()); // System.out.println(jsonArrayEdges.toJSONString()); System.out.println(jsonObject.toJSONString()); Hashtable<String, String> nodesHash = new Hashtable<String, String>(); Hashtable<String, String> boundaryHash = new Hashtable<String, String>(); Hashtable<String, Integer> countNodes = new Hashtable<String, Integer>(); ArrayList<String> boundaryItems = new ArrayList<String>(); ArrayList<String> actorItems = new ArrayList<String>(); GraphViz gv = new GraphViz(); gv.addln(gv.start_graph());//from w w w .ja v a 2 s.c om String nodeType; String nodeName; String nodeBoundary; for (int i = 0; i < jsonArrayNodes.size(); i++) { jsonObject = (JSONObject) jsonArrayNodes.get(i); nodeName = jsonObject.get("name").toString().replace(" ", "_"); // .replace("(", "").replace(")", ""); nodeName = nodeName.replaceAll("[\\W]|`[_]", ""); nodeType = jsonObject.get("elemenType").toString(); nodeBoundary = jsonObject.get("boundary").toString(); // TODO: Verify type of diagram // if (!nodeType.equals("actor") & !nodeBoundary.equals("boundary")) // { if (countNodes.get(nodeName) == null) { countNodes.put(nodeName, 0); } else { countNodes.put(nodeName, countNodes.get(nodeName) + 1); nodeName += "_" + countNodes.put(nodeName, 0); } gv.addln(renderNode(nodeName, nodeType)); // } nodesHash.put(jsonObject.get("id").toString(), nodeName); boundaryHash.put(jsonObject.get("id").toString(), nodeBoundary); if (nodeType.equals("actor")) { actorItems.add(nodeName); } } String edgeType = ""; String source = ""; String target = ""; String edgeSubType = ""; int subgraphCount = 0; boolean hasCluster = false; nodeBoundary = "na"; String idSource; String idTarget; for (int i = 0; i < jsonArrayEdges.size(); i++) { jsonObject = (JSONObject) jsonArrayEdges.get(i); edgeSubType = jsonObject.get("linksubtype").toString(); edgeType = renderEdge(edgeSubType, jsonObject.get("linktype").toString()); idSource = jsonObject.get("source").toString(); idTarget = jsonObject.get("target").toString(); source = nodesHash.get(idSource); target = nodesHash.get(idTarget); if (!boundaryHash.get(idSource).toString().equals("boundary") && !boundaryHash.get(idTarget).toString().equals("boundary")) { if (!boundaryHash.get(idSource).toString().equals(nodeBoundary)) { nodeBoundary = boundaryHash.get(idSource).toString(); if (hasCluster) { gv.addln(gv.end_subgraph()); hasCluster = false; } else { hasCluster = true; } gv.addln(gv.start_subgraph(subgraphCount)); gv.addln(actorItems.get(subgraphCount++)); gv.addln("style=filled;"); gv.addln("color=lightgrey;"); } gv.addln(source + "->" + target + edgeType); } else { boundaryItems.add(source + "->" + target + edgeType); } } if (subgraphCount > 0) { gv.addln(gv.end_subgraph()); } for (String boundaryE : boundaryItems) { gv.addln(boundaryE); } gv.addln(gv.end_graph()); String type = typeGraph; // String type = "dot"; // String type = "fig"; // open with xfig // String type = "pdf"; // String type = "ps"; // String type = "svg"; // open with inkscape // String type = "png"; // String type = "plain"; String repesentationType = layout; // String repesentationType= "neato"; // String repesentationType= "fdp"; // String repesentationType= "sfdp"; // String repesentationType= "twopi"; // String repesentationType= "circo"; // //File out = new File("/tmp/out"+gv.getImageDpi()+"."+ type); // // Linux File out = new File("Examples/out." + type); // Windows gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type, repesentationType), out); }
From source file:currencyexchange.JSONCurrency.java
public static ArrayList<CurrencyUnit> getCurrencyUnitsJSON() { try {//from w w w . j a v a2 s . c om FileReader reader = new FileReader(filePath); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray currencyUnits = (JSONArray) jsonObject.get("units"); ArrayList<CurrencyUnit> currencies = new ArrayList<CurrencyUnit>(); Iterator i = currencyUnits.iterator(); while (i.hasNext()) { JSONObject e = (JSONObject) i.next(); CurrencyUnit currency = new CurrencyUnit((String) e.get("CountryCurrency"), (String) e.get("Units")); currencies.add(currency); } return currencies; } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException | NullPointerException ex) { ex.printStackTrace(); } return null; }