Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:de.azapps.mirakel.model.task.TaskDeserializer.java

License:Open Source License

private static void handleAdditionalEntries(final Task t, final String key, final JsonElement val) {
    if (val.isJsonPrimitive()) {
        final JsonPrimitive p = (JsonPrimitive) val;
        if (p.isBoolean()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsBoolean()));
        } else if (p.isNumber()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsInt()));
        } else if (p.isJsonNull()) {
            t.addAdditionalEntry(key, "null");
        } else if (p.isString()) {
            t.addAdditionalEntry(key, '"' + val.getAsString() + '"');
        } else {/*ww  w . j ava2  s. c  om*/
            Log.w(TAG, "unknown json-type");
        }
    } else if (val.isJsonArray()) {
        final JsonArray a = (JsonArray) val;
        StringBuilder s = new StringBuilder("[");
        boolean first = true;
        for (final JsonElement e : a) {
            if (e.isJsonPrimitive()) {
                final JsonPrimitive p = (JsonPrimitive) e;
                final String add;
                if (p.isBoolean()) {
                    add = String.valueOf(p.getAsBoolean());
                } else if (p.isNumber()) {
                    add = String.valueOf(p.getAsInt());
                } else if (p.isString()) {
                    add = '"' + p.getAsString() + '"';
                } else if (p.isJsonNull()) {
                    add = "null";
                } else {
                    Log.w(TAG, "unknown json-type");
                    break;
                }
                s.append(first ? "" : ",").append(add);
                first = false;
            } else {
                Log.w(TAG, "unknown json-type");
            }
        }
        t.addAdditionalEntry(key, s + "]");
    } else {
        Log.w(TAG, "unknown json-type");
    }
}

From source file:de.csdev.ebus.cfg.std.EBusValueJsonDeserializer.java

License:Open Source License

@Override
public List<EBusValueDTO> deserialize(JsonElement jElement, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonArray asJsonArray = jElement.getAsJsonArray();
    ArrayList<EBusValueDTO> result = new ArrayList<EBusValueDTO>();

    ArrayList<String> fields = new ArrayList<String>();
    for (Field field : EBusValueDTO.class.getDeclaredFields()) {
        SerializedName annotation = field.getAnnotation(SerializedName.class);

        if (annotation != null) {
            fields.add(annotation.value());

        } else {//from   w  ww . j  av a 2  s  .c o m
            fields.add(field.getName());
        }
    }

    for (JsonElement jsonElement : asJsonArray) {
        JsonObject jObject = jsonElement.getAsJsonObject();
        EBusValueDTO valueDTO = context.deserialize(jObject, EBusValueDTO.class);

        for (Entry<String, JsonElement> entry : jObject.entrySet()) {
            if (!fields.contains(entry.getKey())) {

                if (entry.getValue().isJsonPrimitive()) {
                    JsonPrimitive primitive = (JsonPrimitive) entry.getValue();

                    if (primitive.isNumber()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsBigDecimal());

                    } else if (primitive.isBoolean()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsBoolean());

                    } else if (primitive.isString()) {
                        valueDTO.setProperty(entry.getKey(), primitive.getAsString());
                    }

                } else {
                    valueDTO.setProperty(entry.getKey(), entry.getValue().getAsString());

                }

            }
        }

        result.add(valueDTO);
    }

    return result;
}

From source file:de.innovationgate.wgpublisher.webtml.utils.JsonUtils.java

License:Open Source License

public Object jsonToJava(JsonElement jsonValue) {
    Object value = null;/*from w w w  .  j av  a 2s.  c  o  m*/
    if (jsonValue.isJsonNull()) {
        value = null;
    } else if (jsonValue.isJsonPrimitive()) {
        JsonPrimitive prim = (JsonPrimitive) jsonValue;
        if (prim.isNumber()) {
            value = prim.getAsDouble();
        } else if (prim.isBoolean()) {
            value = prim.getAsBoolean();
        } else {
            value = prim.getAsString();
        }
        value = jsonToJavaConversions(value);
    } else if (jsonValue.isJsonArray()) {
        JsonArray array = jsonValue.getAsJsonArray();
        List<Object> list = new ArrayList<Object>();
        for (JsonElement element : array) {
            list.add(jsonToJava(element));
        }
    } else if (jsonValue.isJsonObject()) {
        JsonObject obj = jsonValue.getAsJsonObject();
        Map<String, Object> map = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            map.put(String.valueOf(entry.getKey()), jsonToJava(entry.getValue()));
        }
    }

    return value;
}

From source file:de.sub.goobi.helper.HelperSchritte.java

License:Open Source License

private void replaceJsonElement(JsonElement jel, VariableReplacer replacer) {
    if (jel.isJsonObject()) {
        JsonObject obj = jel.getAsJsonObject();
        for (Entry<String, JsonElement> objEntry : obj.entrySet()) {
            if (objEntry.getValue().isJsonPrimitive()) {
                JsonPrimitive jPrim = objEntry.getValue().getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    obj.addProperty(objEntry.getKey(), newVal);
                }//from  w w w  . ja  v a2 s  .c  o m
            } else {
                replaceJsonElement(objEntry.getValue(), replacer);
            }
        }
    } else if (jel.isJsonArray()) {
        JsonArray jArr = jel.getAsJsonArray();
        for (int i = 0; i < jArr.size(); i++) {
            JsonElement innerJel = jArr.get(i);
            if (innerJel.isJsonPrimitive()) {
                JsonPrimitive jPrim = innerJel.getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    jArr.set(i, new JsonPrimitive(newVal));
                }
            } else {
                replaceJsonElement(innerJel, replacer);
            }
        }
    }

}

From source file:devicemodel.conversions.JsonConversions.java

public static DeviceNode gsonToNode(String name, JsonObject e) {
    DeviceNode n = new DeviceNode(name);

    Iterator<Map.Entry<String, JsonElement>> iterator = e.entrySet().iterator();

    while (iterator.hasNext()) {

        Map.Entry<String, JsonElement> next = iterator.next();

        if (next.getKey().equals("value")) {
            JsonPrimitive val = next.getValue().getAsJsonPrimitive();

            n.setValue(val.getAsString());
        } else if (next.getKey().equals("attributes")) {
            JsonObject att = (JsonObject) next.getValue();

            Iterator<Map.Entry<String, JsonElement>> attributes = att.entrySet().iterator();

            while (attributes.hasNext()) {
                Map.Entry<String, JsonElement> a = attributes.next();

                n.addAttribute(a.getKey(), a.getValue().getAsString());
            }//from  w  w w.  j  av a2s. c  o  m
        } else {
            try {
                n.addChild(gsonToNode(next.getKey(), (JsonObject) next.getValue()));
            } catch (Exception ex) {
            }
        }
    }

    return n;
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

private static void addConstraints(Template tpl, String json) {
    JsonElement el = new JsonParser().parse(json);
    for (JsonElement tel : el.getAsJsonArray()) {
        JsonObject triple = tel.getAsJsonObject();
        String subj = triple.getAsJsonObject("subject").get("id").getAsString();
        String pred = triple.getAsJsonObject("predicate").get("id").getAsString();
        JsonObject objitem = triple.getAsJsonObject("object");
        if (objitem.get("value") != null && objitem.get("isLiteral").getAsBoolean()) {
            JsonPrimitive obj = objitem.get("value").getAsJsonPrimitive();
            String objtype = objitem.get("type") != null ? objitem.get("type").getAsString() : null;
            tpl.getConstraintEngine().createNewDataConstraint(subj, pred,
                    obj.isString() ? obj.getAsString() : obj.toString(), objtype);
        } else {//from w w  w .  j  a v a  2s  .  co  m
            String obj = objitem.get("id").getAsString();
            tpl.getConstraintEngine().createNewConstraint(subj, pred, obj);
        }
    }
}

From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java

License:Open Source License

public static void main(String[] args) {
    FileReader fr = null;//from w  ww  .  j a 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.washington.iam.tools.netact.NetactDNSVerifier.java

License:Apache License

/**
 * Test if a user has ownership of a domain
 *
 * @param id user's uwnetid/*from   w  ww. j  a v a2s  . co m*/
 * @param domain to test
 * @param return list of owners (can be null)
 */

public boolean isOwner(String dns, String id, List<String> owners) throws DNSVerifyException {

    boolean isOwner = false;
    if (id == null)
        id = "";
    log.debug("looking for owner (" + id + ") in " + dns);

    try {
        String[] urls = { hostUrl, domainUrl };
        for (String url : urls) {
            String respString = webClient.simpleRestGet(url + dns);
            // log.debug("got: " + respString);

            JsonParser parser = new JsonParser();
            JsonElement ele = parser.parse(respString);
            if (ele.isJsonObject()) {
                JsonObject resp = ele.getAsJsonObject();
                if (resp.get("table").isJsonObject()) {
                    JsonObject tbl = resp.getAsJsonObject("table");
                    if (tbl.get("row").isJsonArray()) {
                        JsonArray ids = tbl.getAsJsonArray("row");
                        for (int i = 0; i < ids.size(); i++) {
                            JsonObject idi = ids.get(i).getAsJsonObject();
                            JsonPrimitive oidu = idi.getAsJsonPrimitive("uwnetid");
                            if (oidu == null)
                                continue;
                            String oid = oidu.getAsString();
                            if (oid.equals(id)) {
                                if (owners == null)
                                    return true; // done
                                isOwner = true;
                            }
                            if (owners != null && !owners.contains(oid))
                                owners.add(oid);
                        }
                    } else {
                        String oid = tbl.getAsJsonObject("row").getAsJsonPrimitive("uwnetid").getAsString();
                        if (oid.equals(id)) {
                            if (owners == null)
                                return true; // done
                            isOwner = true;
                        }
                        if (owners != null && !owners.contains(oid))
                            owners.add(oid);
                    }
                }
            }
        }

    } catch (Exception e) {
        log.debug("netact dns lookup error: " + e);
        throw new DNSVerifyException(e.getMessage() + " : " + e.getCause());
    }

    // do substrings too
    dns = dns.replaceFirst("[^\\.]+\\.", "");
    // log.debug("do substrings: " + dns);
    int p = dns.indexOf(".");
    if (p > 0) {
        if (isOwner(dns, id, owners)) {
            if (owners == null)
                return true; // done
            isOwner = true;
        }
    }
    return isOwner;
}

From source file:fr.zcraft.MultipleInventories.snaphots.ItemStackSnapshot.java

License:Open Source License

/**
 * From a JSON element, constructs a data structure representing
 * the same structure (recursively) using native types.
 *
 * <p>We had to re-implement this to ensure the generated structure to have the
 * right data type (instead of all numbers being doubles) and precision.</p>
 *
 * @param element The json element to be decoded.
 * @return A native data structure (either a {@link Map Map&lt;String, Object&gt;},
 * a {@link List List&lt;Object&gt;}, or a native type) representing the same
 * structure (recursively).//  www .j a v a  2s .  c  o  m
 *
 * @see #jsonToNative(JsonObject) Converts a json object to an explicit {@link Map}.
 * The JavaDoc also contains explainations on why this is needed.
 */
private static Object jsonToNative(final JsonElement element) {
    if (element.isJsonObject()) {
        return jsonToNative(element.getAsJsonObject());
    } else if (element.isJsonArray()) {
        final List<Object> list = new ArrayList<>();

        element.getAsJsonArray().forEach(listElement -> {
            final Object nativeValue = jsonToNative(listElement);

            if (nativeValue != null) {
                list.add(nativeValue);
            }
        });

        return list;
    } else if (element.isJsonPrimitive()) {
        final JsonPrimitive primitive = element.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else /* it's a number we yet have to find the type. */
        {
            final BigDecimal number = primitive.getAsBigDecimal();

            try {
                return number.byteValueExact();
            } catch (final ArithmeticException e1) {
                try {
                    return number.shortValueExact();
                } catch (final ArithmeticException e2) {
                    try {
                        return number.intValueExact();
                    } catch (final ArithmeticException e3) {
                        try {
                            return number.longValueExact();
                        } catch (final ArithmeticException e4) {
                            try {
                                return number.doubleValue();
                            } catch (final ArithmeticException | NumberFormatException e5) {
                                return number;
                            }
                        }
                    }
                }
            }
        }
    }

    // Else the element is null.
    return null;
}

From source file:gsonlib.GsonTransfer.java

public static void transferJsonResponseParamMap(JsonObject inJson, JsonObject outJson,
        Map<String, String> ctxMap) {

    Set<Map.Entry<String, JsonElement>> inJsonEntrySet = inJson.entrySet();

    for (Map.Entry<String, JsonElement> inJsonEntry : inJsonEntrySet) {
        String inJsonEntryKey = inJsonEntry.getKey();
        JsonElement inJsonEntryValue = inJsonEntry.getValue();

        JsonElement outJsonEntryValue = outJson.get(inJsonEntryKey);

        if (outJsonEntryValue != null) {
            if (inJsonEntryValue.isJsonPrimitive() && outJsonEntryValue.isJsonPrimitive()) {
                JsonPrimitive inPrimitive = inJsonEntryValue.getAsJsonPrimitive();
                JsonPrimitive outPrimitive = outJsonEntryValue.getAsJsonPrimitive();
                ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
            } else if (inJsonEntryValue.isJsonObject() && outJsonEntryValue.isJsonObject()) {
                JsonObject outJsonEntryValObj = outJsonEntryValue.getAsJsonObject();
                JsonObject inJsonEntryValObj = inJsonEntryValue.getAsJsonObject();
                transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
            } else if (inJsonEntryValue.isJsonArray() && outJsonEntryValue.isJsonArray()) {
                JsonArray inJsonEntryValArr = inJsonEntryValue.getAsJsonArray();
                JsonArray outJsonEntryValArr = outJsonEntryValue.getAsJsonArray();
                int outSize = outJsonEntryValArr.size();
                for (int i = 0; i < inJsonEntryValArr.size(); i++) {
                    if (outSize > i) {
                        JsonElement inArrEle = inJsonEntryValArr.get(i);
                        JsonElement outArrEle = outJsonEntryValArr.get(i);
                        if (inArrEle.isJsonPrimitive() && outArrEle.isJsonPrimitive()) {
                            JsonPrimitive inPrimitive = inArrEle.getAsJsonPrimitive();
                            JsonPrimitive outPrimitive = outArrEle.getAsJsonPrimitive();
                            ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
                        } else if (inArrEle.isJsonObject() && outArrEle.isJsonObject()) {
                            JsonObject outJsonEntryValObj = outArrEle.getAsJsonObject();
                            JsonObject inJsonEntryValObj = inArrEle.getAsJsonObject();
                            transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
                        }//from   ww w. j  av a  2  s .c om
                    }
                }
            }
        }

    }

}