Example usage for com.google.gson JsonElement isJsonPrimitive

List of usage examples for com.google.gson JsonElement isJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonPrimitive.

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

public static boolean getBoolVal(JsonElement json) {
    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }/*from  ww w.j a  va 2  s. c  o  m*/

    if (!json.isJsonPrimitive()) {
        throw new JsonSyntaxException("Expected value to be a primitive");
    }

    return json.getAsBoolean();
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

public static boolean getBoolVal(JsonElement json, boolean defVal) {
    if (json == null || !json.isJsonPrimitive()) {
        return defVal;
    }// w  w  w . j  a  va  2s  . c o  m

    return json.getAsBoolean();
}

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);
                }/*w ww.j  a  va2 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:edu.isi.karma.service.json.JsonManager.java

License:Apache License

private static void recursiveParse(JsonElement jse, Element element) {
    if (jse.isJsonObject()) {
        JsonObject j = jse.getAsJsonObject();
        Set<Entry<String, JsonElement>> set = j.entrySet();
        //           System.out.println(set.size());
        Iterator<Entry<String, JsonElement>> iter = set.iterator();
        while (iter.hasNext()) {
            Entry<String, JsonElement> entry = iter.next();

            Element e = new Element();
            e.setKey(entry.getKey());/*from w  ww.  jav a  2 s  .  c o m*/
            //               System.out.println("create " + e.getKey());
            e.setValue(new ArrayValue());
            e.setValueType(ValueType.ARRAY);

            recursiveParse(entry.getValue(), e);

            //               System.out.println("element " + element.getKey());
            e.setParent(element);
            ((ArrayValue) element.getValue()).getElements().add(e);
            //               System.out.println("e " + e.getKey());

        }
    } else if (jse.isJsonArray()) {
        JsonArray j = jse.getAsJsonArray();
        Iterator<JsonElement> iter = j.iterator();
        while (iter.hasNext()) {

            Element e = new Element();
            e.setKey("");
            e.setValue(new ArrayValue());
            e.setValueType(ValueType.ARRAY);
            recursiveParse(iter.next(), e);
            e.setParent(element);
            ((ArrayValue) element.getValue()).getElements().add(e);
        }
    } else if (jse.isJsonPrimitive()) {
        element.setValueType(ValueType.SINGLE);
        element.setValue(new SingleValue(jse.toString()));
        //           System.out.println(jse.getAsString());
    }

}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    if (baseClass.isAssignableFrom(type.getRawType())) {
        return new TypeAdapter<T>() {
            @Override/*from ww w  .j a va  2 s .c o m*/
            public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter delegate = delegateFactory.create(gson, TypeToken.get(value.getClass()));
                JsonTreeWriter treeWriter = new JsonTreeWriter();
                delegate.write(treeWriter, value);
                JsonElement el = treeWriter.get();

                if (el.isJsonObject()) {
                    JsonObject elObject = el.getAsJsonObject();
                    elObject.addProperty(RuntimeTypeAdapterFactory.TYPE, value.getClass().getName());
                    Streams.write(elObject, out);
                } else {
                    Streams.write(el, out);
                }
            }

            @Override
            public T read(JsonReader in) throws IOException {
                // TODO: need to handle null
                JsonElement el = Streams.parse(in);
                Class<? extends T> runtimeType = getRuntimeType(el, type);
                if (runtimeType == null) {
                    throw new ParseException("RuntimeTypeAdapter: Unable to parse runtime type.");
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter<? extends T> delegate = delegateFactory.create(gson,
                        TypeToken.get(runtimeType));

                if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
                    JsonObject typeObject = new JsonObject();
                    typeObject.addProperty(TYPE, el.getAsString());
                    el = typeObject;
                }

                return delegate.read(new JsonTreeReader(el));
            }

        };
    }
    return null;
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public static <T> Class<? extends T> getRuntimeType(JsonElement el, Class<T> baseClass,
        Class<? extends T> defaultClass) {
    Class<? extends T> type = defaultClass;
    String typeString = null;/* w ww.  j a v  a 2 s.  c  o  m*/
    if (el != null) {
        try {
            if (el.isJsonObject()) {
                JsonObject jsonObject = el.getAsJsonObject();
                if (jsonObject.has(RuntimeTypeAdapterFactory.TYPE)) {
                    typeString = jsonObject.get(RuntimeTypeAdapterFactory.TYPE).getAsString();
                }
            } else if (el.isJsonPrimitive()) {
                typeString = el.getAsString();
            }
        } catch (ClassCastException e) {
        }
    }
    // TODO: expand string to allow for builtin to be specified as ".SampleProbe"
    if (typeString != null) {
        try {
            Class<?> runtimeClass = Class.forName(typeString);
            if (baseClass.isAssignableFrom(runtimeClass)) {
                type = (Class<? extends T>) runtimeClass;
            } else {
                Log.w(TAG, "RuntimeTypeAdapter: Runtime class '" + typeString
                        + "' is not assignable from default class '" + defaultClass.getName() + "'.");
            }
        } catch (ClassNotFoundException e) {
            Log.w(TAG, "RuntimeTypeAdapter: Runtime class '" + typeString + "' not found.");
        }
    }
    return type;
}

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  va2  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:eu.crushedpixel.littlstar.api.gson.ErrorsDeserializer.java

License:Apache License

@Override
public Errors deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonPrimitive())
        return new Errors(new String[] { json.getAsString() });
    String[] errors = context.deserialize(json, String[].class);
    return new Errors(errors);
}

From source file:eu.over9000.cathode.data.deserializers.ThumbnailListDeserializer.java

License:Open Source License

@Override
public List<Thumbnail> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonPrimitive()) {
        final String url = json.getAsString();
        return Collections.singletonList(new Thumbnail(url, "processing"));
    }/* w w  w .jav a2 s  .  co  m*/

    return context.deserialize(json, ThumbnailList.class);
}

From source file:ezbake.data.elastic.test.EzElasticTestUtils.java

License:Apache License

public static Map<String, Object> jsonToMap(String json) {
    final JsonObject object = (JsonObject) new JsonParser().parse(json);
    final Iterator<Map.Entry<String, JsonElement>> iterator = object.entrySet().iterator();
    final Map<String, Object> map = new HashMap<>();
    while (iterator.hasNext()) {
        final Map.Entry<String, JsonElement> entry = iterator.next();
        final String key = entry.getKey();
        final JsonElement value = entry.getValue();
        if (value.isJsonPrimitive()) {
            map.put(key, value.getAsString());
        } else {/*w  ww. j a va  2s  . c  o  m*/
            map.put(key, jsonToMap(value.toString()));
        }
    }
    return map;
}