List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:edu.ucla.cs.scai.canali.webapp.PropertySearchServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w . j a v a 2s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebAppUtils.printParameters(this.getServletName(), request); response.setContentType("application/json;charset=UTF-8"); JsonParser jp = new JsonParser(); JsonArray ja = jp.parse(request.getParameter("s")).getAsJsonArray(); String label = null; String restrictedText; for (Iterator<JsonElement> it = ja.iterator(); it.hasNext();) { JsonObject jo = it.next().getAsJsonObject(); label = jo.get("l").getAsString(); restrictedText = jo.get("r").getAsString(); break; } String endpoint = request.getParameter("e"); String limitS = request.getParameter("l"); int limit = 100; try { limit = Integer.parseInt(limitS); } catch (Exception e) { } HashSet<String>[][] res = null; try { res = new TokenIndex().describeProperty(label, limit); } catch (Exception ex) { ex.printStackTrace(); res[0][0] = new HashSet<>(); res[0][0].add("Error"); res[0][1].add(ex.getMessage()); } Gson gson = new Gson(); try (PrintWriter out = response.getWriter()) { out.println(gson.toJson(res)); /* if ($_GET["callback"]) { $json_response = $_GET["callback"] . "(" . $json_response . }")"; */ } }
From source file:edu.ucla.cs.scai.canali.webapp.QueryServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www .j a v a 2 s . co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebAppUtils.printParameters(this.getServletName(), request); response.setContentType("application/json;charset=UTF-8"); JsonParser jp = new JsonParser(); JsonArray ja = jp.parse(request.getParameter("s")).getAsJsonArray(); ArrayList<AutocompleteObject> s = new ArrayList<>(); for (Iterator<JsonElement> it = ja.iterator(); it.hasNext();) { JsonObject jo = it.next().getAsJsonObject(); String state = jo.get("s").getAsString(); String labels = jo.get("l").getAsString(); String type = jo.get("k").getAsString(); String restrictedText = jo.get("r").getAsString(); String freeText = jo.has("f") ? jo.get("f").getAsString() : null; Integer relatedTokenPosition = null; try { relatedTokenPosition = jo.get("c").getAsInt(); } catch (Exception e) { } s.add(new AutocompleteObject(null, restrictedText, state, labels, type, null, relatedTokenPosition, false, freeText)); } String endpoint = request.getParameter("e"); String limitS = request.getParameter("l"); int limit = 100; try { limit = Integer.parseInt(limitS); } catch (Exception e) { } boolean disableSubclasses = false; try { disableSubclasses = request.getParameter("us").equals("false"); } catch (Exception e) { } ResultWrapper res = null; try { res = new QueryService().answerQuery(s, endpoint, limit, disableSubclasses); } catch (Exception ex) { ex.printStackTrace(); res = new ResultWrapper(null, ex.getMessage()); } Gson gson = new Gson(); try (PrintWriter out = response.getWriter()) { out.println(gson.toJson(res)); /* if ($_GET["callback"]) { $json_response = $_GET["callback"] . "(" . $json_response . }")"; */ } }
From source file:edu.ucla.cs.scai.canali.webapp.TranslationServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. ja va 2s .co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebAppUtils.printParameters(this.getServletName(), request); response.setContentType("application/json;charset=UTF-8"); JsonParser jp = new JsonParser(); JsonArray ja = jp.parse(request.getParameter("s")).getAsJsonArray(); ArrayList<AutocompleteObject> s = new ArrayList<>(); for (Iterator<JsonElement> it = ja.iterator(); it.hasNext();) { JsonObject jo = it.next().getAsJsonObject(); String state = jo.get("s").getAsString(); String labels = jo.get("l").getAsString(); String type = jo.get("k").getAsString(); String restrictedText = jo.get("r").getAsString(); String freeText = jo.get("r").getAsString(); Integer relatedTokenPosition = null; try { relatedTokenPosition = jo.get("c").getAsInt(); } catch (Exception e) { } s.add(new AutocompleteObject(null, restrictedText, state, labels, type, null, relatedTokenPosition, false, freeText)); } String endpoint = request.getParameter("e"); String limitS = request.getParameter("l"); int limit = 100; try { limit = Integer.parseInt(limitS); } catch (Exception e) { } boolean disableSubclasses = false; try { disableSubclasses = request.getParameter("us").equals("false"); } catch (Exception e) { } TranslationWrapper res = null; try { res = new TranslationService().translateQuery(s, endpoint, limit, disableSubclasses); } catch (Exception ex) { ex.printStackTrace(); res = new TranslationWrapper(ex.getMessage()); } Gson gson = new Gson(); try (PrintWriter out = response.getWriter()) { out.println(gson.toJson(res)); /* if ($_GET["callback"]) { $json_response = $_GET["callback"] . "(" . $json_response . }")"; */ } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void main(String[] args) { FileReader fr = null;/*from w w w . ja v a2 s . c o m*/ LineNumberReader lnr = null; FileOutputStream fos = null; FileWriter fw = null; FileWriter devOut = null; initialize(args); try { JsonArray jo = null; JsonParser jp = new JsonParser(); String softwareMetadataLocation = p.getProperty("software_info"); fr = new FileReader(softwareMetadataLocation); lnr = new LineNumberReader(fr); JsonElement je = jp.parse(fr); /* The file is an array of JSON objects, one per digital object */ jo = (JsonArray) je; //just want to make sure the "software-ontology-YYY-MM-DD" file write Elements in //the same order, so let's sort the JsonArray jo = sortForEasyValidation(jo); /* //Code used by Levander to validate that the input data (software metadata) //was identical between new version and old version... Gson gson = new GsonBuilder().setPrettyPrinting().create(); Writer fOut = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("orig-software"), "UTF-8")); fOut.write(gson.toJson((JsonElement) jo)); fOut.close(); */ Iterator<JsonElement> i; i = jo.iterator(); System.out.println(jo.size()); // this outer loop for iterator "i" processes one software/data service at a time while (i.hasNext()) { /* Get the next element in the array, which is the JSON object that represents a digital object. */ JsonElement ei = i.next(); JsonObject jo2 = (JsonObject) ei; /* Get the type attribute, and check its value. If it's neither software, nor data service, skip it. */ JsonElement typeElem = jo2.get("type"); String typeFragment = null; if (typeElem.isJsonPrimitive()) { JsonPrimitive typeValue = (JsonPrimitive) typeElem; String type = typeValue.getAsString(); if (type.equals("edu.pitt.isg.mdc.dats2_2.Dataset") || type.equals("edu.pitt.isg.mdc.dats2_2.DataStandard") || type.equals("edu.pitt.isg.mdc.dats2_2.DatasetWithOrganization")) continue; String[] typeFragments = type.split(Pattern.quote(".")); typeFragment = typeFragments[typeFragments.length - 1]; System.out.println("\n\nTYPE ATTRIBUTE HAS VALUE: " + typeFragment); } else { // else it's an error! System.err.println("Bad JSON - type element should be primitive."); } /* Now, the guts of the thing are in the "content" attribute, as a nested JSON object. */ JsonElement contentElem = jo2.get("content"); JsonObject contentObject = (JsonObject) contentElem; String subtype = null; JsonElement je3 = contentObject.get("subtype"); if (je3 == null) { subtype = typeFragment; } else if (je3.isJsonPrimitive()) { JsonPrimitive jprim = (JsonPrimitive) je3; subtype = jprim.getAsString(); } System.out.println("SUBTYPE. subtype=\"" + subtype + "\""); //System.out.println("\t"+ key + " is a " + subtype); baseName = ""; versionSuffix = ""; fullName = ""; versionNames = null; /* hostSpeciesIncluded diseaseCoverage isApolloEnabled executables webApplication sourceCodeRelease documentation source generalInfo title directory version userGuidesAndManuals license controlMeasures publicationsThatUsedRelease locationCoverage location developer publicationsAboutRelease isOlympus doi what's source vs. sourceCodeRelease */ Set<Map.Entry<String, JsonElement>> dtmAttSet = contentObject.entrySet(); Iterator<Map.Entry<String, JsonElement>> j = dtmAttSet.iterator(); HashSet<String> reqInds = new HashSet<String>(); while (j.hasNext()) { Map.Entry<String, JsonElement> ej = j.next(); String keyj = ej.getKey(); allDtmAtt.add(keyj); //System.out.println("\t\t" + keyj); if (keyj.equals("title")) { JsonElement jej = ej.getValue(); if (jej instanceof JsonPrimitive) { baseName = ((JsonPrimitive) jej).getAsString(); System.out.println("\t" + baseName + " is a " + subtype); } else { System.err.println("title key does not have primitive value"); throw new IllegalArgumentException( "title element may not be something other than primitive!"); } } else if (keyj.equals("version")) { JsonElement jej = ej.getValue(); if (jej instanceof JsonPrimitive) { /* versionNames = new String[1]; versionNames[0] = ((JsonPrimitive)jej).getAsString(); System.out.println("CAUTION: There are still version primitives!"); */ throw new IllegalArgumentException("Version element may not be primitive"); } else { //System.err.println("version key does not have primitive value"); //System.err.println("it's type is instead " + jej.getClass()); JsonArray versionArray = (JsonArray) jej; Iterator<JsonElement> vIter = versionArray.iterator(); versionNames = new String[versionArray.size()]; //System.out.println("VERSION COUNT: " + versionNames.length); int vIndex = 0; while (vIter.hasNext()) { JsonElement vElement = vIter.next(); //System.out.println("Version element is " + vElement.getClass()); if (vElement instanceof JsonPrimitive) { versionNames[vIndex++] = ((JsonPrimitive) vElement).getAsString(); //System.out.print(versionNames[vIndex-1] + ", "); } else { System.err.println("Version element is not primitive!!!"); } } } } HashSet<String> indsForKey = indsMap.get(keyj); if (indsForKey != null) { reqInds.addAll(indsForKey); //System.out.println("adding inds for key " + keyj); } } // end while (j.hasNext()) //System.out.println(); if ((baseName.contains("FluTE") || baseName.contains("NAADSM")) && versionNames.length > 1) { versionSuffix = ""; for (int iName = 0; iName < versionNames.length; iName++) { versionSuffix += versionNames[iName] + ((iName < versionNames.length - 1) ? ", " : ""); } } else if (baseName.contains("GLEAM") && versionNames.length > 1) { versionSuffix = ""; for (int iName = 0; iName < versionNames.length; iName++) { if (versionNames[iName].contains("Server")) { versionSuffix = versionNames[iName]; } } } else { versionSuffix = (versionNames != null) ? versionNames[0] : ""; } int cVersion = (versionNames != null) ? versionNames.length : 0; //System.out.println("Number of versions is : " + cVersion); //System.out.println("base name = " + baseName + ", version = " + version); String baseLabel = (versionNames == null) ? baseName : baseName + " - " + ((Character.isDigit(versionSuffix.charAt(0))) ? "v" + versionSuffix : versionSuffix); fullName = baseLabel; //System.out.println("FULLNAME: " + fullName); Iterator<String> k = reqInds.iterator(); //System.out.println("\t\t\treqInds.size() = " + reqInds.size()); IRI labelIri = iriMap.lookupAnnPropIri("editor preferred"); HashMap<String, OWLNamedIndividual> niMap = new HashMap<String, OWLNamedIndividual>(); while (k.hasNext()) { String ks = k.next(); IRI classIri = (ks.equals("dtm")) ? iriMap.lookupClassIri(subtype) : iriMap.lookupClassIri(ks); //System.out.println("\t\t\t'" + ks + "'\t" + classIri); String indLabel = fullName + " " + ((subtype.equals("MetagenomicAnalysis")) ? "metagenomic analysis" : subtype.substring(0, subtype.length() - 1)); indLabel = indLabel + ((ks.equals("dtm")) ? " software" : " " + ks); OWLNamedIndividual oni = createNamedIndividualWithTypeAndLabel(odf, oo, classIri, labelIri, indLabel); //if (ks.equals("dtm")) System.out.println("DTMINDLABEL: " + indLabel); if (ks.equals("dtm")) { addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("label"), fullName, odf, oo); OWLNamedIndividual mdcInd = odf.getOWLNamedIndividual(iriMap.lookupIndividIri("mdc")); /* Add all software objects to MDC. */ createOWLObjectPropertyAssertion(mdcInd, iriMap.lookupObjPropIri("has proper part"), oni, odf, oo); } if (ks.startsWith("simulat")) simPops.write(oni.getIRI() + "\t" + fullName + " " + ks + "\t" + fullName + "\n"); niMap.put(ks, oni); } // end while k.hasNext() //Once we've identified all the individuals we need, and we've created them, now we have to go back through // and stick stuff on the individuals j = dtmAttSet.iterator(); HashSet<String> locations = new HashSet<String>(); HashSet<String> pathogens = new HashSet<String>(); HashSet<String> hosts = new HashSet<String>(); boolean hasIdentifier = false; while (j.hasNext()) { Map.Entry<String, JsonElement> ej = j.next(); String keyj = ej.getKey(); if (keyj.equals("title")) { handleTitle(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("version")) { handleVersion(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("source")) { handleSource(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("license")) { handleLicense(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("doi")) { //this attribute appears to be obsolete. Identifier is used. handleDoi(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("sourceCodeRelease")) { handleSourceCodeRelease(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("generalInfo") || keyj.equals("humanReadableSynopsis")) { handleGeneralInfo(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("executables")) { handleExecutables(ej, niMap, oo, odf, iriMap); fullNameToExecutable.put(fullName, niMap.get("executable")); } else if (keyj.equals("webApplication")) { handleWebApplication(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("location") || keyj.equals("site") || keyj.equals("website")) { handleLocation(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("documentation") || keyj.startsWith("userGuides")) { handleDocumentation(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("developer") || keyj.equals("developers")) { handleDeveloper(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("publicationsThatUsedRelease")) { handlePublicationsThatUsedRelease(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("availableAt")) { handleAvailableAt(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("isUdsi") || keyj.equals("availableOnUdsi") || keyj.equals("availableViaUdsi") || keyj.equals("availableAtUids") || keyj.equals("availableOnUids") || keyj.equals("availableOnUIDS")) { OWLNamedIndividual executableInd = niMap.get("executable"); OWLNamedIndividual uidsConcInd = niMap.get("uidsConc"); JsonElement elem = ej.getValue(); String value = ((JsonPrimitive) elem).getAsString(); handleUids(value, 1, executableInd, uidsConcInd, iriMap, odf, oo); } else if (keyj.equals("availableOnOlympus") || keyj.equals("isOlympus") || keyj.equals("availableAtOlympus")) { OWLNamedIndividual executableInd = niMap.get("executable"); OWLNamedIndividual execConcInd = niMap.get("olympusConc"); JsonElement elem = ej.getValue(); String value = ((JsonPrimitive) elem).getAsString(); createOWLObjectPropertyAssertion(olympus, iriMap.lookupObjPropIri("bearer"), execConcInd, odf, oo); } else if (keyj.equals("controlMeasures")) { handleControlMeasures(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("dataInputFormats") || keyj.equals("dataInputFormat")) { handleDataInputFormats(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("dataOutputFormats")) { handleDataOutputFormats(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("publicationsAbout") || keyj.equals("publicationsAboutRelease")) { handlePublicationsAbout(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("identifier")) { handleIdentifier(ej.getValue(), niMap, oo, odf, iriMap, subtype); hasIdentifier = true; } else if (keyj.equals("grants")) { handleGrants(ej.getValue(), niMap, oo, odf, iriMap, subtype); } else if (keyj.equals("visualizationType")) { handleVisualizationType(ej.getValue(), niMap, oo, odf, iriMap, subtype); } /* Handle attributes specific to disease forecasters. It might be better just to connect all of them in batch at the end. */ else if (keyj.equals("diseases")) { handleDiseases(ej, niMap, oo, odf, iriMap); } else if (keyj.equals("region")) { handleRegion(ej, niMap, oo, odf, iriMap); } /* End attributes specific to disease forecasters */ else { /* Supposedly if we get here, then it's an attribute we don't know how to handle yet. However, inexplicably, we handle some still below and I'm still trying to figure out why I did that. Right now, it appears to be that we don't handle the attribute directly here in the code, but in a manual, post-processing step. */ boolean handled = false; /* Get the value of the attribute & report it out too. */ JsonElement jeRemainder = ej.getValue(); if (jeRemainder instanceof JsonPrimitive) { //If the value is primitive, it looks like we just eat it, which is odd. String value = ((JsonPrimitive) jeRemainder).getAsString(); } else if (jeRemainder instanceof JsonArray) { /* Otherwise if the value is an array, we get the array. We can handle array values above so not sure why I moved this code down here. */ JsonArray remArray = (JsonArray) jeRemainder; Iterator<JsonElement> remIter = remArray.iterator(); /* Iterate through the array, which is the value of the attribute we don't know about yet. */ while (remIter.hasNext()) { /* For the next element in the array... */ JsonElement remNext = remIter.next(); if (remNext instanceof JsonObject) { // If it is a JSON object, and the key is location coverage... JsonElement idElem = remNext.getAsJsonObject().get("identifier"); if (idElem == null) { System.out.println("WARNING: ignoring " + keyj + " attribute."); continue; } JsonElement valueElem = idElem.getAsJsonObject().get("identifierDescription"); if (valueElem == null) continue; String value = valueElem.getAsString(); if (keyj.equals("locationCoverage")) { //System.out.println("LOCATION: " + value); handled = true; if (!value.equals("N/A")) { /* Here, we just record the values of locations covered, we don't actually "handle" them in the sense of connecting the software or data service to them */ uniqueLocationsCovered.add(value); locations.add(value); } } else if (keyj.equals("diseaseCoverage") || keyj.equals("pathogenCoverage")) { handled = true; if (!value.equals("N/A")) { /* Same thing for disease/pathogen coverage. Just note the value, but we don't connect the software to the particular disease or pathogen in this code. */ uniquePathogensCovered.add(value); pathogens.add(value); } } else if (keyj.equals("hostSpeciesIncluded")) { handled = true; if (!value.equals("N/A")) { /* Same thing for host coverage. Just note the value, but we don't connect the software to the particular host in this code. */ uniqueHostsCovered.add(value); hosts.add(value); } } } else { /* If we get here, we have an array of things that are mere strings. The only attribute like this is the dataServiceDescriptor or something like that. */ System.err.println("NOTE: element " + keyj + " has array of values that are string. Ignoring."); } } } else { /* If we get here, we have neither a String value, nor an Array value, but an object value, for the key for which we don't know how to process */ //System.err.println("jeRemainder instanceof " + jeRemainder.getClass()); //System.err.println(jeRemainder); JsonObject remObject = (JsonObject) jeRemainder; Set<Map.Entry<String, JsonElement>> remEntrySet = remObject.entrySet(); for (Map.Entry<String, JsonElement> remEntryi : remEntrySet) { String key = remEntryi.getKey(); JsonElement remElem = remEntryi.getValue(); //System.err.println("\t" + key + " == " + remElem.isJsonPrimitive()); /* Identifier lives here, because we don't handle it above. But I think we just need to move it above and everything should still work fine if (key.equals("identifier")) { handleIdentifier(remElem, niMap, oo, odf, iriMap); } else {*/ System.out.println("WARNING: assuming that handling of " + key + " attribute in remainder will occur in manual, post-processing step. values " + remElem); //} } } if (!handled && !keyj.equals("subtype") && !attributesHandledInPostprocessing.contains(keyj)) { //} && !keyj.equals("identifier")) { System.out.println("WARNING: assuming that handling of " + keyj + " attribute will occur in manual, post-processing step. values " + ej.getValue()); if (keyj.equals("publicationsAboutRelease")) { //System.out.println("PUB ABOUT: " + ej.getValue()); } } //} } // end while (j.hasNext()) } //Now, we need to connect up all the individuals connectDtmIndividuals(niMap, oo, odf, iriMap); //System.out.println(locations.size()); //System.out.println(pathogens.size()); //System.out.println(hosts.size()); ArrayList<String> popsForThisDtm = new ArrayList<String>(); for (String loci : locations) { for (String path : pathogens) { String pop = path + " in region of " + loci; populationsNeeded.add(pop); popsForThisDtm.add(pop); //System.out.println(pop); } for (String host : hosts) { String pop = host + " in region of " + loci; populationsNeeded.add(pop); popsForThisDtm.add(pop); //System.out.println(pop); } } popsNeededByDtm.put(fullName, popsForThisDtm); handleSimInds(niMap, oo, odf, iriMap); if (!hasIdentifier) { identifierToOwlIndividual.put(baseName, niMap.get("dtm")); System.out.println("BASE NAME IS: " + baseName); if (subtype.contains("forecaster")) forecasterIds.add(baseName); //System.out.println("hashing individual with baseName=" + baseName + ", other info is " + // "baseLabel=" + baseLabel + ", fullName=" + fullName + ", versionSuffix=" + versionSuffix); } try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String dateTxt = df.format(new Date()); String owlFileName = "software-ontology-" + dateTxt + ".owl"; fos = new FileOutputStream(owlFileName); oom.saveOntology(oo, fos); } catch (OWLOntologyStorageException oose) { oose.printStackTrace(); } } /* while(i.hasNext()). i is iterating over settings plus the main payload, which is all the software apps and data services. In new JSON retrieved by API, there are no settings any longer */ /* This code merely iterates over all the attributes specified by all the software and data services collectively, and prints them out. It's handy to have a complete list of everything used. */ Iterator<String> si = allDtmAtt.iterator(); while (si.hasNext()) { System.out.println(si.next()); } /* This code displays all the geographical regions encountered across all software and data services. */ System.out.println("Locations required:"); for (String location : uniqueLocationsCovered) { System.out.println("\t" + location); } System.out.println(); /* This code displays all the pathogens encountered across all sofware and data services. */ System.out.println("Pathogens required:"); for (String pathogen : uniquePathogensCovered) { System.out.println("\t" + pathogen); } System.out.println(); /* This code displays all the hosts encountered across all software and data services. */ System.out.println("Hosts required: "); for (String host : uniqueHostsCovered) { System.out.println("\t" + host); } System.out.println(); /* This code displays all the pathogen+geographical region and host+geographical region combinations required. */ System.out.println("Populations required: "); for (String pop : populationsNeeded) { System.out.println("\t" + pop); } System.out.println(); /* This code writes to a file all the populations (host and pathogen) that are required for each DTM. */ fw = new FileWriter("./pops_by_dtm.txt"); int iPop = 1; Set<String> dtmsWithPops = popsNeededByDtm.keySet(); for (String dtm : dtmsWithPops) { ArrayList<String> popsNeeded = popsNeededByDtm.get(dtm); for (String pop : popsNeeded) { System.out.println(iPop + "\t" + dtm + "\t" + pop); fw.write(iPop + "\t" + dtm + "\t" + pop + "\n"); iPop++; } } /* This code outputs all the IRIs that were assigned to individuals created to represent developers of software and data services. */ devOut = new FileWriter("./developer_iris.txt"); Set<String> devs = devNis.keySet(); for (String dev : devs) { OWLNamedIndividual devInd = devNis.get(dev); devOut.write(dev + "\t" + devInd.getIRI() + "\n"); if (dev.equals("Shawn T. Brown")) devOut.write("Shawn Brown\t" + devInd.getIRI() + "\n"); if (dev.contains("Bill")) { String devAlt = dev.replace("Bill", "William"); devOut.write(devAlt + "\t" + devInd.getIRI() + "\n"); } } devOut.close(); /* This code displays all the unique control measures encountered across all DTMs. */ System.out.println("Control measures:"); for (String cm : uniqueCms) { System.out.println(cm); } /* This code combines all the input/output formats into a single, unique list. */ uniqueFormats.addAll(uniqueInputFormats); uniqueFormats.addAll(uniqueOutputFormats); /* Display all the unique input formats encountered */ System.out.println("\nInput formats:"); for (String input : uniqueInputFormats) { System.out.println("\t" + input); } /* Display all the unique output formats encountered */ System.out.println("\nOutput formats:"); for (String output : uniqueOutputFormats) { System.out.println("\t" + output); } /* Display the entire list of unique formats across all input & output */ System.out.println("\nAll formats:"); for (String format : uniqueFormats) { System.out.println("\t" + format); } /* Process manually curated disease forecaster attribute info, including diseases locationCoverage (used to be called 'region') forecasts forecastFrequency */ processForecasterInfo(); processPathogenEvolutionModelInfo(); processPopulationDynamicsModelInfo(); processDiseaseTransmissionTreeEstimatorInfo(); try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String dateTxt = df.format(new Date()); String owlFileName = "software-ontology-" + dateTxt + ".owl"; fos = new FileOutputStream(owlFileName); oom.saveOntology(oo, fos); } catch (OWLOntologyStorageException oose) { oose.printStackTrace(); } /* This code helpfully prints out where the program left off with IRI generation, so that any other programs needing to pick up where this one left off can do so. */ System.out.println(nextSimPopIri()); System.out.println(nextSimPopIri()); System.out.println(nextIri()); System.out.println(nextIri()); } catch (IOException ioe) { ioe.printStackTrace(); } catch (JsonIOException jioe) { jioe.printStackTrace(); } catch (JsonSyntaxException jse) { jse.printStackTrace(); } finally { try { /* Close everything down */ if (fw != null) fw.close(); if (fos != null) fos.close(); if (lnr != null) lnr.close(); if (fr != null) fr.close(); if (simPops != null) simPops.close(); if (devOut != null) devOut.close(); } catch (IOException ioe) { //just eat it, eat it, don't you make me repeat it! //Strangely, this is the correct thing to do in this situation: yay, java! } } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleGrants(JsonElement elem, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap, String subtype) { /*// w ww. java 2 s. c o m The value of the grants element is a JsonArray. Each item in the array is a simple value. */ if (elem instanceof JsonArray) { JsonArray ja = (JsonArray) elem; Iterator<JsonElement> i = ja.iterator(); while (i.hasNext()) { JsonElement elemi = i.next(); String granti = ((JsonPrimitive) elemi).getAsString(); /* Get the named individual for string granti from the HashMap that holds the mapping. This individual is the research process that realizes the plan in the grant proposal text. This process has as part the codewriting of the software, is our assumption. */ OWLNamedIndividual grantResearchInd = grantTxtToIndividual.get(granti); OWLNamedIndividual codeWritingInd = niMap.get("codewriting"); createOWLObjectPropertyAssertion(codeWritingInd, iriMap.lookupObjPropIri("is part of"), grantResearchInd, odf, oo); } } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleVisualizationType(JsonElement elem, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap, String subtype) { // The value of the visualizationType attribute is a JsonArray. if (elem instanceof JsonArray) { JsonArray ja = (JsonArray) elem; Iterator<JsonElement> i = ja.iterator(); while (i.hasNext()) { JsonElement elemi = i.next(); String visualizationType = ((JsonPrimitive) elemi).getAsString(); /*/*ww w .jav a 2 s . c o m*/ Get the executing of the software individual */ OWLNamedIndividual executionInd = niMap.get("executionof"); /* Create the time series data set individual. The executing has specified input the dataset. */ OWLNamedIndividual tsDataSet = createNamedIndividualWithTypeAndLabel( iriMap.lookupClassIri("time series data set"), iriMap.lookupAnnPropIri("editor preferred"), "time series data set input into " + fullName); addAnnotationToIndividual(tsDataSet, iriMap.lookupAnnPropIri("label"), visualizationType, odf, oo); createOWLObjectPropertyAssertion(executionInd, iriMap.lookupObjPropIri("has specified input"), tsDataSet, odf, oo); /* Create the diagram individual. The executing has specified output the diagram. */ OWLNamedIndividual diagram = createNamedIndividualWithTypeAndLabel(iriMap.lookupClassIri("diagram"), iriMap.lookupAnnPropIri("editor preferred"), "diagram output by " + fullName); createOWLObjectPropertyAssertion(executionInd, iriMap.lookupObjPropIri("has specified output"), diagram, odf, oo); } } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleExecutables(Map.Entry<String, JsonElement> e, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap) { //get the executable individual we already created OWLNamedIndividual execInd = niMap.get("executable"); //get the compiling process individual we already created OWLNamedIndividual compInd = niMap.get("compiling"); //get the preferred term from the executable individual String execIndPrefTerm = getAnnotationValueFromNamedIndividual(execInd, iriMap.lookupAnnPropIri("editor preferred"), oo); //get the preferred term from the compiling individual String compIndPrefTerm = getAnnotationValueFromNamedIndividual(execInd, iriMap.lookupAnnPropIri("editor preferred"), oo); /*// w w w . jav a2 s .co m There actually might be multiple executables, which we don't really know until we get here */ JsonElement je = e.getValue(); if (je instanceof JsonArray) { JsonArray elemArray = (JsonArray) je; Iterator<JsonElement> elemIter = elemArray.iterator(); String[] execs = new String[elemArray.size()]; int iExec = 0; /* Accumulate all the values for the executable attribute. The values are always in a JSON array, even if there's only one value. */ while (elemIter.hasNext()) { JsonElement elemi = elemIter.next(); String value = ((JsonPrimitive) elemi).getAsString(); execs[iExec++] = value; } /* So we have to create new individuals for the additional executables if there are more than two, and new compiling process individuals. We assume that each executable is the result of a different compiling process, although it is conceivable that one big "build" process could create all of them. We just don't know. */ ArrayList<OWLNamedIndividual> execNis = new ArrayList<OWLNamedIndividual>(); ArrayList<OWLNamedIndividual> compNis = new ArrayList<OWLNamedIndividual>(); String labelPrefix = ""; if (execs[0].contains("<a ")) { /* We often get URLs embedded in <a href= with a text value, so parse all that out of the HTML */ Document d = Jsoup.parse(execs[0]); Elements links = d.select("a"); String url = links.get(0).attr("href"); String txt = links.get(0).ownText(); addAnnotationToIndividual(execInd, iriMap.lookupAnnPropIri("hasURL"), url, odf, oo); addAnnotationToIndividual(execInd, iriMap.lookupAnnPropIri("label"), txt, odf, oo); } else { //otherwise, if the executable value is not html, just put whatever is in there on as a URL. if (execs[0].startsWith("http")) { addAnnotationToIndividual(execInd, iriMap.lookupAnnPropIri("hasURL"), execs[0], odf, oo); } else { addAnnotationToIndividual(execInd, iriMap.lookupAnnPropIri("label"), execs[0], odf, oo); } } //execNis.add(oni); //System.err.println("there are " + execs.length + " executables"); if (execs.length > 1) { for (int i = 1; i < execs.length; i++) { if (execs[i].trim().startsWith("<a ")) { Document d = Jsoup.parse(execs[i]); Elements links = d.select("a"); String url = links.get(0).attr("href"); String txt = links.get(0).ownText(); String newExecIndPrefTerm = execIndPrefTerm + " " + txt; String newCompIndPrefTerm = "compiling to " + newExecIndPrefTerm; OWLNamedIndividual execi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("executable"), iriMap.lookupAnnPropIri("label"), txt); OWLNamedIndividual compi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("compiling"), iriMap.lookupAnnPropIri("editor preferred"), newCompIndPrefTerm); addAnnotationToIndividual(execi, iriMap.lookupAnnPropIri("hasURL"), url, odf, oo); addAnnotationToIndividual(execi, iriMap.lookupAnnPropIri("editor preferred"), newExecIndPrefTerm, odf, oo); execNis.add(execi); compNis.add(compi); } else { String newExecIndPrefTerm = execIndPrefTerm + " " + execs[i]; String newCompIndPrefTerm = "compiling to " + newExecIndPrefTerm; OWLNamedIndividual execi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("executable"), iriMap.lookupAnnPropIri("editor preferred"), newExecIndPrefTerm); OWLNamedIndividual compi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("compiling"), iriMap.lookupAnnPropIri("editor preferred"), newCompIndPrefTerm); if (execs[i].startsWith("http")) { addAnnotationToIndividual(execi, iriMap.lookupAnnPropIri("hasURL"), execs[i].trim(), odf, oo); } else { addAnnotationToIndividual(execi, iriMap.lookupAnnPropIri("label"), execs[i].trim(), odf, oo); } execNis.add(execi); compNis.add(compi); } } } //Some of the values for executables attribute is an html link to the documentation with link text. In that case // put the link on the executable individual with hasURL annotation, and put the link // text on that individual as an rdfs:label annotation. for (int i = 0; i < execNis.size(); i++) { OWLNamedIndividual execi = execNis.get(i); OWLNamedIndividual compi = compNis.get(i); String execKey = "executable" + i; String compKey = "compiling" + i; niMap.put(execKey, execi); niMap.put(compKey, compi); } } else { System.err.println("Executables attribute has value that is not array."); throw new IllegalArgumentException("executables must be an array and isn't"); } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleWebApplication(Map.Entry<String, JsonElement> e, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap) { OWLNamedIndividual oni = niMap.get("webexecutionof"); JsonElement je = e.getValue();//from w w w.j a va2 s . c o m if (je instanceof JsonArray) { JsonArray elemArray = (JsonArray) je; Iterator<JsonElement> elemIter = elemArray.iterator(); //System.out.println("Web application size: " + elemArray.size()); while (elemIter.hasNext()) { JsonElement elemi = elemIter.next(); String value = ((JsonPrimitive) elemi).getAsString(); //value is just a URL so slap it on the web execution of dtm individual addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("hasURL"), value, odf, oo); } } else { System.err.println("Web application attribute has value that is not primitive."); throw new IllegalArgumentException("Web application attribute must be array."); } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleDocumentation(Map.Entry<String, JsonElement> e, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap) { OWLNamedIndividual oni = niMap.get("documentation"); JsonElement je = e.getValue();//ww w.j a va 2 s. com if (je instanceof JsonPrimitive) { String value = ((JsonPrimitive) je).getAsString(); //Some of the documentation is an html link to the documentation with link text. In that case // put the link on the documentation individual with hasURL annotation, and put the link // text on that individual as an rdfs:label annotation. if (value.startsWith("<a ")) { Document d = Jsoup.parse(value); Elements links = d.select("a"); String url = links.get(0).attr("href"); String txt = links.get(0).ownText(); //System.out.println("URL IS " + url + " AND TEXT IS " + txt); addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("hasURL"), url, odf, oo); addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("label"), txt, odf, oo); } else { //otherwise, if the documentation value is not an <a href=... construct then if it starts with http:/// add as URL otherwise, add as label if (value.startsWith("http:")) addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("hasURL"), value, odf, oo); else addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("label"), value, odf, oo); } } else if (je instanceof JsonArray) { JsonArray ja = (JsonArray) je; //System.out.println("DOCUMENTATION SIZE = " + ja.size()); Iterator<JsonElement> elemIter = ja.iterator(); while (elemIter.hasNext()) { JsonElement elemi = elemIter.next(); int iDoc = 1; if (elemi instanceof JsonPrimitive) { String value = ((JsonPrimitive) elemi).getAsString(); //Some of the documentation is an html link to the documentation with link text. In that case // put the link on the documentation individual with hasURL annotation, and put the link // text on that individual as an rdfs:label annotation. if (value.startsWith("<a ")) { Document d = Jsoup.parse(value); Elements links = d.select("a"); String url = links.get(0).attr("href"); String txt = links.get(0).ownText(); //System.out.println("URL IS " + url + " AND TEXT IS " + txt); addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("hasURL"), url, odf, oo); addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("label"), txt, odf, oo); } else { //otherwise, if the documentation value is not html, just put whatever is in there on as a URL. addAnnotationToIndividual(oni, iriMap.lookupAnnPropIri("hasURL"), value, odf, oo); } } else { throw new IllegalArgumentException( "entry in list of documentation is not primitive, but should be"); } iDoc++; if (elemIter.hasNext()) oni = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("documentation"), iriMap.lookupAnnPropIri("editor preferred"), baseName + " documentation " + iDoc); } } else { System.err.println("Documentation attribute has value that is not array!."); } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
public static void handleDeveloper(Map.Entry<String, JsonElement> e, HashMap<String, OWLNamedIndividual> niMap, OWLOntology oo, OWLDataFactory odf, IriLookup iriMap) { /*// ww w . j av a 2 s .c o m We connect developers to the software through the process of writing it, so we have both the developer individual and the codewriting individual. */ OWLNamedIndividual devInd = niMap.get("developer"); OWLNamedIndividual wrtInd = niMap.get("codewriting"); JsonElement je = e.getValue(); if (je instanceof JsonPrimitive) { /* This should no longer happen. In early version of the JSON, occasionally the developers were a primitive value and multiple developers names were separated by commas. */ String value = ((JsonPrimitive) je).getAsString(); String[] devs = (value.contains(";")) ? value.split(Pattern.quote(";")) : value.split(Pattern.quote(",")); //System.out.println("There are " + devs.length + " developers:"); //Because this situation shouldn't happen any more, report it out as an error: System.err.println("Developer attribute has value that is primitive."); } else { /* This is what we expect: developer values are in JsonArray even if just one. If there's no developers specified by JSON, then we shouldn't even have the attribute. */ JsonArray devArray = (JsonArray) je; String[] devs = new String[devArray.size()]; Iterator<JsonElement> devIter = devArray.iterator(); int iDev = 0; while (devIter.hasNext()) { JsonElement devElement = devIter.next(); devs[iDev++] = ((JsonPrimitive) devElement).getAsString(); } //ArrayList<OWLNamedIndividual> devNis = new ArrayList<OWLNamedIndividual>(); //devNis.add(devInd); String[] devNames = new String[devs.length]; for (int i = 0; i < devs.length; i++) { //System.out.println("devs[i] = " + devs[i]); if (devs[i].trim().startsWith("<a")) { Document d = Jsoup.parse(devs[i]); Elements links = d.select("a"); String url = links.get(0).attr("href"); String txt = links.get(0).ownText(); devNames[i] = txt.trim(); //System.out.println("developer name = " + devNames[i] + "\t" + txt); //System.out.println("developer href = " + url + "\t" + url); OWLNamedIndividual devi = null; if (!devNis.containsKey(devNames[i])) { devi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("developer"), iriMap.lookupAnnPropIri("label"), devNames[i]); OWLNamedIndividual lpri = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("legalpersonrole"), iriMap.lookupAnnPropIri("label"), "legal person role of " + devNames[i]); createOWLObjectPropertyAssertion(devi, iriMap.lookupObjPropIri("bearer"), lpri, odf, oo); devNis.put(devNames[i], devi); } else { devi = devNis.get(devNames[i]); } addAnnotationToIndividual(devi, iriMap.lookupAnnPropIri("editor preferred"), devNames[i] + ", developer of " + fullName, odf, oo); OWLNamedIndividual emailInd = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("email address"), iriMap.lookupAnnPropIri("label"), url); createOWLObjectPropertyAssertion(emailInd, iriMap.lookupObjPropIri("is contact information about"), devi, odf, oo); createOWLObjectPropertyAssertion(wrtInd, iriMap.lookupObjPropIri("has active participant"), devi, odf, oo); } else { devNames[i] = devs[i].trim(); OWLNamedIndividual devi = null; if (!devNis.containsKey(devNames[i])) { devi = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("developer"), iriMap.lookupAnnPropIri("label"), devNames[i]); OWLNamedIndividual lpri = createNamedIndividualWithTypeAndLabel(odf, oo, iriMap.lookupClassIri("legalpersonrole"), iriMap.lookupAnnPropIri("label"), "legal person role of " + devNames[i]); createOWLObjectPropertyAssertion(devi, iriMap.lookupObjPropIri("bearer"), lpri, odf, oo); devNis.put(devNames[i], devi); } else { devi = devNis.get(devNames[i]); } createOWLObjectPropertyAssertion(wrtInd, iriMap.lookupObjPropIri("has active participant"), devi, odf, oo); addAnnotationToIndividual(devi, iriMap.lookupAnnPropIri("editor preferred"), devNames[i] + ", developer of " + fullName, odf, oo); } //System.out.println(i); } } }