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:org.zoxweb.server.util.GSONUtil.java

License:Apache License

public static QueryRequest fromQueryRequest(String json) {
    JsonElement je = new JsonParser().parse(json);
    QueryRequest ret = null;//from www.java 2 s .co m

    if (je instanceof JsonObject) {
        ret = new QueryRequest();
        JsonObject jo = (JsonObject) je;
        ret.setCanonicalID(jo.get(MetaToken.CANONICAL_ID.getName()).getAsString());
        JsonElement batchSize = jo.get("batch_size");

        if (batchSize != null) {
            ret.setBatchSize(batchSize.getAsInt());
        }

        JsonArray jaFNs = (JsonArray) jo.get("field_names");

        if (jaFNs != null) {
            List<String> fieldNames = new ArrayList<String>();

            for (int i = 0; i < jaFNs.size(); i++) {
                fieldNames.add(jaFNs.get(i).getAsString());
            }

            ret.setFieldNames(fieldNames);
        }

        JsonArray jaQuery = (JsonArray) jo.get("query");
        if (jaQuery != null) {
            List<QueryMarker> qms = new ArrayList<QueryMarker>();
            for (int i = 0; i < jaQuery.size(); i++) {
                // get the query marker
                JsonObject joQM = (JsonObject) jaQuery.get(i);
                QueryMarker qm = null;

                JsonPrimitive lo = (JsonPrimitive) joQM.get(MetaToken.LOGICAL_OPERATOR.getName());

                if (lo != null) {
                    qm = Const.LogicalOperator.valueOf(lo.getAsString());
                } else {
                    Const.RelationalOperator ro = null;

                    JsonPrimitive jpRO = (JsonPrimitive) joQM.get(MetaToken.RELATIONAL_OPERATOR.getName());

                    if (jpRO != null) {
                        ro = Const.RelationalOperator.valueOf(jpRO.getAsString());
                    }

                    String name = null;
                    JsonElement value = null;

                    Set<Map.Entry<String, JsonElement>> allParams = joQM.entrySet();

                    for (Map.Entry<String, JsonElement> e : allParams) {
                        if (!e.getKey().equals(MetaToken.RELATIONAL_OPERATOR.getName())) {
                            name = e.getKey();
                            value = e.getValue();
                            break;
                        }
                    }

                    // try to guess the type
                    if (value.isJsonPrimitive()) {
                        JsonPrimitive jp = (JsonPrimitive) value;

                        if (jp.isString()) {
                            qm = new QueryMatchString(ro, jp.getAsString(), name);
                        } else if (jp.isNumber()) {
                            qm = new QueryMatchLong(ro, jp.getAsLong(), name);
                        }
                    }
                }

                if (qm != null) {
                    qms.add(qm);
                }
            }

            ret.setQuery(qms);
        }
    }

    return ret;
}

From source file:org.zoxweb.server.util.GSONUtil.java

License:Apache License

public static NVBase<?> guessPrimitive(String name, NVConfig nvc, JsonPrimitive jp) {
    GNVType gnvType = nvc != null ? GNVType.toGNVType(nvc) : null;

    if (gnvType == null) {
        GNVTypeName tn = GNVType.toGNVTypeName(name, ':');
        if (tn != null) {
            gnvType = tn.getType();//from   www  .ja  va  2s  .c  o m
            name = tn.getName();
        }
    }

    if (gnvType != null) {
        switch (gnvType) {
        case NVBLOB:
            try {
                byte value[] = SharedBase64.decode(Base64Type.URL, jp.getAsString());
                return new NVBlob(name, value);
            } catch (Exception e) {

            }
            break;
        case NVBOOLEAN:
            return new NVBoolean(name, jp.getAsBoolean());
        case NVDOUBLE:
            return new NVDouble(name, jp.getAsDouble());
        case NVFLOAT:
            return new NVFloat(name, jp.getAsFloat());
        case NVINT:
            return new NVInt(name, jp.getAsInt());
        case NVLONG:
            return new NVLong(name, jp.getAsLong());

        }
    }

    if (jp.isBoolean()) {
        return new NVBoolean(name, jp.getAsBoolean());
    } else if (jp.isNumber()) {
        // if there is no dots it should be a 
        //if (jp.getAsString().indexOf(".") == -1)
        {
            try {
                Number number = SharedUtil.parseNumber(jp.getAsString());
                return SharedUtil.numberToNVBase(name, number);

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        //else
        {
            try {
                return new NVDouble(name, jp.getAsDouble());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    } else if (jp.isString()) {
        try {
            byte value[] = SharedBase64.decodeWrappedAsString(jp.getAsString());
            return new NVBlob(name, value);
        } catch (Exception e) {

        }
        try {
            Long.parseLong(jp.getAsString());
        } catch (Exception e) {
            if (TimestampFilter.SINGLETON.isValid(jp.getAsString())) {
                return new NVLong(name, TimestampFilter.SINGLETON.validate(jp.getAsString()));
            }
        }

        return new NVPair(name, jp.getAsString());
    }

    return null;

}

From source file:org.zoxweb.server.util.GSONUtil.java

License:Apache License

public static Map<String, ?> fromJSONMap(String json, Base64Type b64Type) throws APIException {
    Map<String, Object> ret = new LinkedHashMap<String, Object>();

    JsonElement je = new JsonParser().parse(json);

    log.log(Level.FINE, "JSONElement created from json (String): " + je);

    if (je instanceof JsonObject) {
        JsonObject jo = (JsonObject) je;

        for (Entry<String, JsonElement> element : jo.entrySet()) {
            if (!element.getValue().isJsonNull()) {
                if (element.getValue().isJsonArray()) {
                    List<Object> list = new ArrayList<Object>();

                    JsonArray jsonArray = element.getValue().getAsJsonArray();

                    for (int i = 0; i < jsonArray.size(); i++) {
                        if (jsonArray.get(i).isJsonObject()) {
                            NVEntity nve = fromJSON(jsonArray.get(i).getAsJsonObject(), null, b64Type);
                            list.add(nve);
                        } else if (jsonArray.get(i).isJsonPrimitive()) {
                            JsonPrimitive jsonPrimitive = jsonArray.get(i).getAsJsonPrimitive();

                            if (jsonPrimitive.isString()) {
                                list.add(jsonArray.get(i).getAsString());
                            } else if (jsonPrimitive.isBoolean()) {
                                list.add(jsonArray.get(i).getAsBoolean());
                            }/*from  w  ww.  j a  v a 2 s  .c o  m*/
                        }
                    }

                    ret.put(element.getKey(), list);
                } else if (element.getValue().isJsonObject()) {
                    NVEntity nve = fromJSON(element.getValue().getAsJsonObject(), null, b64Type);
                    ret.put(element.getKey(), nve);
                } else if (element.getValue().isJsonPrimitive()) {
                    JsonPrimitive jsonPrimitive = element.getValue().getAsJsonPrimitive();

                    if (jsonPrimitive.isString()) {
                        ret.put(element.getKey(), jsonPrimitive.getAsString());
                    } else if (jsonPrimitive.isBoolean()) {
                        ret.put(element.getKey(), jsonPrimitive.getAsBoolean());
                    }
                }
            } else {
                ret.put(element.getKey(), null);
            }
        }
    }

    return ret;
}

From source file:org.zoxweb.server.util.GSONUtil.java

License:Apache License

@SuppressWarnings("unchecked")
private static NVEntity fromJSON(JsonObject jo, Class<? extends NVEntity> clazz, Base64Type b64Type)
        throws AccessException, APIException {

    // check if the jo has class name setup
    // before creating the new instance
    JsonElement classType = jo.get(MetaToken.CLASS_TYPE.getName());

    if (classType != null) {
        if (!classType.isJsonNull()) {

            try {
                clazz = (Class<? extends NVEntity>) Class.forName(classType.getAsString());
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                throw new APIException(e.getMessage(), Reason.NOT_FOUND);
            }/* w w  w.  j  av  a2s .c o  m*/
        }
    }

    NVEntity nve = null;

    try {
        try {
            nve = clazz.getDeclaredConstructor().newInstance();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            throw new APIException(e.getMessage(), Reason.NOT_FOUND);
        }
    } catch (InstantiationException | InvocationTargetException | NoSuchMethodException ie) {
        ie.printStackTrace();
        log.info("Error class:" + clazz);
        log.info("" + jo.toString());
        throw new APIException(ie.getMessage(), Reason.NOT_FOUND);
        //         if (ie instanceof InstantiationException)
        //            throw (InstantiationException)ie;
        //         else 
        //            throw new InstantiationException(ie.getMessage());

    } catch (SecurityException ie) {
        throw new AccessException(ie.getMessage(), Reason.ACCESS_DENIED);
    }

    if (jo.get(MetaToken.REFERENCE_ID.getName()) != null
            && !jo.get(MetaToken.REFERENCE_ID.getName()).isJsonNull()) {
        nve.setReferenceID(jo.get(MetaToken.REFERENCE_ID.getName()).getAsString());
    }

    NVConfigEntity mcEntity = (NVConfigEntity) nve.getNVConfig();

    List<NVConfig> nvconfigs = mcEntity.getAttributes();

    for (NVConfig nvc : nvconfigs) {
        Class<?> metaType = nvc.getMetaType();
        JsonElement je = jo.get(nvc.getName());

        if (je != null && !je.isJsonNull()) {
            NVBase<?> nvb = nve.lookup(nvc.getName());

            if (nvc.isArray()) {
                //if ( nvb instanceof NVBase<List<NVEntity>>)

                //if ( NVEntity.class.isAssignableFrom( metaType.getComponentType()))
                if (NVEntity.class.isAssignableFrom(nvc.getMetaTypeBase())) {
                    ArrayValues<NVEntity> tempArray = (ArrayValues<NVEntity>) nvb;
                    JsonArray jsonArray = je.getAsJsonArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonObject jobj = jsonArray.get(i).getAsJsonObject();
                        //                     try
                        {
                            tempArray.add(
                                    fromJSON(jobj, (Class<? extends NVEntity>) nvc.getMetaTypeBase(), b64Type));
                        }
                        //                     catch (InstantiationException ie)
                        //                     {
                        //                        log.info("nvc:" + nvc.getName() + ":" + nvc.getMetaTypeBase());
                        //                        throw ie;
                        //                     }
                        //nvl.getValue().add( toNVPair( jobj));      
                    }
                }
                // enum must be checked first
                else if (metaType.getComponentType().isEnum()) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<List<Enum<?>>> nel = (NVBase<List<Enum<?>>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        String jobj = jsonArray.get(i).getAsString();
                        nel.getValue().add(SharedUtil.enumValue(metaType.getComponentType(), jobj));
                    }
                } else if (String[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    ArrayValues<NVPair> nvpm = (ArrayValues<NVPair>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonObject jobj = jsonArray.get(i).getAsJsonObject();
                        nvpm.add(toNVPair(jobj));
                    }
                } else if (Long[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<Long>> nval = (NVBase<ArrayList<Long>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add(jsonArray.get(i).getAsLong());
                    }
                } else if (byte[].class.equals(metaType)) {
                    String byteArray64 = je.getAsString();

                    if (byteArray64 != null) {
                        nve.setValue(nvc, SharedBase64.decode(b64Type, byteArray64.getBytes()));
                    }
                } else if (Integer[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<Integer>> nval = (NVBase<ArrayList<Integer>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add((int) jsonArray.get(i).getAsLong());
                    }
                } else if (Float[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<Float>> nval = (NVBase<ArrayList<Float>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add((float) jsonArray.get(i).getAsDouble());
                    }
                } else if (Double[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<Double>> nval = (NVBase<ArrayList<Double>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add(jsonArray.get(i).getAsDouble());
                    }
                } else if (Date[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<Long>> nval = (NVBase<ArrayList<Long>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonPrimitive jp = (JsonPrimitive) jsonArray.get(i);
                        long tempDate = 0;

                        if (jp.isString() && nvc.getValueFilter() != null) {
                            tempDate = (Long) nvc.getValueFilter().validate(jp.getAsString());
                        } else {
                            tempDate = jp.getAsLong();
                        }

                        nval.getValue().add(tempDate);
                    }
                } else if (BigDecimal[].class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVBase<ArrayList<BigDecimal>> nval = (NVBase<ArrayList<BigDecimal>>) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add(jsonArray.get(i).getAsBigDecimal());
                    }
                }

            } else {
                // not array
                if (nvc instanceof NVConfigEntity) {
                    if (!(je instanceof JsonNull)) {
                        ((NVBase<NVEntity>) nvb).setValue(fromJSON(je.getAsJsonObject(),
                                (Class<? extends NVEntity>) nvc.getMetaType(), b64Type));
                    }
                } else if (NVGenericMap.class.equals(metaType)) {

                    if (!(je instanceof JsonNull)) {
                        NVGenericMap nvgm = fromJSONGenericMap(je.getAsJsonObject(), null, b64Type);
                        ((NVGenericMap) nve.lookup(nvc)).add(nvgm.values(), true);

                    }

                } else if (NVStringList.class.equals(metaType)) {
                    JsonArray jsonArray = je.getAsJsonArray();
                    NVStringList nval = (NVStringList) nvb;

                    for (int i = 0; i < jsonArray.size(); i++) {
                        nval.getValue().add(jsonArray.get(i).getAsString());
                    }
                } else if (nvc.isEnum()) {
                    if (!(je instanceof JsonNull)) {
                        //                     if (metaType.isAssignableFrom( DynamicEnumMap.class))
                        //                     {
                        //                        
                        //                        ((NVDynamicEnum)nvb).setValue(je.getAsString());
                        //                     }
                        //                     else
                        {
                            ((NVBase<Enum<?>>) nvb).setValue(SharedUtil.enumValue(metaType, je.getAsString()));
                        }
                    }
                } else if (String.class.equals(metaType)) {
                    if (!(je instanceof JsonNull)) {
                        ((NVPair) nvb).setValue(je.getAsString());
                    }
                } else if (Long.class.equals(metaType)) {
                    ((NVBase<Long>) nvb).setValue(je.getAsLong());
                } else if (Boolean.class.equals(metaType)) {
                    ((NVBase<Boolean>) nvb).setValue(je.getAsBoolean());
                } else if (Integer.class.equals(metaType)) {
                    ((NVBase<Integer>) nvb).setValue((int) je.getAsLong());
                } else if (Float.class.equals(metaType)) {
                    ((NVBase<Float>) nvb).setValue((float) je.getAsDouble());
                } else if (Double.class.equals(metaType)) {
                    ((NVBase<Double>) nvb).setValue(je.getAsDouble());
                } else if (Date.class.equals(metaType)) {
                    JsonPrimitive jp = (JsonPrimitive) je;

                    if (jp.isString()) {
                        if (nvc.getValueFilter() != null)
                            ((NVBase<Long>) nvb)
                                    .setValue((Long) nvc.getValueFilter().validate(jp.getAsString()));
                        else
                            ((NVBase<Long>) nvb).setValue(TimestampFilter.SINGLETON.validate(jp.getAsString()));
                    }

                    else {
                        ((NVBase<Long>) nvb).setValue(jp.getAsLong());
                    }
                } else if (BigDecimal.class.equals(metaType)) {
                    ((NVBase<BigDecimal>) nvb).setValue(je.getAsBigDecimal());
                }

            }
        }

    }

    if (nve instanceof SubjectID) {
        ((SubjectID<?>) nve).getSubjectID();
    }
    return nve;
}

From source file:ph.fingra.statisticsweb.service.DashBoardServiceImpl.java

License:Apache License

private void checkAppIcon(App app) {
    if ((app.getAppInfo() != null && app.getAppInfo().getSmallicon() != null) || !app.hasValidAppId())
        return;/*from  w  w  w .j a v a 2s  . c  o m*/
    if (app.getAppInfo() == null) {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppkey(app.getAppkey());
        app.setAppInfo(appInfo);
    }
    if (AppPlatform.valueOf(app.getPlatform()) == AppPlatform.IPHONE) {
        ResponseEntity<String> response = restTemplate
                .getForEntity("https://itunes.apple.com/lookup?id={appId}", String.class, app.getAppid());
        if (response.getStatusCode() != HttpStatus.OK)
            return;
        JsonObject result = (JsonObject) new JsonParser().parse(response.getBody());
        JsonArray arr = result.getAsJsonArray("results");
        if (result.getAsJsonPrimitive("resultCount").getAsInt() != 1)
            return;
        JsonPrimitive smallIconUrl = arr.get(0).getAsJsonObject().getAsJsonPrimitive("artworkUrl60");
        app.getAppInfo().setSmallicon(smallIconUrl.getAsString());
    } else {
        Document d = null;
        try {
            d = Jsoup.connect("https://play.google.com/store/apps/details?id=" + app.getAppid()).get();
            Elements div = d.getElementsByAttributeValueContaining("class", "cover-container");
            //System.out.println(div.hasClass("cover-container"));
            if (div.size() == 0)
                return;
            String path = div.get(0).getElementsByTag("img").attr("src");
            app.getAppInfo().setSmallicon(path);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
    appDao.updateAppInfo(app.getAppInfo());

}

From source file:pI.generator.JsonJavaMapper.java

License:Open Source License

public Object json2JavaPrimitive(JsonPrimitive prim) {
    if (prim.isBoolean()) {
        return prim.getAsBoolean();
    } else if (prim.isString()) {
        return prim.getAsString();
    } else if (prim.isNumber()) {
        return prim.getAsNumber();
    } else {/*from  w w  w  .j a  v  a 2  s . c o  m*/
        throw new IllegalStateException();
    }
}

From source file:qa.qcri.qnoise.util.NoiseJsonAdapterDeserializer.java

License:MIT License

@Override
public NoiseJsonAdapter deserialize(JsonElement rootElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    NoiseJsonAdapter adapter = new NoiseJsonAdapter();

    JsonObject rootObj = (JsonObject) rootElement;

    // ---------------- parsing source --------------------- //
    JsonObject source = (JsonObject) (rootObj.get("source"));
    Preconditions.checkNotNull(source != null, "Source is not found.");

    JsonPrimitive pathPrimitive = source.getAsJsonPrimitive("path");
    Preconditions.checkNotNull(pathPrimitive);
    adapter.inputFile = pathPrimitive.getAsString();

    JsonArray schemaArray = source.getAsJsonArray("type");
    if (schemaArray != null) {
        adapter.schema = Lists.newArrayList();
        for (JsonElement primitive : schemaArray) {
            adapter.schema.add(primitive.getAsString());
        }//from   www .  j ava  2 s. c  o  m
    }

    JsonPrimitive csvSeparator = source.getAsJsonPrimitive("csvSeparator");
    if (csvSeparator != null) {
        adapter.csvSeparator = csvSeparator.getAsCharacter();
    } else {
        adapter.csvSeparator = NoiseJsonAdapter.DEFAULT_CSV_SEPARATOR;
    }

    // ---------------- parsing noises --------------------- //
    JsonElement noiseElement = rootObj.get("noise");
    JsonArray noiseArray;
    if (noiseElement instanceof JsonArray) {
        noiseArray = (JsonArray) (rootObj.get("noise"));
    } else {
        noiseArray = new JsonArray();
        noiseArray.add(noiseElement);
    }

    Preconditions.checkArgument(noiseArray != null && noiseArray.size() > 0,
            "Noise specification is null or empty.");

    adapter.specs = Lists.newArrayList();
    for (JsonElement specJson : noiseArray) {
        JsonObject noiseObj = (JsonObject) specJson;
        NoiseSpec spec = new NoiseSpec();

        JsonPrimitive noiseType = noiseObj.getAsJsonPrimitive("noiseType");
        Preconditions.checkNotNull(noiseType);
        spec.noiseType = NoiseType.fromString(noiseType.getAsString());

        JsonPrimitive granularity = noiseObj.getAsJsonPrimitive("granularity");
        if (granularity != null) {
            spec.granularity = GranularityType.fromString(granularity.getAsString());
        } else {
            // assign default granularity
            if (spec.noiseType == NoiseType.Duplicate)
                spec.granularity = GranularityType.Row;
            else
                spec.granularity = GranularityType.Cell;
        }

        JsonPrimitive percentage = noiseObj.getAsJsonPrimitive("percentage");
        if (percentage != null)
            spec.percentage = percentage.getAsDouble();
        else
            throw new IllegalArgumentException("Percentage cannot be null.");

        JsonPrimitive model = noiseObj.getAsJsonPrimitive("model");
        if (model != null) {
            spec.model = NoiseModel.fromString(model.getAsString());
        } else {
            spec.model = NoiseModel.Random;
        }

        JsonArray column = noiseObj.getAsJsonArray("column");
        if (column != null) {
            spec.filteredColumns = new String[column.size()];
            for (int i = 0; i < column.size(); i++)
                spec.filteredColumns[i] = column.get(i).getAsString();
        }

        JsonPrimitive numberOfSeed = noiseObj.getAsJsonPrimitive("numberOfSeed");
        if (numberOfSeed != null) {
            spec.numberOfSeed = numberOfSeed.getAsDouble();
        }

        JsonArray distance = noiseObj.getAsJsonArray("distance");
        if (distance != null) {
            spec.distance = new double[distance.size()];
            for (int i = 0; i < distance.size(); i++)
                spec.distance[i] = distance.get(i).getAsDouble();
        } else if (spec.filteredColumns != null)
            spec.distance = new double[spec.filteredColumns.length];

        // domain or distance
        if (spec.distance == null) {
            JsonArray domain = noiseObj.getAsJsonArray("domain");
            if (domain != null) {
                spec.distance = new double[domain.size()];
                for (int i = 0; i < domain.size(); i++)
                    spec.distance[i] = domain.get(i).getAsDouble();
            } else if (spec.filteredColumns != null)
                spec.distance = new double[spec.filteredColumns.length];
        }

        JsonArray constraints = noiseObj.getAsJsonArray("constraint");
        if (constraints != null) {
            spec.constraint = new Constraint[constraints.size()];
            for (int i = 0; i < constraints.size(); i++)
                spec.constraint[i] = ConstraintFactory
                        .createConstraintFromString(constraints.get(i).getAsString());
        }

        JsonPrimitive logFile = noiseObj.getAsJsonPrimitive("logFile");
        if (logFile != null) {
            spec.logFile = logFile.getAsString();
        } else {
            Calendar calendar = Calendar.getInstance();
            DateFormat dateFormat = new SimpleDateFormat("MMddHHmmss");
            spec.logFile = "log" + dateFormat.format(calendar.getTime()) + ".csv";
        }
        adapter.specs.add(spec);
    }

    // -------------- verify specifications ------------------- //
    for (NoiseSpec spec : adapter.specs) {
        String errorMessage = NoiseHelper.verify(spec);
        if (errorMessage != null)
            throw new IllegalArgumentException(errorMessage);
    }

    return adapter;
}

From source file:rpc.server.data.JSONSerializer.java

License:Open Source License

private Object fromJsonElement(JsonElement jsonElement, Type expected) throws NoSuitableSerializableFactory {

    if (jsonElement == null) {
        return null;
    }//from  w  w w . j  a  v a  2s  .  c  o m

    // Null
    if (jsonElement.isJsonNull()) {
        return null;
    }

    // Boolean
    // Integer
    // Long
    // Float
    // Double
    // String
    // Enum
    if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();

        if (asJsonPrimitive.isBoolean()) {
            return asJsonPrimitive.getAsBoolean();
        }

        if (asJsonPrimitive.isNumber()) {
            if (expected.isInteger()) {
                return asJsonPrimitive.getAsInt();
            }

            if (expected.isLong()) {
                return asJsonPrimitive.getAsLong();
            }

            if (expected.isFloat()) {
                return asJsonPrimitive.getAsFloat();
            }

            if (expected.isDouble()) {
                return asJsonPrimitive.getAsDouble();
            }

            return asJsonPrimitive.getAsNumber();
        }

        if (asJsonPrimitive.isString()) {
            if (expected.isEnum()) {
                String value = asJsonPrimitive.getAsString();
                return Enum.valueOf((Class) expected.getTypeClass(), value);
            } else {
                return asJsonPrimitive.getAsString();
            }
        }
    }

    // Map
    // Serializable
    if (jsonElement.isJsonObject()) {
        JsonObject asJsonObject = jsonElement.getAsJsonObject();

        if (expected.isMap()) {
            Map<Object, Object> map = new HashMap<Object, Object>();

            Type keyType = expected.getParameterized(0);
            Type valueType = expected.getParameterized(1);

            if (!(keyType.isString() || keyType.isEnum())) {
                return null;
            }

            for (Map.Entry<String, JsonElement> entry : asJsonObject.entrySet()) {

                String key = entry.getKey();
                JsonElement value = entry.getValue();

                if (keyType.isString()) {
                    map.put(entry.getKey(), fromJsonElement(value, valueType));
                }

                if (keyType.isEnum()) {
                    map.put(Enum.valueOf((Class) keyType.getTypeClass(), key),
                            fromJsonElement(value, valueType));
                }
            }

            return map;
        } else {
            if (provider == null) {
                throw new NoSuitableSerializableFactory();
            }

            Serializable object = provider.make(expected);

            for (Map.Entry<String, Type> entry : object.fields().entrySet()) {

                String field = entry.getKey();
                Type fieldType = entry.getValue();

                JsonElement value = asJsonObject.get(field);
                object.set(field, fromJsonElement(value, fieldType));
            }

            return object;
        }
    }

    // List
    if (jsonElement.isJsonArray()) {
        JsonArray asJsonArray = jsonElement.getAsJsonArray();

        int size = asJsonArray.size();

        List<Object> list = new ArrayList<Object>();
        Type itemType = expected.getParameterized(0);

        for (int i = 0; i < size; i++) {
            JsonElement value = asJsonArray.get(i);
            list.add(fromJsonElement(value, itemType));
        }

        return list;
    }

    return null;
}

From source file:tk.breezy64.pantex.core.ConfigManager.java

private static Object jsonElementToObject(JsonElement e) {
    if (e.isJsonObject()) {
        return jsonObjectToMap(e.getAsJsonObject());
    } else if (e.isJsonPrimitive()) {
        JsonPrimitive p = e.getAsJsonPrimitive();
        if (p.isNumber()) {
            return p.getAsInt();
        } else if (p.isString()) {
            return p.getAsString();
        } else if (p.isBoolean()) {
            return p.getAsBoolean();
        }/*from  ww w . j a v a  2  s . co m*/
    } else if (e.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        e.getAsJsonArray().forEach((x) -> list.add(jsonElementToObject(x)));
        return list;
    }
    return null;
}

From source file:tk.jomp16.properties.JSONProperties.java

License:Open Source License

public List<String> getJsonArrayAsString(String key) {
    List<String> arrayList = new ArrayList<>();

    getJsonArrayAsJsonElement(key).forEach(element -> {
        JsonPrimitive jsonPrimitive = (JsonPrimitive) element;

        if (jsonPrimitive.isString()) {
            arrayList.add(jsonPrimitive.getAsString());
        }//w  ww  .j a v a 2  s  . c  om
    });

    return arrayList;
}