Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.flipkart.android.proteus.builder.LayoutBuilderFactory.java

License:Apache License

protected void registerFormatter(DataParsingLayoutBuilder layoutBuilder) {

    Formatter NumberFormatter = new Formatter() {

        private DecimalFormat formatter;

        @Override//from  w w w.j  a v  a2s.  com
        public String format(JsonElement elementValue) {
            double valueAsNumber;
            try {
                valueAsNumber = Double.parseDouble(elementValue.getAsString());
            } catch (NumberFormatException e) {
                return elementValue.toString();
            }
            formatter = new DecimalFormat("#,###");
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
                formatter.setRoundingMode(RoundingMode.FLOOR);
            }
            formatter.setMinimumFractionDigits(0);
            formatter.setMaximumFractionDigits(2);
            return formatter.format(valueAsNumber);
        }

        @Override
        public String getName() {
            return "number";
        }
    };

    Formatter DateFormatter = new Formatter() {

        @SuppressLint("SimpleDateFormat")
        private SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @SuppressLint("SimpleDateFormat")
        private SimpleDateFormat to = new SimpleDateFormat("d MMM, E");

        @Override
        public String format(JsonElement elementValue) {
            try {
                // 2015-06-18 12:01:37
                Date date = from.parse(elementValue.getAsString());
                return to.format(date);
            } catch (Exception e) {
                return elementValue.toString();
            }
        }

        @Override
        public String getName() {
            return "date";
        }
    };

    Formatter IndexFormatter = new Formatter() {
        @Override
        public String format(JsonElement elementValue) {
            int valueAsNumber;
            try {
                valueAsNumber = Integer.parseInt(elementValue.getAsString());
            } catch (NumberFormatException e) {
                return elementValue.toString();
            }
            return String.valueOf(valueAsNumber + 1);
        }

        @Override
        public String getName() {
            return "index";
        }
    };

    Formatter joinFormatter = new Formatter() {
        @Override
        public String format(JsonElement elementValue) {
            if (elementValue.isJsonArray()) {
                return Utils.getStringFromArray(elementValue.getAsJsonArray(), ",");
            } else {
                return elementValue.toString();
            }
        }

        @Override
        public String getName() {
            return "join";
        }
    };

    layoutBuilder.registerFormatter(NumberFormatter);
    layoutBuilder.registerFormatter(DateFormatter);
    layoutBuilder.registerFormatter(IndexFormatter);
    layoutBuilder.registerFormatter(joinFormatter);
}

From source file:com.flipkart.android.proteus.parser.custom.ViewGroupParser.java

License:Apache License

@Override
public boolean handleChildren(ProteusView view) {
    ProteusViewManager viewManager = view.getViewManager();
    LayoutBuilder builder = viewManager.getLayoutBuilder();
    JsonObject layout = viewManager.getLayout();
    JsonElement children = layout.get(ProteusConstants.CHILDREN);
    JsonObject data = viewManager.getDataContext().getData();
    int dataIndex = viewManager.getDataContext().getIndex();
    Styles styles = view.getViewManager().getStyles();

    if (null != children && !children.isJsonNull()) {
        if (children.isJsonArray()) {
            ProteusView child;//from w ww .  j a  v  a  2  s  .  c  o  m
            for (JsonElement jsonElement : children.getAsJsonArray()) {
                child = builder.build((ViewGroup) view, jsonElement.getAsJsonObject(), data, dataIndex, styles);
                addView(view, child);
            }
        } else if (children.isJsonObject()) {
            handleDataDrivenChildren(builder, view, viewManager, children.getAsJsonObject(), data, styles,
                    dataIndex);
        }
    }

    return true;
}

From source file:com.flipkart.android.proteus.parser.custom.ViewGroupParser.java

License:Apache License

private void handleDataDrivenChildren(LayoutBuilder builder, ProteusView parent, ProteusViewManager viewManager,
        JsonObject children, JsonObject data, Styles styles, int dataIndex) {

    String dataPath = children.get(ProteusConstants.DATA).getAsString().substring(1);
    viewManager.setDataPathForChildren(dataPath);

    Result result = Utils.readJson(dataPath, data, dataIndex);
    JsonElement element = result.isSuccess() ? result.element : null;

    JsonObject childLayout = children.getAsJsonObject(ProteusConstants.LAYOUT);

    viewManager.setChildLayout(childLayout);

    if (null == element || element.isJsonNull()) {
        return;/*from w  ww  .  ja va2 s.co  m*/
    }

    int length = element.getAsJsonArray().size();

    ProteusView child;
    for (int index = 0; index < length; index++) {
        child = builder.build((ViewGroup) parent, childLayout, data, index, styles);
        if (child != null) {
            this.addView(parent, child);
        }
    }
}

From source file:com.flipkart.android.proteus.processor.DrawableResourceProcessor.java

License:Apache License

/**
 * This block handles different drawables.
 * Selector and LayerListDrawable are handled here.
 * Override this to handle more types of drawables
 *
 * @param attributeKey/*  w  ww.  ja  va2  s.c  om*/
 * @param attributeValue
 * @param view
 */
protected void handleElement(String attributeKey, JsonElement attributeValue, V view) {

    JsonObject jsonObject = attributeValue.getAsJsonObject();

    JsonElement type = jsonObject.get(TYPE);
    String drawableType = type.getAsString();
    JsonElement childrenElement = null;
    switch (drawableType) {
    case DRAWABLE_SELECTOR:
        final StateListDrawable stateListDrawable = new StateListDrawable();
        childrenElement = jsonObject.get(CHILDREN);
        if (childrenElement != null) {
            JsonArray children = childrenElement.getAsJsonArray();
            for (JsonElement childElement : children) {
                JsonObject child = childElement.getAsJsonObject();
                final Pair<int[], JsonElement> state = ParseHelper.parseState(child);
                if (state != null) {
                    DrawableResourceProcessor<V> processor = new DrawableResourceProcessor<V>() {
                        @Override
                        public void setDrawable(V view, Drawable drawable) {
                            stateListDrawable.addState(state.first, drawable);
                        }
                    };
                    processor.handle(attributeKey, state.second, view);
                }

            }
        }
        setDrawable(view, stateListDrawable);
        break;
    case DRAWABLE_SHAPE:
        GradientDrawable gradientDrawable = loadGradientDrawable(view.getContext(), jsonObject);
        if (null != gradientDrawable) {
            setDrawable(view, gradientDrawable);
        }
        break;
    case DRAWABLE_LAYER_LIST:
        final List<Pair<Integer, Drawable>> drawables = new ArrayList<>();
        childrenElement = jsonObject.get(CHILDREN);
        if (childrenElement != null) {
            JsonArray children = childrenElement.getAsJsonArray();
            for (JsonElement childElement : children) {
                JsonObject child = childElement.getAsJsonObject();
                final Pair<Integer, JsonElement> layerPair = ParseHelper.parseLayer(child);
                if (null != layerPair) {
                    DrawableResourceProcessor<V> processor = new DrawableResourceProcessor<V>() {
                        @Override
                        public void setDrawable(V view, Drawable drawable) {
                            drawables.add(new Pair<>(layerPair.first, drawable));
                            onLayerDrawableFinish(view, drawables);
                        }
                    };
                    processor.handle(attributeKey, layerPair.second, view);
                }
            }
        }
        break;
    case DRAWABLE_LEVEL_LIST:
        final LevelListDrawable levelListDrawable = new LevelListDrawable();
        childrenElement = jsonObject.get(CHILDREN);
        if (childrenElement != null) {
            JsonArray children = childrenElement.getAsJsonArray();
            for (JsonElement childElement : children) {
                LayerListDrawableItem layerListDrawableItem = sGson.fromJson(childElement,
                        LayerListDrawableItem.class);
                layerListDrawableItem.addItem(view.getContext(), levelListDrawable);
            }
        }
        break;
    case DRAWABLE_RIPPLE:
        Drawable rippleDrawable = loadRippleDrawable(view.getContext(), jsonObject, attributeKey, view);
        if (null != rippleDrawable) {
            setDrawable(view, rippleDrawable);
        }
        break;
    }
}

From source file:com.flipkart.android.proteus.toolbox.ColorUtils.java

License:Apache License

private static ColorStateList inflateFromJson(Context context, JsonObject jsonObject) {
    ColorStateList result = null;/*  w w w. ja  v  a  2s  .  c  o  m*/
    JsonElement type = jsonObject.get("type");
    if (null != type && type.isJsonPrimitive()) {
        String colorType = type.getAsString();
        if (TextUtils.equals(colorType, "selector")) {
            JsonElement childrenElement = jsonObject.get("children");

            if (null != childrenElement && childrenElement.isJsonArray()) {
                JsonArray children = childrenElement.getAsJsonArray();
                int listAllocated = 20;
                int listSize = 0;
                int[] colorList = new int[listAllocated];
                int[][] stateSpecList = new int[listAllocated][];

                for (int idx = 0; idx < children.size(); idx++) {
                    JsonElement itemObject = children.get(idx);
                    if (!itemObject.isJsonObject()) {
                        continue;
                    }

                    Set<Map.Entry<String, JsonElement>> entrySet = ((JsonObject) itemObject).entrySet();
                    if (entrySet.size() == 0) {
                        continue;
                    }

                    int j = 0;
                    Integer baseColor = null;
                    float alphaMod = 1.0f;

                    int[] stateSpec = new int[entrySet.size() - 1];
                    boolean ignoreItem = false;
                    for (Map.Entry<String, JsonElement> entry : entrySet) {
                        if (ignoreItem) {
                            break;
                        }
                        if (!entry.getValue().isJsonPrimitive()) {
                            continue;
                        }
                        Integer attributeId = getAttribute(entry.getKey());
                        if (null != attributeId) {
                            switch (attributeId) {
                            case android.R.attr.type:
                                if (!TextUtils.equals("item", entry.getValue().getAsString())) {
                                    ignoreItem = true;
                                }
                                break;
                            case android.R.attr.color:
                                String colorRes = entry.getValue().getAsString();
                                if (!TextUtils.isEmpty(colorRes)) {
                                    baseColor = getColorFromAttributeValue(context, colorRes);
                                }
                                break;
                            case android.R.attr.alpha:
                                String alphaStr = entry.getValue().getAsString();
                                if (!TextUtils.isEmpty(alphaStr)) {
                                    alphaMod = Float.parseFloat(alphaStr);
                                }
                                break;
                            default:
                                stateSpec[j++] = entry.getValue().getAsBoolean() ? attributeId : -attributeId;
                                break;
                            }
                        }
                    }
                    if (!ignoreItem) {
                        stateSpec = StateSet.trimStateSet(stateSpec, j);
                        if (null == baseColor) {
                            throw new IllegalStateException("No Color Specified");
                        }

                        if (listSize + 1 >= listAllocated) {
                            listAllocated = idealIntArraySize(listSize + 1);
                            int[] ncolor = new int[listAllocated];
                            System.arraycopy(colorList, 0, ncolor, 0, listSize);
                            int[][] nstate = new int[listAllocated][];
                            System.arraycopy(stateSpecList, 0, nstate, 0, listSize);
                            colorList = ncolor;
                            stateSpecList = nstate;
                        }

                        final int color = modulateColorAlpha(baseColor, alphaMod);

                        colorList[listSize] = color;
                        stateSpecList[listSize] = stateSpec;
                        listSize++;
                    }
                }
                if (listSize > 0) {
                    int[] colors = new int[listSize];
                    int[][] stateSpecs = new int[listSize][];
                    System.arraycopy(colorList, 0, colors, 0, listSize);
                    System.arraycopy(stateSpecList, 0, stateSpecs, 0, listSize);
                    result = new ColorStateList(stateSpecs, colors);
                }
            }
        }
    }
    return result;
}

From source file:com.flipkart.android.proteus.toolbox.Utils.java

License:Apache License

public static Result readJson(String path, JsonObject data, int index) {
    // replace INDEX reference with index value
    if (ProteusConstants.INDEX.equals(path)) {
        path = path.replace(ProteusConstants.INDEX, String.valueOf(index));
        return Result.success(new JsonPrimitive(path));
    } else {//  w  w  w . ja  v  a  2 s . co m
        StringTokenizer tokenizer = new StringTokenizer(path, ProteusConstants.DATA_PATH_DELIMITERS);
        JsonElement elementToReturn = data;
        JsonElement tempElement;
        JsonArray tempArray;

        while (tokenizer.hasMoreTokens()) {
            String segment = tokenizer.nextToken();
            if (elementToReturn == null) {
                return Result.NO_SUCH_DATA_PATH_EXCEPTION;
            }
            if (elementToReturn.isJsonNull()) {
                return Result.JSON_NULL_EXCEPTION;
            }
            if ("".equals(segment)) {
                continue;
            }
            if (elementToReturn.isJsonArray()) {
                tempArray = elementToReturn.getAsJsonArray();

                if (ProteusConstants.INDEX.equals(segment)) {
                    if (index < tempArray.size()) {
                        elementToReturn = tempArray.get(index);
                    } else {
                        return Result.NO_SUCH_DATA_PATH_EXCEPTION;
                    }
                } else if (ProteusConstants.ARRAY_DATA_LENGTH_REFERENCE.equals(segment)) {
                    elementToReturn = new JsonPrimitive(tempArray.size());
                } else if (ProteusConstants.ARRAY_DATA_LAST_INDEX_REFERENCE.equals(segment)) {
                    if (tempArray.size() == 0) {
                        return Result.NO_SUCH_DATA_PATH_EXCEPTION;
                    }
                    elementToReturn = tempArray.get(tempArray.size() - 1);
                } else {
                    try {
                        index = Integer.parseInt(segment);
                    } catch (NumberFormatException e) {
                        return Result.INVALID_DATA_PATH_EXCEPTION;
                    }
                    if (index < tempArray.size()) {
                        elementToReturn = tempArray.get(index);
                    } else {
                        return Result.NO_SUCH_DATA_PATH_EXCEPTION;
                    }
                }
            } else if (elementToReturn.isJsonObject()) {
                tempElement = elementToReturn.getAsJsonObject().get(segment);
                if (tempElement != null) {
                    elementToReturn = tempElement;
                } else {
                    return Result.NO_SUCH_DATA_PATH_EXCEPTION;
                }
            } else if (elementToReturn.isJsonPrimitive()) {
                return Result.INVALID_DATA_PATH_EXCEPTION;
            } else {
                return Result.NO_SUCH_DATA_PATH_EXCEPTION;
            }
        }
        if (elementToReturn.isJsonNull()) {
            return Result.JSON_NULL_EXCEPTION;
        }
        return Result.success(elementToReturn);
    }
}

From source file:com.flipkart.android.proteus.toolbox.Utils.java

License:Apache License

public static JsonElement merge(JsonElement oldJson, JsonElement newJson, boolean useCopy, Gson gson) {

    JsonElement newDataElement;/*from  w w  w . j a  v  a 2  s. co  m*/
    JsonArray oldArray;
    JsonArray newArray;
    JsonElement oldArrayItem;
    JsonElement newArrayItem;
    JsonObject oldObject;

    if (oldJson == null || oldJson.isJsonNull()) {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    if (newJson == null || newJson.isJsonNull()) {
        newJson = JsonNull.INSTANCE;
        return newJson;
    }

    if (newJson.isJsonPrimitive()) {
        JsonPrimitive value;
        if (!useCopy) {
            return newJson;
        }
        if (newJson.getAsJsonPrimitive().isBoolean()) {
            value = new JsonPrimitive(newJson.getAsBoolean());
        } else if (newJson.getAsJsonPrimitive().isNumber()) {
            value = new JsonPrimitive(newJson.getAsNumber());
        } else if (newJson.getAsJsonPrimitive().isString()) {
            value = new JsonPrimitive(newJson.getAsString());
        } else {
            value = newJson.getAsJsonPrimitive();
        }
        return value;
    }

    if (newJson.isJsonArray()) {
        if (!oldJson.isJsonArray()) {
            return useCopy ? gson.fromJson(newJson, JsonArray.class) : newJson;
        } else {
            oldArray = oldJson.getAsJsonArray();
            newArray = newJson.getAsJsonArray();

            if (oldArray.size() > newArray.size()) {
                while (oldArray.size() > newArray.size()) {
                    oldArray.remove(oldArray.size() - 1);
                }
            }

            for (int index = 0; index < newArray.size(); index++) {
                if (index < oldArray.size()) {
                    oldArrayItem = oldArray.get(index);
                    newArrayItem = newArray.get(index);
                    oldArray.set(index, merge(oldArrayItem, newArrayItem, useCopy, gson));
                } else {
                    oldArray.add(newArray.get(index));
                }
            }
        }
    } else if (newJson.isJsonObject()) {
        if (!oldJson.isJsonObject()) {
            return useCopy ? gson.fromJson(newJson, JsonObject.class) : newJson;
        } else {
            oldObject = oldJson.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : newJson.getAsJsonObject().entrySet()) {
                newDataElement = merge(oldObject.get(entry.getKey()), entry.getValue(), useCopy, gson);
                oldObject.add(entry.getKey(), newDataElement);
            }
        }
    } else {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    return oldJson;
}

From source file:com.fooock.shodan.model.banner.BannerDeserializer.java

License:Open Source License

@Override
public List<Banner> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final List<Banner> banners = new ArrayList<>();
    if (json.isJsonNull()) {
        return banners;
    }//from   w w w  . j a v a  2s. c  o m
    JsonArray jsonArray = json.getAsJsonArray();
    if (jsonArray.isJsonNull()) {
        return banners;
    }
    for (JsonElement element : jsonArray) {
        JsonObject jsonObject = element.getAsJsonObject();
        JsonElement port = jsonObject.get("port");
        JsonElement ip = jsonObject.get("ip");
        JsonElement asn = jsonObject.get("asn");
        JsonElement data = jsonObject.get("data");
        JsonElement ipStr = jsonObject.get("ip_str");
        JsonElement ipv6 = jsonObject.get("ipv6");
        JsonElement timestamp = jsonObject.get("timestamp");
        JsonElement hostnames = jsonObject.get("hostnames");
        JsonElement domains = jsonObject.get("domains");
        JsonElement location = jsonObject.get("location");
        JsonElement options = jsonObject.get("opts");
        JsonElement metadata = jsonObject.get("_shodan");
        JsonElement ssl = jsonObject.get("ssl");

        JsonElement uptime = jsonObject.get("uptime");
        JsonElement link = jsonObject.get("link");
        JsonElement title = jsonObject.get("title");
        JsonElement html = jsonObject.get("html");
        JsonElement product = jsonObject.get("product");
        JsonElement version = jsonObject.get("version");
        JsonElement isp = jsonObject.get("isp");
        JsonElement os = jsonObject.get("os");
        JsonElement transport = jsonObject.get("transport");
        JsonElement devicetype = jsonObject.get("devicetype");
        JsonElement info = jsonObject.get("info");
        JsonElement cpe = jsonObject.get("cpe");

        final Banner banner = new Banner();
        if (port == null || port.isJsonNull()) {
            banner.setPort(0);
        } else {
            banner.setPort(port.getAsInt());
        }

        if (ip == null || ip.isJsonNull()) {
            banner.setIp(0);
        } else {
            banner.setIp(ip.getAsLong());
        }

        if (asn == null || asn.isJsonNull()) {
            banner.setAsn("unknown");
        } else {
            banner.setAsn(asn.getAsString());
        }

        if (data == null || data.isJsonNull()) {
            banner.setData("unknown");
        } else {
            banner.setData(data.getAsString());
        }

        if (ipStr == null || ipStr.isJsonNull()) {
            banner.setIpStr("unknown");
        } else {
            banner.setIpStr(ipStr.getAsString());
        }

        if (ipv6 == null || ipv6.isJsonNull()) {
            banner.setIpv6("unknown");
        } else {
            banner.setIpv6(ipv6.getAsString());
        }

        if (timestamp == null || timestamp.isJsonNull()) {
            banner.setTimestamp("unknown");
        } else {
            banner.setTimestamp(timestamp.getAsString());
        }

        if (hostnames == null || hostnames.isJsonNull()) {
            banner.setHostnames(new String[0]);
        } else {
            JsonArray hostnamesAsJsonArray = hostnames.getAsJsonArray();
            String[] hostnameArray = new String[hostnamesAsJsonArray.size()];
            for (int i = 0; i < hostnamesAsJsonArray.size(); i++) {
                hostnameArray[i] = hostnamesAsJsonArray.get(i).getAsString();
            }
            banner.setHostnames(hostnameArray);
        }

        if (domains == null || domains.isJsonNull()) {
            banner.setDomains(new String[0]);
        } else {
            JsonArray domainsAsJsonArray = domains.getAsJsonArray();
            String[] domainsArray = new String[domainsAsJsonArray.size()];
            for (int i = 0; i < domainsAsJsonArray.size(); i++) {
                domainsArray[i] = domainsAsJsonArray.get(i).getAsString();
            }
            banner.setDomains(domainsArray);
        }

        if (location == null || location.isJsonNull()) {
            banner.setLocation(new Location());
        } else {
            JsonObject locationAsJsonObject = location.getAsJsonObject();
            JsonElement areaCode = locationAsJsonObject.get("area_code");
            JsonElement latitude = locationAsJsonObject.get("latitude");
            JsonElement longitude = locationAsJsonObject.get("longitude");
            JsonElement city = locationAsJsonObject.get("city");
            JsonElement regionCode = locationAsJsonObject.get("region_code");
            JsonElement postalCode = locationAsJsonObject.get("postal_code");
            JsonElement dmaCode = locationAsJsonObject.get("dma_code");
            JsonElement countryCode = locationAsJsonObject.get("country_code");
            JsonElement countryCode3 = locationAsJsonObject.get("country_code3");
            JsonElement countryName = locationAsJsonObject.get("country_name");

            Location locationObject = new Location();
            if (areaCode == null || areaCode.isJsonNull()) {
                locationObject.setAreaCode(0);
            } else {
                locationObject.setAreaCode(areaCode.getAsInt());
            }

            if (latitude == null || latitude.isJsonNull()) {
                locationObject.setLatitude(0.0);
            } else {
                locationObject.setLatitude(latitude.getAsDouble());
            }

            if (longitude == null || location.isJsonNull()) {
                locationObject.setLongitude(0.0);
            } else {
                locationObject.setLongitude(longitude.getAsDouble());
            }

            if (city == null || city.isJsonNull()) {
                locationObject.setCity("unknown");
            } else {
                locationObject.setCity(city.getAsString());
            }

            if (regionCode == null || regionCode.isJsonNull()) {
                locationObject.setRegionCode("unknown");
            } else {
                locationObject.setRegionCode(regionCode.getAsString());
            }

            if (postalCode == null || postalCode.isJsonNull()) {
                locationObject.setPostalCode("unknown");
            } else {
                locationObject.setPostalCode(postalCode.getAsString());
            }

            if (dmaCode == null || dmaCode.isJsonNull()) {
                locationObject.setDmaCode("unknown");
            } else {
                locationObject.setDmaCode(dmaCode.getAsString());
            }

            if (countryCode == null || countryCode.isJsonNull()) {
                locationObject.setCountryCode("unknown");
            } else {
                locationObject.setCountryCode(countryCode.getAsString());
            }

            if (countryCode3 == null || countryCode3.isJsonNull()) {
                locationObject.setCountryCode3("unknown");
            } else {
                locationObject.setCountryCode3(countryCode3.getAsString());
            }

            if (countryName == null || countryName.isJsonNull()) {
                locationObject.setCountryName("unknown");
            } else {
                locationObject.setCountryName(countryName.getAsString());
            }

            banner.setLocation(locationObject);
        }

        final Options opts = new Options();
        if (options == null || options.isJsonNull()) {
            opts.setRaw("unknown");
        } else {
            JsonObject object = options.getAsJsonObject();
            JsonElement raw = object.get("raw");
            if (raw == null || raw.isJsonNull()) {
                opts.setRaw("unknown");
            } else {
                opts.setRaw(raw.getAsString());
            }
        }
        banner.setOptions(opts);

        final Metadata shodanMetadata = new Metadata();
        if (metadata == null || metadata.isJsonNull()) {
            shodanMetadata.setCrawler("unknown");
            shodanMetadata.setId("unknown");
            shodanMetadata.setModule("unknown");
        } else {
            JsonObject metadataAsJsonObject = metadata.getAsJsonObject();
            JsonElement crawler = metadataAsJsonObject.get("crawler");
            JsonElement id = metadataAsJsonObject.get("id");
            JsonElement module = metadataAsJsonObject.get("module");

            if (crawler == null || crawler.isJsonNull()) {
                shodanMetadata.setCrawler("unknown");
            } else {
                shodanMetadata.setCrawler(crawler.getAsString());
            }

            if (id == null || id.isJsonNull()) {
                shodanMetadata.setId("unknown");
            } else {
                shodanMetadata.setId(id.getAsString());
            }

            if (module == null || module.isJsonNull()) {
                shodanMetadata.setModule("unknown");
            } else {
                shodanMetadata.setModule(module.getAsString());
            }
        }
        banner.setMetadata(shodanMetadata);

        final SslInfo sslInfo = new SslInfo();
        if (ssl == null || ssl.isJsonNull()) {
            banner.setSslEnabled(false);
        } else {
            banner.setSslEnabled(true);

            JsonObject sslAsJsonObject = ssl.getAsJsonObject();
            JsonElement chain = sslAsJsonObject.get("chain");
            JsonArray chainAsJsonArray = chain.getAsJsonArray();
            String[] chainArray = new String[chainAsJsonArray.size()];
            for (int i = 0; i < chainAsJsonArray.size(); i++) {
                chainArray[i] = chainAsJsonArray.get(i).getAsString();
            }
            sslInfo.setChain(chainArray);

            JsonElement versions = sslAsJsonObject.get("versions");
            JsonArray versionAsJsonArray = versions.getAsJsonArray();
            String[] versionsArray = new String[versionAsJsonArray.size()];
            for (int i = 0; i < versionsArray.length; i++) {
                versionsArray[i] = versionAsJsonArray.get(i).getAsString();
            }
            sslInfo.setVersions(versionsArray);

            JsonElement cipher = sslAsJsonObject.get("cipher");
            JsonObject cipherAsJsonObject = cipher.getAsJsonObject();
            JsonElement bits = cipherAsJsonObject.get("bits");
            JsonElement cipherVersion = cipherAsJsonObject.get("version");
            JsonElement name = cipherAsJsonObject.get("name");

            final Cipher cipherObject = new Cipher();
            if (bits != null && !bits.isJsonNull()) {
                cipherObject.setBits(bits.getAsInt());
            }
            if (cipherVersion != null && !cipherVersion.isJsonNull()) {
                cipherObject.setVersion(cipherVersion.getAsString());
            } else {
                cipherObject.setVersion("unknown");
            }
            if (name == null || name.isJsonNull()) {
                cipherObject.setName("unknown");
            } else {
                cipherObject.setName(name.getAsString());
            }
            sslInfo.setCipher(cipherObject);

            JsonElement dhparams = sslAsJsonObject.get("dhparams");
            if (dhparams != null && !dhparams.isJsonNull()) {
                JsonObject dhparamsAsJsonObject = dhparams.getAsJsonObject();

                JsonElement bits1 = dhparamsAsJsonObject.get("bits");
                JsonElement prime = dhparamsAsJsonObject.get("prime");
                JsonElement publicKey = dhparamsAsJsonObject.get("public_key");
                JsonElement generator = dhparamsAsJsonObject.get("generator");
                JsonElement fingerprint = dhparamsAsJsonObject.get("fingerprint");

                final DiffieHellmanParams diffieHellmanParams = new DiffieHellmanParams();
                if (bits1 != null && !bits1.isJsonNull()) {
                    diffieHellmanParams.setBits(bits1.getAsInt());
                }
                if (prime == null || prime.isJsonNull()) {
                    diffieHellmanParams.setPrime("unknown");
                } else {
                    diffieHellmanParams.setPrime(prime.getAsString());
                }
                if (publicKey == null || publicKey.isJsonNull()) {
                    diffieHellmanParams.setPublicKey("unknown");
                } else {
                    diffieHellmanParams.setPublicKey(publicKey.getAsString());
                }
                if (generator == null || generator.isJsonNull()) {
                    diffieHellmanParams.setGenerator("unknown");
                } else {
                    diffieHellmanParams.setGenerator(generator.getAsString());
                }
                if (fingerprint == null || fingerprint.isJsonNull()) {
                    diffieHellmanParams.setFingerprint("unknown");
                } else {
                    diffieHellmanParams.setFingerprint(fingerprint.getAsString());
                }
                sslInfo.setDiffieHellmanParams(diffieHellmanParams);
            }
        }
        banner.setSslInfo(sslInfo);

        if (uptime == null || uptime.isJsonNull()) {
            banner.setUptime(0);
        } else {
            banner.setUptime(uptime.getAsInt());
        }

        if (link == null || link.isJsonNull()) {
            banner.setLink("unknown");
        } else {
            banner.setLink(link.getAsString());
        }

        if (title == null || title.isJsonNull()) {
            banner.setTitle("unknown");
        } else {
            banner.setTitle(title.getAsString());
        }

        if (html == null || html.isJsonNull()) {
            banner.setHtml("unknown");
        } else {
            banner.setHtml(html.getAsString());
        }

        if (product == null || product.isJsonNull()) {
            banner.setProduct("unknown");
        } else {
            banner.setProduct(product.getAsString());
        }

        if (version == null || version.isJsonNull()) {
            banner.setVersion("unknown");
        } else {
            banner.setVersion(version.getAsString());
        }

        if (isp == null || isp.isJsonNull()) {
            banner.setIsp("unknown");
        } else {
            banner.setIsp(isp.getAsString());
        }

        if (os == null || os.isJsonNull()) {
            banner.setOs("unknown");
        } else {
            banner.setOs(os.getAsString());
        }

        if (transport == null || transport.isJsonNull()) {
            banner.setTransport("unknown");
        } else {
            banner.setTransport(transport.getAsString());
        }

        if (devicetype == null || devicetype.isJsonNull()) {
            banner.setDeviceType("unknown");
        } else {
            banner.setDeviceType(devicetype.getAsString());
        }

        if (info == null || info.isJsonNull()) {
            banner.setInfo("unknown");
        } else {
            banner.setInfo(info.getAsString());
        }

        if (cpe == null || cpe.isJsonNull()) {
            banner.setCpe(new String[0]);
        } else {
            // cpe can be string or string[]. Fix for #4
            if (cpe.isJsonObject()) {
                banner.setCpe(new String[] { cpe.getAsString() });

            } else {
                JsonArray cpeAsJsonArray = cpe.getAsJsonArray();
                String[] cpeArray = new String[cpeAsJsonArray.size()];
                for (int i = 0; i < cpeAsJsonArray.size(); i++) {
                    cpeArray[i] = cpeAsJsonArray.get(i).getAsString();
                }
                banner.setCpe(cpeArray);
            }
        }

        banners.add(banner);
    }
    return banners;
}

From source file:com.fooock.shodan.model.exploit.ExploitDeserializer.java

License:Open Source License

@Override
public List<Exploit> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    List<Exploit> exploits = new ArrayList<>();
    try {//from w w  w  .j a v  a  2 s.c o m
        JsonObject jsonObject = json.getAsJsonObject();
        JsonElement matches = jsonObject.get("matches");
        if (matches == null || matches.isJsonNull()) {
            return exploits;
        }
        JsonArray array = matches.getAsJsonArray();
        if (array == null || array.isJsonNull()) {
            return exploits;
        }
        for (JsonElement element : array) {
            Exploit exploit = parseJsonExploit(element);
            exploits.add(exploit);
        }
    } catch (IllegalStateException e) {
        // parsing the array of exploits directly, used when search with facets
        JsonArray elements = json.getAsJsonArray();
        if (elements == null || elements.isJsonNull()) {
            return exploits;
        }
        for (JsonElement element : elements) {
            Exploit exploit = parseJsonExploit(element);
            exploits.add(exploit);
        }
    }
    return exploits;
}

From source file:com.fooock.shodan.model.exploit.ExploitDeserializer.java

License:Open Source License

private Exploit parseJsonExploit(JsonElement json) {
    Exploit exploit = new Exploit();

    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get("_id").getAsString();
    String desc = jsonObject.get("description").getAsString();
    String source = jsonObject.get("source").getAsString();

    JsonElement jsonAuthor = jsonObject.get("author");
    if (jsonAuthor != null && !jsonAuthor.isJsonNull()) {
        if (jsonAuthor.isJsonPrimitive()) {
            String author = jsonAuthor.getAsString();
            exploit.setAuthor(author);/*from  ww w  . jav a  2  s. com*/
        } else {
            JsonArray array = jsonAuthor.getAsJsonArray();
            if (array != null) {
                String resAuthors = "";
                for (JsonElement element : array) {
                    resAuthors += ", " + element.getAsString();
                }
                exploit.setAuthor(resAuthors);
            }
        }
    }

    JsonElement jsonCode = jsonObject.get("code");
    if (jsonCode != null && !jsonCode.isJsonNull()) {
        String code = jsonCode.getAsString();
        exploit.setCode(code);
    }

    JsonElement jsonType = jsonObject.get("type");
    if (jsonType != null && !jsonType.isJsonNull()) {
        String type = jsonType.getAsString();
        exploit.setType(type);
    }

    JsonElement jsonVersion = jsonObject.get("version");
    if (jsonVersion != null && !jsonVersion.isJsonNull()) {
        String version = jsonVersion.getAsString();
        exploit.setVersion(version);
    }

    JsonElement jsonPrivileged = jsonObject.get("privileged");
    if (jsonPrivileged != null && !jsonPrivileged.isJsonNull()) {
        boolean privileged = jsonPrivileged.getAsBoolean();
        exploit.setPrivileged(privileged);
    }

    JsonElement jsonPort = jsonObject.get("port");
    if (jsonPort != null && !jsonPort.isJsonNull()) {
        int port = jsonPort.getAsInt();
        exploit.setPort(port);
    }

    JsonArray jsonBid = jsonObject.getAsJsonArray("bid");
    if (jsonBid != null) {
        String[] bid = new String[jsonBid.size()];
        for (int i = 0; i < jsonBid.size(); i++) {
            bid[i] = jsonBid.get(i).getAsString();
        }
        exploit.setBid(bid);
    }

    JsonArray jsonCve = jsonObject.getAsJsonArray("cve");
    if (jsonCve != null) {
        String[] cve = new String[jsonCve.size()];
        for (int i = 0; i < jsonCve.size(); i++) {
            cve[i] = jsonCve.get(i).getAsString();
        }
        exploit.setCve(cve);
    }

    JsonArray jsonMsb = jsonObject.getAsJsonArray("msb");
    if (jsonMsb != null) {
        String[] msb = new String[jsonMsb.size()];
        for (int i = 0; i < jsonMsb.size(); i++) {
            msb[i] = jsonMsb.get(i).getAsString();
        }
        exploit.setMsb(msb);
    }

    JsonArray jsonOsvdb = jsonObject.getAsJsonArray("osvdb");
    if (jsonOsvdb != null) {
        String[] osvdb = new String[jsonOsvdb.size()];
        for (int i = 0; i < jsonOsvdb.size(); i++) {
            osvdb[i] = jsonOsvdb.get(i).getAsString();
        }
        exploit.setOsvdb(osvdb);
    }

    try {
        JsonArray jsonPlatform = jsonObject.getAsJsonArray("platform");
        if (jsonPlatform != null && jsonPlatform.isJsonArray()) {
            String[] platform = new String[jsonPlatform.size()];
            for (int i = 0; i < jsonPlatform.size(); i++) {
                platform[i] = jsonPlatform.get(i).getAsString();
            }
            exploit.setPlatform(platform);
        }
    } catch (ClassCastException err) {
        JsonElement platPrimitive = jsonObject.get("platform");
        if (platPrimitive != null && !platPrimitive.isJsonNull()) {
            exploit.setPlatform(new String[] { platPrimitive.getAsString() });
        }
    }

    exploit.setId(id);
    exploit.setDescription(desc);
    exploit.setSource(source);

    return exploit;
}