Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:org.ms123.common.datamapper.JsonMetaData.java

License:Open Source License

private JsonElement getFirstChild(JsonArray array) {
    Iterator i = array.iterator();
    if (i.hasNext()) {
        return (JsonElement) i.next();
    }/*  w  w w.  j a v a2 s  .  com*/
    return null;
}

From source file:org.openbaton.monitoring.agent.ZabbixMonitoringAgent.java

License:Apache License

@Override
public String createPMJob(ObjectSelection objectSelection, List<String> performanceMetrics,
        List<String> performanceMetricGroup, Integer collectionPeriod, Integer reportingPeriod)
        throws MonitoringException {
    if (objectSelection == null || objectSelection.getObjectInstanceIds().isEmpty())
        throw new MonitoringException("The objectSelection is null or empty");
    if (performanceMetrics == null && performanceMetricGroup == null)
        throw new MonitoringException(
                "At least performanceMetrics or performanceMetricGroup need to be present");
    if (collectionPeriod < 0 || reportingPeriod < 0)
        throw new MonitoringException("The collectionPeriod or reportingPeriod is negative");
    PmJob pmJob = null;//from  w w  w. j a  v a 2  s  . c  om
    try {
        if (performanceMetrics == null || performanceMetrics.isEmpty())
            throw new MonitoringException("PerformanceMetrics is null");
        pmJob = new PmJob(objectSelection, collectionPeriod);
        for (String hostname : objectSelection.getObjectInstanceIds()) {
            String hostId = zabbixApiManager.getHostId(hostname);
            String interfaceId = zabbixApiManager.getHostInterfaceId(hostId);
            for (String performanceMetric : performanceMetrics) {
                log.debug("The performance metric is: " + performanceMetric);
                int type = getType(collectionPeriod);
                // Check for wildcard
                if (performanceMetric.contains("*")) {
                    // Get the host list
                    log.debug("The performance metric is a wildcard");
                    String params = "{'output': ['itemid','key_']," + "'hostids': '" + hostId
                            + "' ,'search': {'key_':'" + performanceMetric
                            + "' },'searchWildcardsEnabled': 'true' }";
                    String method = "item.get";
                    //log.debug(params);
                    JsonObject items = callPost(params, method);
                    //log.debug(items.toString());
                    JsonArray itemArray = items.get("result").getAsJsonArray();
                    Iterator<JsonElement> iterator = itemArray.iterator();
                    while (iterator.hasNext()) {
                        JsonObject jsonObj = iterator.next().getAsJsonObject();
                        String itemId = jsonObj.getAsJsonObject().get("itemid").getAsString();
                        String key = jsonObj.getAsJsonObject().get("key_").getAsString();
                        if (itemId != null) {
                            //log.debug(itemId + " : " + key);
                            pmJob.addPerformanceMetric(itemId, key);
                        }
                    }
                } else {
                    // check already exists
                    String itemId = zabbixApiManager.getItemId(performanceMetric, hostId);

                    if (itemId != null) {
                        pmJob.addPerformanceMetric(itemId, performanceMetric);
                        continue;
                    }

                    //Check if is present a LLD
                    if (isPrototype(performanceMetric)) {

                        String ruleId = zabbixApiManager.getRuleId(hostId);
                        itemId = zabbixApiManager.createPrototypeItem(collectionPeriod, hostId, interfaceId,
                                performanceMetric, "ZabbixPrototypeItem on demand: " + performanceMetric, type,
                                0, ruleId);
                        pmJob.addPerformanceMetric(itemId, performanceMetric);
                    } else {
                        itemId = zabbixApiManager.createItem("ZabbixItem on demand: " + performanceMetric,
                                collectionPeriod, hostId, type, 0, performanceMetric, interfaceId);
                        pmJob.addPerformanceMetric(itemId, performanceMetric);
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new MonitoringException("The Pm job cannot be created: " + e.getMessage(), e);
    }
    pmJobs.put(pmJob.getPmjobId(), pmJob);
    return pmJob.getPmjobId();
}

From source file:org.opendaylight.vtn.javaapi.openstack.validation.PortResourceValidator.java

License:Open Source License

/**
 * Validates the parameters of POST request body
 * /*from  ww w .j a va 2  s.c  o m*/
 * @param requestBody
 *            - JSON request body corresponding to POST operation
 * @return
 */
public boolean validatePost(final JsonObject requestBody) {
    LOG.trace("Start PortResourceValidator#validatePost()");
    boolean isValid = true;
    // validation of mandatory parameters
    if (requestBody == null || !requestBody.has(VtnServiceOpenStackConsts.PORT)
            || !requestBody.has(VtnServiceOpenStackConsts.DATAPATH_ID)
            || !requestBody.has(VtnServiceOpenStackConsts.VID)) {
        isValid = false;
        setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
    } else {
        // validation of id
        if (requestBody.has(VtnServiceOpenStackConsts.ID)) {
            final JsonElement id = requestBody.get(VtnServiceOpenStackConsts.ID);
            if (id.isJsonNull() || id.getAsString().isEmpty()
                    || !validator.isValidMaxLengthAlphaNum(id.getAsString(), VtnServiceJsonConsts.LEN_24)) {
                isValid = false;
                setInvalidParameter(VtnServiceOpenStackConsts.ID + VtnServiceConsts.COLON
                        + (id.isJsonNull() ? id : id.getAsString()));
            }
        }

        // validation of datapath_id
        if (isValid) {
            final JsonElement datapathId = requestBody.get(VtnServiceOpenStackConsts.DATAPATH_ID);
            setInvalidParameter(VtnServiceOpenStackConsts.DATAPATH_ID);
            if (datapathId.isJsonNull() || !isValidDataPathId(datapathId.getAsString())) {
                isValid = false;
                setInvalidParameter(VtnServiceOpenStackConsts.DATAPATH_ID + VtnServiceConsts.COLON
                        + (datapathId.isJsonNull() ? datapathId : datapathId.getAsString()));
            }
        }

        // validation of port
        if (isValid) {
            final JsonElement port = requestBody.get(VtnServiceOpenStackConsts.PORT);
            if (!port.isJsonNull() && !port.getAsString().equalsIgnoreCase(VtnServiceOpenStackConsts.NULL)) {
                if (port.getAsString().isEmpty()) {
                    isValid = false;
                } else {
                    try {
                        isValid = validator.isValidBigIntegerRangeString(new BigInteger(port.getAsString()),
                                VtnServiceJsonConsts.BIG_VAL0, VtnServiceJsonConsts.BIG_VAL_4294967040);
                    } catch (Exception e) {
                        isValid = false;
                    }
                }

                // set message as per above checks
                if (!isValid) {
                    setInvalidParameter(VtnServiceOpenStackConsts.PORT + VtnServiceConsts.COLON
                            + (port.isJsonNull() ? port : port.getAsString()));
                }
            }
        }

        // validation of vid
        if (isValid) {
            final JsonElement vid = requestBody.get(VtnServiceOpenStackConsts.VID);
            setInvalidParameter(VtnServiceOpenStackConsts.VID);
            if (vid.isJsonNull() || vid.getAsString().isEmpty()) {
                isValid = false;
            } else {
                try {
                    isValid = validator.isValidRange(vid.getAsString(), VtnServiceJsonConsts.VAL_1,
                            VtnServiceJsonConsts.VAL_4095);
                    if (Integer.parseInt(vid.getAsString()) == VtnServiceJsonConsts.VAL_65535) {
                        isValid = true;
                    }
                } catch (Exception e) {
                    isValid = false;
                }
            }

            // set message as per above checks
            if (!isValid) {
                setInvalidParameter(VtnServiceOpenStackConsts.VID + VtnServiceConsts.COLON
                        + (vid.isJsonNull() ? vid : vid.getAsString()));
            }
        }

        // validation of filters.
        if (isValid) {
            setInvalidParameter(VtnServiceOpenStackConsts.FILTERS);
            if (requestBody.has(VtnServiceOpenStackConsts.FILTERS)) {
                if (requestBody.get(VtnServiceOpenStackConsts.FILTERS).isJsonArray()) {
                    if (requestBody.getAsJsonArray(VtnServiceOpenStackConsts.FILTERS).size() > 0) {
                        JsonArray filters = requestBody.getAsJsonArray(VtnServiceOpenStackConsts.FILTERS);
                        Iterator<JsonElement> iterator = filters.iterator();
                        while (iterator.hasNext()) {
                            JsonElement filterID = iterator.next();
                            if (filterID.isJsonPrimitive()) {
                                isValid = isValidFilterId(filterID.getAsString());
                                // Set message as per above checks
                                if (!isValid) {
                                    setInvalidParameter(VtnServiceOpenStackConsts.FILTER_RES_ID
                                            + VtnServiceConsts.COLON + filterID.getAsString());
                                    LOG.debug("Invalid flow filter id: %s", filterID.getAsString());
                                    break;
                                }
                            } else {
                                setInvalidParameter(
                                        UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
                                isValid = false;
                                break;
                            }
                        }
                    }
                } else {
                    setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
                    isValid = false;
                }
            }
            // filters is not specified, The isValid is true.
        }
    }

    if (isValid) {
        final JsonElement port = requestBody.get(VtnServiceOpenStackConsts.PORT);
        if (port.isJsonNull() || port.getAsString().equalsIgnoreCase(VtnServiceOpenStackConsts.NULL)) {
            if (requestBody.has(VtnServiceOpenStackConsts.FILTERS)
                    && requestBody.getAsJsonArray(VtnServiceOpenStackConsts.FILTERS).size() > 0) {
                isValid = false;
                setInvalidParameter("filters,but no port");
            }
        }
    }

    // validation of port and datapath_id combination
    if (isValid) {
        final JsonElement port = requestBody.get(VtnServiceOpenStackConsts.PORT);
        final JsonElement datapathid = requestBody.get(VtnServiceOpenStackConsts.DATAPATH_ID);
        if (datapathid.getAsString().isEmpty() && (!port.isJsonNull()
                && !port.getAsString().equalsIgnoreCase(VtnServiceOpenStackConsts.NULL))) {
            isValid = false;
            setInvalidParameter("port specified, but datapath_id not " + "specified");
        }
    }
    LOG.trace("Complete PortResourceValidator#validatePost()");
    return isValid;
}

From source file:org.opendaylight.vtn.javaapi.resources.openstack.PortsResource.java

License:Open Source License

/**
 * Perform Filter related operations at UNC
 * //from   w  w w  .  ja v a 2 s. com
 * @param requestBody
 *            - OpenStack request body
 * @param restResource
 *            - RestResource instance
 * @param connection
 *            - Database Connection instance
 * @return - erorrCode, 200 for Success
 * @throws SQLException 
 */
private int performFilterOperations(JsonObject requestBody, RestResource restResource, Connection connection)
        throws SQLException {
    int errorCode = UncResultCode.UNC_INTERNAL_SERVER_ERROR.getValue();

    /*
     * Delete duplicate flow filter.
     */
    Set<String> filterSet = new HashSet<String>();
    JsonArray filters = requestBody.getAsJsonArray(VtnServiceOpenStackConsts.FILTERS);
    Iterator<JsonElement> iterator = filters.iterator();
    while (iterator.hasNext()) {
        JsonElement element = iterator.next();
        filterSet.add(element.getAsString());

        // check filter id if exist.
        if (!hasFilterId(connection, element.getAsString())) {
            LOG.error("Resource not found error.");
            return UncResultCode.UNC_NOT_FOUND.getValue();
        }

        LOG.debug("filter_id: %s", element.getAsString());
    }

    /*
     * Create request body for type of filter creation
     */
    JsonObject flowFilterInRequestBody = new JsonObject();
    flowFilterInRequestBody.add(VtnServiceJsonConsts.FLOWFILTER, new JsonObject());
    flowFilterInRequestBody.get(VtnServiceJsonConsts.FLOWFILTER).getAsJsonObject()
            .addProperty(VtnServiceJsonConsts.FFTYPE, VtnServiceJsonConsts.IN);

    // send request.
    errorCode = createFlowFilterIn(requestBody, restResource, flowFilterInRequestBody);

    if (UncResultCode.UNC_SUCCESS.getValue() == errorCode) {
        LOG.info("filter in Creation at UNC is successful.");
        ArrayList<FlowFilterVbrBean> vbridgeList = new ArrayList<FlowFilterVbrBean>();
        for (String filterID : filterSet) {
            FlowFilterVbrBean vbrBean = new FlowFilterVbrBean();
            vbrBean.setVtnName(getTenantId());
            vbrBean.setVbrName(getNetId());
            vbrBean.setVbrIfName(requestBody.get(VtnServiceOpenStackConsts.ID).getAsString());
            vbrBean.setFlName(filterID);
            vbridgeList.add(vbrBean);
        }

        // Insert db for flow filter.
        final FlowFilterDao flowFilterDao = new FlowFilterDao();
        int status = flowFilterDao.insertVbridgeFilterInfo(connection, vbridgeList);
        if (1 == status) {
            LOG.info("Resource insertion successful at database " + "operation.");
            for (String filterID : filterSet) {
                /*
                 * Create request body for flow filter creation
                 */
                String action = VtnServiceOpenStackConsts.S_PASS;
                if (VtnServiceOpenStackConsts.X_DROP == filterID.charAt(4)) {
                    action = VtnServiceOpenStackConsts.S_DROP;
                }

                String priority = filterID.substring(5, 9);

                JsonObject flowFilterRequestBody = new JsonObject();
                flowFilterRequestBody.add(VtnServiceJsonConsts.FLOWFILTERENTRY, new JsonObject());
                JsonObject flowfilter = flowFilterRequestBody
                        .getAsJsonObject(VtnServiceJsonConsts.FLOWFILTERENTRY);
                flowfilter.addProperty(VtnServiceJsonConsts.SEQNUM,
                        String.valueOf((Integer.parseInt(priority, 16))));
                flowfilter.addProperty(VtnServiceJsonConsts.FLNAME, filterID);
                flowfilter.addProperty(VtnServiceJsonConsts.ACTIONTYPE, action);
                flowfilter.add(VtnServiceJsonConsts.REDIRECTDST, new JsonObject());

                // send request.
                errorCode = createFlowFilter(requestBody, restResource, flowFilterRequestBody);
                if (UncResultCode.UNC_SUCCESS.getValue() != errorCode) {
                    LOG.error("Failed to create flow filter entry(%s) " + "at UNC.", filterID);
                    break;
                }
            }
        } else {
            LOG.error("Failed to insert Resource(filter for interface " + "of vbridge) at database operation.");
            errorCode = UncResultCode.UNC_SERVER_ERROR.getValue();
        }
    } else {
        LOG.error("Failed to create type(in) of flow filter at UNC.");
    }

    return errorCode;
}

From source file:org.opendaylight.vtn.javaapi.validation.logical.VTepGroupResourceValidator.java

License:Open Source License

/**
 * validate put request Json object for VTepGroup API.
 * /*from   w w  w .ja  v  a  2  s  .c  o m*/
 * @param requestBody
 *            the request Json object
 * @return true, if successful
 * @throws VtnServiceException
 *             the vtn service exception
 */
private boolean validatePut(final JsonObject requestBody) throws VtnServiceException {
    LOG.trace("Start VTepGroupResourceValidator#validatePut()");
    boolean isValid = false;
    setInvalidParameter(VtnServiceJsonConsts.VTEPGROUP);
    if (requestBody.has(VtnServiceJsonConsts.VTEPGROUP)
            && requestBody.get(VtnServiceJsonConsts.VTEPGROUP).isJsonObject()) {
        isValid = true;
        final JsonObject vTep = requestBody.getAsJsonObject(VtnServiceJsonConsts.VTEPGROUP);
        setInvalidParameter(VtnServiceJsonConsts.MEMBERVTEPS);
        if (vTep.has(VtnServiceJsonConsts.MEMBERVTEPS)
                && vTep.get(VtnServiceJsonConsts.MEMBERVTEPS).isJsonArray()) {
            final JsonArray memberVtep = vTep.getAsJsonArray(VtnServiceJsonConsts.MEMBERVTEPS);
            final Iterator<JsonElement> vtep = memberVtep.iterator();
            while (vtep.hasNext()) {
                if (isValid) {
                    setInvalidParameter(VtnServiceJsonConsts.VTEPNAME);
                    final JsonObject vtepName = (JsonObject) vtep.next();
                    // validation for key: vtep_name(optinal)
                    if (vtepName.has(VtnServiceJsonConsts.VTEPNAME)
                            && vtepName.getAsJsonPrimitive(VtnServiceJsonConsts.VTEPNAME).getAsString() != null
                            && !vtepName.getAsJsonPrimitive(VtnServiceJsonConsts.VTEPNAME).getAsString()
                                    .isEmpty()) {
                        isValid = validator.isValidMaxLengthAlphaNum(
                                vtepName.getAsJsonPrimitive(VtnServiceJsonConsts.VTEPNAME).getAsString(),
                                VtnServiceJsonConsts.LEN_31);
                    }
                }
            }
        }
    }
    LOG.trace("Complete VTepGroupResourceValidator#validatePut()");
    return isValid;
}

From source file:org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter.java

License:Open Source License

private List<Object> handleJsonArray(JsonElement entry) {
    List<Object> array = new ArrayList<>();
    JsonArray jsonArray = entry.getAsJsonArray();
    Iterator<JsonElement> iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        Object object;/*from ww w  . j av  a  2s. c  o m*/
        JsonElement element = iterator.next();
        if (element.isJsonPrimitive()) {
            object = json2JavaPrimitive(element.getAsJsonPrimitive());
        } else {
            object = handleComplexJsonValue(element);
        }
        array.add(object);
    }
    return array;
}

From source file:org.opengrid.data.impl.PlenarioDataProvider.java

private String getFeatures(JsonArray jsonArray, OpenGridDataset desc)
        throws ServiceException, JsonParseException, JsonMappingException, IOException {
    StringBuilder sb = new StringBuilder();

    Iterator itr = jsonArray.iterator();
    int i = 0;/*from ww w  . j a  va2  s  .  c o m*/

    while (itr.hasNext()) {
        if (i > 0)
            sb.append(",");

        sb.append(getFeature((JsonObject) itr.next(), desc));
        i++;
    }

    return sb.toString();
}

From source file:org.opengrid.data.impl.PlenarioDataProvider.java

private String getFeatures_New(String sURL, OpenGridDataset desc, int max)
        throws ServiceException, JsonParseException, JsonMappingException, IOException {
    StringBuilder sb = new StringBuilder();
    int count = 0;

    while (count < max) {
        if (count > 0) {
            sURL = sURL + "&offset=" + count;
        }/*from  w w w .j  a v a 2  s.c o  m*/
        com.google.gson.JsonObject rootobj = getJsonObjectFromURL(sURL);
        JsonArray jsonArray = (JsonArray) rootobj.get("objects");

        Iterator itr = jsonArray.iterator();
        int i = 0;

        while (itr.hasNext()) {
            if (i > 0 || (count < max && count > 0))
                sb.append(",");

            sb.append(getFeature((JsonObject) itr.next(), desc));
            i++;
        }

        if (i < 1000) {
            break;
        }

    }

    return sb.toString();
}

From source file:org.opengrid.data.impl.PlenarioDataProvider.java

private OpenGridMeta mapPlenarioToOpenGridMeta(JsonObject rootobj, boolean includeColumns, boolean cityOnly) {
    OpenGridMeta meta = new OpenGridMeta();

    try {/*www . j av a 2 s .com*/
        JsonArray objects = (JsonArray) rootobj.get("objects");
        List<OpenGridDataset> openGridDatasets = new ArrayList<OpenGridDataset>();

        Iterator itr = objects.iterator();

        String defaultAttribution = properties.getStringProperty("plenario.attribution.default");
        int counter = 0;
        String defaultDataset = properties.getStringProperty("plenario.dataset.default");

        while (itr.hasNext()) {
            OpenGridDataset dataset = getOpenGridDatasetFromPlenarioObject(defaultAttribution, defaultDataset,
                    (JsonObject) itr.next(), includeColumns, cityOnly, counter);
            if (dataset != null) {
                openGridDatasets.add(dataset);
            }
            counter++;
            // if(openGridDatasets.size()> 5)
            // break;
        }
        meta.setDatasets(openGridDatasets);

    } catch (Exception e) {
        throw new ServiceException("Error processing Plenar.io Datasets API.");
    }

    return meta;

}

From source file:org.opengrid.data.impl.PlenarioDataProvider.java

private List<OpenGridColumn> getColumnsForDataset(JsonObject rootobj) {
    List<OpenGridColumn> columns = new ArrayList<OpenGridColumn>();

    try {//from w  w  w.  j a v a2  s  .  co  m
        JsonArray objects = (JsonArray) rootobj.get("objects");
        List<OpenGridDataset> openGridDatasets = new ArrayList<OpenGridDataset>();

        Iterator itr = objects.iterator();
        int count = 1;

        while (itr.hasNext()) {
            OpenGridColumn column = new OpenGridColumn();
            JsonObject object = (JsonObject) (itr.next());

            column.setDisplayName(object.get("field_name").toString().replace("\"", ""));
            column.setId(object.get("field_name").toString().replace("\"", ""));
            column.setDataType(
                    getOpenDataGridTypeFromPlenario(object.get("field_type").toString().replace("\"", "")));

            column.setPopup(shouldColumnBeInPopup(object.get("field_name").toString().replace("\"", "")));
            column.setFilter(shouldColumnBeInPopup(object.get("field_name").toString().replace("\"", "")));
            column.setGroupBy(shouldColumnBeInGroupBy(object.get("field_name").toString().replace("\"", "")));
            column.setQuickSearch(
                    shouldColumnBeInQuickSearch(object.get("field_name").toString().replace("\"", "")));

            if (!IgnoreColumn(object.get("field_name").toString().replace("\"", ""))) {
                column.setList(true);
                column.setSortOrder(count);
                count++;
            }
            columns.add(column);
        }

        return columns;

    } catch (Exception e) {
        throw new ServiceException("Error accessing Plenar.io Datasets API.");
    }
}