Example usage for com.google.gson JsonElement isJsonNull

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

Introduction

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

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:org.nordapp.web.util.GsonHashMapDeserializer.java

License:Apache License

public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonNull())
        return null;
    else if (json.isJsonPrimitive())
        return handlePrimitive(json.getAsJsonPrimitive());
    else if (json.isJsonArray())
        return handleArray(json.getAsJsonArray(), context);
    else/* w  w w.  j  a v  a  2  s.c om*/
        return handleObject(json.getAsJsonObject(), context);
}

From source file:org.odk.collect.android.application.Collect.java

License:Apache License

public void beginGetSurveys(Context ctx) {
    Ctx = ctx;//from   w  ww.ja v  a2 s.c  om

    try {
        MobileServiceClient client = new MobileServiceClient("https://flikkodk.azure-mobile.net/",
                "SenCBSjDhFGTRqbwhDMiKKZJSxBhGK39", Ctx);

        PropertyManager manager = new PropertyManager(this);
        String userName = manager.getSingularProperty("username");
        String userNameSpaced = userName.replace('_', ' ');

        client.getTable("Survey").where().field("Completed").eq(false).and().field("surveyorname")
                .eq(userNameSpaced).execute(new TableJsonQueryCallback() {
                    @Override
                    public void onCompleted(JsonElement result, int count, Exception exception,
                            ServiceFilterResponse response) {
                        if (exception == null) {
                            Log.d("Azure", result.toString());
                            JsonArray res = (JsonArray) result;
                            Surveys = new JsonArray();
                            for (JsonElement e : res) {
                                try {
                                    JsonObject o = (JsonObject) e;
                                    if (e != null) {
                                        JsonElement address1 = o.get("address1");
                                        if (address1.isJsonNull()) {
                                        } else if (address1.getAsString().length() == 0) {
                                        } else {
                                            Surveys.add(e);
                                        }
                                    }
                                } catch (Exception ex) {
                                }
                            }
                            sendBroadcast(SurveysUpdatedKey);
                        } else {
                            Log.wtf("Azure", exception.getMessage());
                            //receivedMessage = exception.getMessage();
                        }
                    }
                });

    } catch (MalformedURLException e) {

    }

}

From source file:org.odk.collect.android.application.Collect.java

License:Apache License

public Intent getStartSurveyIntent(int surveyIndex) {
    //get the item we are on
    JsonObject o = (JsonObject) Surveys.get(surveyIndex);
    if (o != null) {
        StringBuilder sb = new StringBuilder();
        JsonElement surveyTypeCode = o.get("SurveyTypeCode");
        JsonElement address1 = o.get("address1");
        JsonElement address2 = o.get("address2");
        JsonElement surveynumber = o.get("surveynumber");
        if (surveyTypeCode.isJsonNull() || surveyTypeCode.getAsString().length() == 0)
            sb.append("No Survey Type ");
        String address = "";
        if (!address1.isJsonNull() && address1.getAsString().length() > 0) {
            address += address1.getAsString();
        }// w ww  . ja  v  a2  s.c om
        if (!address2.isJsonNull() && address2.getAsString().length() > 0) {
            address += address2.getAsString();
        }
        if (address.length() == 0)
            sb.append("No Address ");
        if (surveynumber.isJsonNull() || surveynumber.getAsString().length() == 0)
            sb.append("No Survey Number Type");

        if (sb.length() > 0) {
            Toast toast = Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG);
            return null;
        }

        String mFormPath = getBlankFormPath(surveyTypeCode.getAsString());

        if (mFormPath == null) {
            Toast toast = Toast.makeText(this,
                    String.format("Could not find a Form for %s. Please Download Blank Forms.",
                            surveyTypeCode.getAsString()),
                    Toast.LENGTH_LONG);
            return null;
        }

        //find the uri of the form in the SQLLite database
        Uri formUri = Uri.parse(mFormPath);
        Intent intent = new Intent(Intent.ACTION_EDIT, formUri);
        intent.putExtra("flikk", o.toString());
        //intent.setDataAndType(Uri.parse("vnd.android.cursor.item/vnd.odk.form"), mFormPath);

        //new Intent(ACTION_EDIT,
        //        Uri.parse(FormsProviderAPI.FormsColumns.FLIKK_SURVEY_TYPE))
        //startActivity(intent);

        return intent;

    }

    return null;
}

From source file:org.openbaton.clients.interfaces.client.openstack.OpenstackClient.java

License:Apache License

private List<String> listFreeFloatingIps(VimInstance vimInstance) throws VimDriverException {
    log.debug("Listing all free FloatingIPs of VimInstance with name: " + vimInstance.getName());
    String tenantId = getTenantId(vimInstance);
    try {/*from w ww .  ja  va2s  .c om*/
        NovaApi novaApi = ContextBuilder.newBuilder("openstack-nova").endpoint(vimInstance.getAuthUrl())
                .credentials(vimInstance.getTenant() + ":" + vimInstance.getUsername(),
                        vimInstance.getPassword())
                .modules(modules).overrides(overrides).buildApi(NovaApi.class);
        NeutronApi neutronApi = ContextBuilder.newBuilder("openstack-neutron")
                .endpoint(vimInstance.getAuthUrl())
                .credentials(vimInstance.getTenant() + ":" + vimInstance.getUsername(),
                        vimInstance.getPassword())
                .modules(modules).overrides(overrides).buildApi(NeutronApi.class);

        //      if (novaApi.getFloatingIPApi(getZone(vimInstance)).isPresent()){
        boolean floatingIpApiNotPresent = false;
        Optional<FloatingIPApi> neutronApiFloatingIPApi = null;
        try {
            neutronApiFloatingIPApi = neutronApi.getFloatingIPApi(getZone(vimInstance));
        } catch (Exception e) {
            floatingIpApiNotPresent = true;
        }

        if (!floatingIpApiNotPresent && neutronApiFloatingIPApi.isPresent()) {
            FloatingIPApi floatingIPApi = neutronApiFloatingIPApi.get();

            //        org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi floatingIPApi =
            //            novaApi.getFloatingIPApi(getZone(vimInstance)).get();
            List<String> floatingIPs = new LinkedList<String>();

            for (FloatingIP floatingIP : floatingIPApi.list(new PaginationOptions())) {
                if (floatingIP.getTenantId().equals(tenantId) && floatingIP.getFixedIpAddress() == null) {
                    floatingIPs.add(floatingIP.getFloatingIpAddress() /*getFloatingIpAddress()*/);
                }
            }
            log.info("Listed all free FloatingIPs of VimInstance with name: " + vimInstance.getName()
                    + " -> free FloatingIPs: " + floatingIPs);
            return floatingIPs;
        } else {
            /*
            REQ: curl -i http://192.168.45.101:9696/v2.0/floatingips.json -X GET -H "X-Auth-Token: ..." -H
            "Content-Type: application/json" -H "Accept: application/json" -H "User-Agent: python-neutronclient"
             */

            URI endpoint = null;
            ContextBuilder contextBuilder = ContextBuilder.newBuilder("openstack-nova")
                    .credentials(vimInstance.getUsername(), vimInstance.getPassword())
                    .endpoint(vimInstance.getAuthUrl());
            ComputeServiceContext context = contextBuilder.buildView(ComputeServiceContext.class);
            Function<Credentials, Access> auth = context.utils().injector()
                    .getInstance(Key.get(new TypeLiteral<Function<Credentials, Access>>() {
                    }));

            Access access = auth.apply(new Credentials.Builder<>()
                    .identity(vimInstance.getTenant() + ":" + vimInstance.getUsername())
                    .credential(vimInstance.getPassword()).build());

            log.debug("listing FloatingIPs: finding endpoint");
            for (org.jclouds.openstack.keystone.v2_0.domain.Service service : access) {
                if (service.getName().equals("neutron")) {
                    for (Endpoint end : service) {
                        endpoint = end.getPublicURL();
                        break;
                    }
                    break;
                }
            }

            HttpURLConnection connection = null;
            URL url = new URL(endpoint + "/v2.0/floatingips.json");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("User-Agent", "python-neutronclient");
            connection.setRequestProperty("X-Auth-Token", access.getToken().getId());

            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            //Parse json to object
            log.debug("List of FloatingIPs: Response of final request is: " + response.toString());

            JsonObject res = new GsonBuilder().setPrettyPrinting().create().fromJson(response.toString(),
                    JsonObject.class);

            log.debug("JsonObject is: " + res);

            List<String> result = new ArrayList<>();
            if (res.has("floatingips")) {
                for (JsonElement element : res.get("floatingips").getAsJsonArray()) {
                    log.debug("FloatingIp is: " + element.getAsJsonObject());
                    JsonElement fixed_ip_address = element.getAsJsonObject().get("fixed_ip_address");
                    JsonElement tenant_id = element.getAsJsonObject().get("tenant_id");
                    if (!fixed_ip_address.isJsonNull() || !tenant_id.getAsString().equals(tenantId)) {
                        //              log.debug("FixedIpAddress is: " + fixed_ip_address);
                        continue;
                    }

                    String floating_ip_address = element.getAsJsonObject().get("floating_ip_address")
                            .getAsString();
                    log.debug("found ip: " + floating_ip_address);
                    result.add(floating_ip_address);
                }
            } else {
                log.warn("Was not possible through Openstack ReST api to retrieve all the FloatingIP");
            }
            log.info("Free Floating ips are: " + result);
            return result;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new VimDriverException(e.getMessage());
    }
}

From source file:org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeReader.java

License:Open Source License

public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
    JsonParser parser = new JsonParser();

    JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream)));
    if (rootElement.isJsonNull()) {
        // no content, so return null to indicate no input
        return null;
    }//from   www. j  av  a 2 s. c  o  m

    if (!rootElement.isJsonObject()) {
        throw new UnsupportedFormatException("Root element of Json has to be Object");
    }

    Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
    if (entrySetsOfRootJsonObject.size() != 1) {
        throw new UnsupportedFormatException("Json Object should contain one element");
    }

    Entry<String, JsonElement> childEntry = entrySetsOfRootJsonObject.iterator().next();
    String firstElementName = childEntry.getKey();
    JsonElement firstElementType = childEntry.getValue();
    if (firstElementType.isJsonObject()) {
        // container in yang
        return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
    }
    if (firstElementType.isJsonArray()) {
        // list in yang
        if (firstElementType.getAsJsonArray().size() == 1) {
            JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
            if (firstElementInArray.isJsonObject()) {
                return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
            }
            throw new UnsupportedFormatException(
                    "Array as the first element in Json Object can have only Object element");
        }
    }
    throw new UnsupportedFormatException(
            "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
}

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

License:Open Source License

/**
 * Validates the parameters of PUT request body
 * /*from  w  ww  .  j  a  v a  2  s  .  c  o  m*/
 * @param requestBody
 *            - JSON request body corresponding to PUT operation
 * @return - validation status as true or false
 */
private boolean validatePut(JsonObject requestBody) {
    LOG.trace("Start DestinationControllerResourceValidator#validatePut()");
    boolean isValid = true;
    // 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_31)) {
            isValid = false;
            setInvalidParameter(VtnServiceOpenStackConsts.ID + VtnServiceConsts.COLON
                    + (id.isJsonNull() ? id : id.getAsString()));
        }
    } else {
        isValid = false;
        setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
    }
    LOG.trace("Complete DestinationControllerResourceValidator#validatePut()");
    return isValid;
}

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

License:Open Source License

/**
 * Validates the parameters of POST request body.
 * /* w  w w.j a v a  2  s .  co  m*/
 * @param requestBody
 *            - JSON request body corresponding to POST operation
 * @return
 */
private boolean validatePost(final JsonObject requestBody) {
    LOG.trace("Start FilterResourceValidator#validatePost()");

    boolean isValid = false;
    if (null == requestBody) {
        setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
    } else if (!requestBody.has(VtnServiceOpenStackConsts.ACTION)) {
        setInvalidParameter("no action");
    } else if (!requestBody.has(VtnServiceOpenStackConsts.PRIORITY)) {
        setInvalidParameter("no priority");
    } else {
        /* Check id. */
        String idValue = "";
        if (requestBody.has(VtnServiceOpenStackConsts.ID)) {
            JsonElement id = requestBody.get(VtnServiceOpenStackConsts.ID);
            if (id.isJsonNull() || id.getAsString().isEmpty() || !isValidFilterId(id.getAsString())) {
                setInvalidParameter(VtnServiceOpenStackConsts.ID + VtnServiceConsts.COLON
                        + (id.isJsonNull() ? id : id.getAsString()));
                return isValid;
            } else {
                idValue = id.getAsString();
            }
        }

        /* Check action. */
        JsonElement action = requestBody.get(VtnServiceOpenStackConsts.ACTION);
        if (action.isJsonNull() || action.getAsString().isEmpty()
                || (!action.getAsString().equals(VtnServiceJsonConsts.PASS)
                        && !action.getAsString().equals(VtnServiceJsonConsts.DROP))) {
            setInvalidParameter(VtnServiceOpenStackConsts.ACTION + VtnServiceConsts.COLON
                    + (action.isJsonNull() ? action : action.getAsString()));
            return isValid;
        }
        if (!idValue.isEmpty() && idValue.charAt(4) != action.getAsString().charAt(0)) {
            /* "id:" + idValue + "," + "action:" + action.getAsString() */
            setInvalidParameter(
                    VtnServiceOpenStackConsts.ID + VtnServiceConsts.COLON + idValue + VtnServiceConsts.COMMA
                            + VtnServiceOpenStackConsts.ACTION + VtnServiceConsts.COLON + action.getAsString());
            return isValid;
        }

        /* Check priority. */
        JsonElement priority = requestBody.get(VtnServiceOpenStackConsts.PRIORITY);
        if (priority.isJsonNull() || priority.getAsString().isEmpty()) {
            isValid = false;
        } else {
            try {
                isValid = validator.isValidRange(priority.getAsString(), VtnServiceJsonConsts.VAL_1,
                        VtnServiceJsonConsts.VAL_32766);
            } catch (Exception e) {
                isValid = false;
            }
        }
        if (!isValid) {
            setInvalidParameter(VtnServiceOpenStackConsts.PRIORITY + VtnServiceConsts.COLON
                    + (priority.isJsonNull() ? priority : priority.getAsString()));
        } else if (!idValue.isEmpty()) {
            int val1 = Integer.parseInt(idValue.substring(5, 9), 16);
            int val2 = Integer.parseInt(priority.getAsString());
            if (val1 != val2) {
                /*
                 * "id:" + idValue + "," + "priority:" +
                 * priority.getAsString()
                 */
                setInvalidParameter(VtnServiceOpenStackConsts.ID + VtnServiceConsts.COLON + idValue
                        + VtnServiceConsts.COMMA + VtnServiceOpenStackConsts.PRIORITY + VtnServiceConsts.COLON
                        + priority.getAsString());
                return false;
            }
        }
    }

    if (isValid) {
        isValid = validatePut(requestBody);
    }
    LOG.trace("Complete FilterResourceValidator#validatePost()");
    return isValid;
}

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

License:Open Source License

/**
 * Validates the parameters of PUT request body.
 * /*from   www  .  j a  va2  s  .  com*/
 * @param requestBody
 *            - JSON request body corresponding to PUT operation
 * @return - validation status as true or false
 */
private boolean validatePut(final JsonObject requestBody) {
    LOG.trace("Start FilterResourceValidator#validatePut()");
    boolean isValid = false;

    /* Check src_mac. */
    if (requestBody.has(VtnServiceOpenStackConsts.SRC_MAC)) {
        JsonElement srcMac = requestBody.get(VtnServiceOpenStackConsts.SRC_MAC);
        if (srcMac.isJsonNull() || (!srcMac.getAsString().isEmpty()
                && !srcMac.getAsString().matches(VtnServiceOpenStackConsts.OS_MAC_ADD_REGEX))) {
            setInvalidParameter(VtnServiceOpenStackConsts.SRC_MAC + VtnServiceConsts.COLON
                    + (srcMac.isJsonNull() ? srcMac : srcMac.getAsString()));
            return isValid;
        }
    }

    /* Check dst_mac. */
    if (requestBody.has(VtnServiceOpenStackConsts.DST_MAC)) {
        JsonElement dstMac = requestBody.get(VtnServiceOpenStackConsts.DST_MAC);
        if (dstMac.isJsonNull() || (!dstMac.getAsString().isEmpty()
                && !dstMac.getAsString().matches(VtnServiceOpenStackConsts.OS_MAC_ADD_REGEX))) {
            setInvalidParameter(VtnServiceOpenStackConsts.DST_MAC + VtnServiceConsts.COLON
                    + (dstMac.isJsonNull() ? dstMac : dstMac.getAsString()));
            return isValid;
        }
    }

    /* Check eth_type. */
    if (requestBody.has(VtnServiceOpenStackConsts.ETH_TYPE)) {
        JsonElement ethType = requestBody.get(VtnServiceOpenStackConsts.ETH_TYPE);
        if (ethType.isJsonNull()) {
            isValid = false;
        } else if (ethType.getAsString().isEmpty()) {
            isValid = true;
        } else {
            try {
                isValid = ethType.getAsString().matches(VtnServiceConsts.ETH_TYPE_REGEX);
            } catch (Exception e) {
                isValid = false;
            }
        }

        if (!isValid) {
            setInvalidParameter(VtnServiceOpenStackConsts.ETH_TYPE + VtnServiceConsts.COLON
                    + (ethType.isJsonNull() ? ethType : ethType.getAsString()));
            return isValid;
        }
    }

    isValid = false;
    /* Check src_cidr. */
    if (requestBody.has(VtnServiceOpenStackConsts.SRC_CIDR)) {
        JsonElement srcCidr = requestBody.get(VtnServiceOpenStackConsts.SRC_CIDR);
        if (srcCidr.isJsonNull() || (!srcCidr.getAsString().isEmpty() && !isValidIp(srcCidr.getAsString()))) {
            setInvalidParameter(VtnServiceOpenStackConsts.SRC_CIDR + VtnServiceConsts.COLON
                    + (srcCidr.isJsonNull() ? srcCidr : srcCidr.getAsString()));
            return isValid;
        }
    }

    /* Check dst_cidr. */
    if (requestBody.has(VtnServiceOpenStackConsts.DST_CIDR)) {
        JsonElement dstCidr = requestBody.get(VtnServiceOpenStackConsts.DST_CIDR);
        if (dstCidr.isJsonNull() || (!dstCidr.getAsString().isEmpty() && !isValidIp(dstCidr.getAsString()))) {
            setInvalidParameter(VtnServiceOpenStackConsts.DST_CIDR + VtnServiceConsts.COLON
                    + (dstCidr.isJsonNull() ? dstCidr : dstCidr.getAsString()));
            return isValid;
        }
    }

    /* Check protocol. */
    int protocolVal = 0;
    if (requestBody.has(VtnServiceOpenStackConsts.PROTOCOL)) {
        JsonElement protocol = requestBody.get(VtnServiceOpenStackConsts.PROTOCOL);
        if (protocol.isJsonNull()) {
            isValid = false;
        } else if (protocol.getAsString().isEmpty()) {
            isValid = true;
        } else {
            try {
                isValid = validator.isValidRange(protocol.getAsString(), VtnServiceJsonConsts.VAL_1,
                        VtnServiceJsonConsts.VAL_255);
            } catch (Exception e) {
                isValid = false;
            }
        }
        if (!isValid) {
            setInvalidParameter(VtnServiceOpenStackConsts.PROTOCOL + VtnServiceConsts.COLON
                    + (protocol.isJsonNull() ? protocol : protocol.getAsString()));
            return isValid;
        } else if (!protocol.getAsString().isEmpty()) {
            protocolVal = Integer.parseInt(protocol.getAsString());
        }
    }

    isValid = false;
    /* Check src_port. */
    if (requestBody.has(VtnServiceOpenStackConsts.SRC_PORT)) {
        JsonElement srcPort = requestBody.get(VtnServiceOpenStackConsts.SRC_PORT);
        if (srcPort.isJsonNull()
                || (!srcPort.getAsString().isEmpty() && !isValidPort(protocolVal, srcPort.getAsString()))) {
            setInvalidParameter(VtnServiceOpenStackConsts.SRC_PORT + VtnServiceConsts.COLON
                    + (srcPort.isJsonNull() ? srcPort : srcPort.getAsString()));
            return isValid;
        }
    }

    /* Check dst_port. */
    if (requestBody.has(VtnServiceOpenStackConsts.DST_PORT)) {
        JsonElement dstPort = requestBody.get(VtnServiceOpenStackConsts.DST_PORT);
        if (dstPort.isJsonNull()
                || (!dstPort.getAsString().isEmpty() && !isValidPort(protocolVal, dstPort.getAsString()))) {
            setInvalidParameter(VtnServiceOpenStackConsts.DST_PORT + VtnServiceConsts.COLON
                    + (dstPort.isJsonNull() ? dstPort : dstPort.getAsString()));
            return isValid;
        }
    }

    isValid = true;
    /* Check apply_ports. */
    if (requestBody.has(VtnServiceOpenStackConsts.APPLY_PORTS)) {
        JsonElement applyPorts = requestBody.get(VtnServiceOpenStackConsts.APPLY_PORTS);
        isValid = isValidApplyPort(applyPorts);
    }

    LOG.trace("Complete FilterResourceValidator#validatePut()");
    return isValid;
}

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

License:Open Source License

/**
 * Check the validity of applyPort.// w  w  w.  j  a v  a  2 s.c om
 * 
 * @param protocol
 *            - protocol value
 * @param port
 *            - port value
 * @return - result as true or false
 */
private boolean isValidApplyPort(JsonElement applyPort) {
    boolean isValid = false;

    if (applyPort.isJsonNull() || !applyPort.isJsonArray()) {
        setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
        return isValid;
    }

    JsonArray portArray = applyPort.getAsJsonArray();

    /* "apply_ports":[""] case, Invalid Format */
    /* "apply_ports":[{""}] case, Invalid Format */
    /* "apply_ports":[{}] case, Invalid Format */
    if (portArray.toString().equals("[\"\"]") || portArray.toString().equals("[{\"\"}]")
            || portArray.toString().equals("[{}]")) {
        setInvalidParameter(UncCommonEnum.UncResultCode.UNC_INVALID_FORMAT.getMessage());
        return isValid;
    }

    /* When "apply_ports":[] case. */
    if (portArray.size() == 0) {
        return true;
    }

    for (int i = 0; i < portArray.size(); i++) {
        JsonObject info = portArray.get(i).getAsJsonObject();

        if (!(info.has(VtnServiceOpenStackConsts.TENANT)
                && ((info.has(VtnServiceOpenStackConsts.NETWORK) && info.has(VtnServiceOpenStackConsts.PORT))
                        || (info.has(VtnServiceOpenStackConsts.ROUTER)
                                && info.has(VtnServiceOpenStackConsts.INTERFACE))))) {
            setInvalidParameter(createPortErrorMsg(info));
            return isValid;
        }

        /* Check tenant id. */
        JsonElement tenantId = info.get(VtnServiceOpenStackConsts.TENANT);
        if (tenantId.isJsonNull() || tenantId.getAsString().isEmpty()
                || !validator.isValidMaxLengthAlphaNum(tenantId.getAsString(), VtnServiceJsonConsts.LEN_31)) {
            setInvalidParameter(createPortErrorMsg(info));
            return isValid;
        }

        /* Check network id and port id. */
        if (info.has(VtnServiceOpenStackConsts.NETWORK)) {
            JsonElement netId = info.get(VtnServiceOpenStackConsts.NETWORK);
            if (netId.isJsonNull() || netId.getAsString().isEmpty()
                    || !validator.isValidMaxLengthAlphaNum(netId.getAsString(), VtnServiceJsonConsts.LEN_31)) {
                setInvalidParameter(createPortErrorMsg(info));
                return isValid;
            }

            JsonElement portId = info.get(VtnServiceOpenStackConsts.PORT);
            if (portId.isJsonNull() || portId.getAsString().isEmpty()
                    || !validator.isValidMaxLengthAlphaNum(portId.getAsString(), VtnServiceJsonConsts.LEN_24)) {
                setInvalidParameter(createPortErrorMsg(info));
                return isValid;
            }
        }

        /* Check router id and interface id. */
        if (info.has(VtnServiceOpenStackConsts.ROUTER)) {
            JsonElement routerId = info.get(VtnServiceOpenStackConsts.ROUTER);
            if (routerId.isJsonNull() || routerId.getAsString().isEmpty() || !validator
                    .isValidMaxLengthAlphaNum(routerId.getAsString(), VtnServiceJsonConsts.LEN_31)) {
                setInvalidParameter(createPortErrorMsg(info));
                return isValid;
            }

            JsonElement ifId = info.get(VtnServiceOpenStackConsts.INTERFACE);
            if (ifId.isJsonNull() || ifId.getAsString().isEmpty()
                    || !validator.isValidMaxLengthAlphaNum(ifId.getAsString(), VtnServiceJsonConsts.LEN_24)) {
                setInvalidParameter(createPortErrorMsg(info));
                return isValid;
            }
        }
    }

    return true;
}

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

License:Open Source License

/**
 * When port information is invalid, create error massage.
 * /* w w w  .  j  av  a2s  . c o m*/
 * @param info
 *            - Port information reference
 * @return - result as true or false
 */
private String createPortErrorMsg(final JsonObject info) {
    StringBuffer msg = new StringBuffer();

    /* Format1: apply_ports:{tenant:os_vtn_1,network:os_vbr_#2,port:1} */
    /* Format2: apply_ports:{tenant:os_vtn_1,router:os_vrt_#,interface:2} */

    /* Append "apply_ports:{tenant:" */
    msg.append(VtnServiceOpenStackConsts.APPLY_PORTS);
    msg.append(VtnServiceConsts.COLON);
    msg.append(VtnServiceConsts.OPEN_CURLY_BRACES);
    msg.append(VtnServiceOpenStackConsts.TENANT);
    msg.append(VtnServiceConsts.COLON);

    if (info.has(VtnServiceOpenStackConsts.TENANT)) {
        JsonElement tenantId = info.get(VtnServiceOpenStackConsts.TENANT);
        if (!(tenantId.isJsonNull() || tenantId.getAsString().isEmpty())) {
            /* Append "os_vtn_1" */
            msg.append(tenantId.getAsString());
        }
    }

    /* Append "," */
    msg.append(VtnServiceConsts.COMMA);

    if (info.has(VtnServiceOpenStackConsts.ROUTER) || info.has(VtnServiceOpenStackConsts.INTERFACE)) {
        /* Append "router:" */
        msg.append(VtnServiceOpenStackConsts.ROUTER);
        msg.append(VtnServiceConsts.COLON);

        if (info.has(VtnServiceOpenStackConsts.ROUTER)) {
            JsonElement routerId = info.get(VtnServiceOpenStackConsts.ROUTER);
            if (!(routerId.isJsonNull() || routerId.getAsString().isEmpty())) {
                /* Append "os_vrt_#" */
                msg.append(routerId.getAsString());
            }
        }

        /* Append ",interface:" */
        msg.append(VtnServiceConsts.COMMA);
        msg.append(VtnServiceOpenStackConsts.INTERFACE);
        msg.append(VtnServiceConsts.COLON);

        if (info.has(VtnServiceOpenStackConsts.INTERFACE)) {
            JsonElement ifId = info.get(VtnServiceOpenStackConsts.INTERFACE);
            if (!(ifId.isJsonNull() || ifId.getAsString().isEmpty())) {
                /* Append "2" */
                msg.append(ifId.getAsString());
            }
        }
    } else {
        /* Append "network:" */
        msg.append(VtnServiceOpenStackConsts.NETWORK);
        msg.append(VtnServiceConsts.COLON);

        if (info.has(VtnServiceOpenStackConsts.NETWORK)) {
            JsonElement netId = info.get(VtnServiceOpenStackConsts.NETWORK);
            if (!(netId.isJsonNull() || netId.getAsString().isEmpty())) {
                /* Append "os_vbr_#2" */
                msg.append(netId.getAsString());
            }
        }

        /* Append ",port:" */
        msg.append(VtnServiceConsts.COMMA);
        msg.append(VtnServiceOpenStackConsts.PORT);
        msg.append(VtnServiceConsts.COLON);

        if (info.has(VtnServiceOpenStackConsts.PORT)) {
            JsonElement portId = info.get(VtnServiceOpenStackConsts.PORT);
            if (!(portId.isJsonNull() || portId.getAsString().isEmpty())) {
                /* Append "1" */
                msg.append(portId.getAsString());
            }
        }
    }

    /* Append "}" */
    msg.append(VtnServiceConsts.CLOSE_CURLY_BRACES);

    return msg.toString();
}