Example usage for com.google.gson JsonObject remove

List of usage examples for com.google.gson JsonObject remove

Introduction

In this page you can find the example usage for com.google.gson JsonObject remove.

Prototype

public JsonElement remove(String property) 

Source Link

Document

Removes the property from this JsonObject .

Usage

From source file:org.opendaylight.vtn.javaapi.validation.physical.DomainResourceValidator.java

License:Open Source License

/**
 * Validate get request json for Domain API
 * /*from  w  ww.j  a  v  a2s  .  c  o  m*/
 * @param requestBody
 *            the request Json object
 * @return true, if successful
 * @throws VtnServiceException
 */
private boolean validateGet(final JsonObject requestBody, final boolean opFlag) throws VtnServiceException {
    LOG.trace("Start DomainResourceValidator#validateGet()");
    boolean isValid = true;
    // validation for key: targetdb
    setInvalidParameter(VtnServiceJsonConsts.TARGETDB);
    isValid = validator.isValidRequestDB(requestBody);
    if (!opFlag) {
        if (requestBody.has(VtnServiceJsonConsts.OP)) {
            requestBody.remove(VtnServiceJsonConsts.OP);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.INDEX)) {
            requestBody.remove(VtnServiceJsonConsts.INDEX);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.MAX)) {
            requestBody.remove(VtnServiceJsonConsts.MAX);
        } else {
            LOG.debug("No need to remove");
        }
    } else {
        // validation for key: op
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.OP);
            isValid = validator.isValidOperation(requestBody);
        }
        // validation for key: index
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.INDEX);
            if (requestBody.has(VtnServiceJsonConsts.INDEX)
                    && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString() != null
                    && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString().isEmpty()) {
                isValid = validator.isValidDomainId(
                        requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString(),
                        VtnServiceJsonConsts.LEN_31);
            }
        }
        // validation for key: max_repitition
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.MAX);
            isValid = validator.isValidMaxRepetition(requestBody);
        }
    }
    LOG.trace("Complete DomainResourceValidator#validateGet()");
    return isValid;
}

From source file:org.opendaylight.vtn.javaapi.validation.physical.LinkResourceValidator.java

License:Open Source License

/**
 * Validate get request json for Link API .
 * //from  w w w.  ja v a2s  .co m
 * @param requestBody
 *            , the request Json object .
 * @param opFlag
 *            , to resolve operation type .
 * @return true, if is valid get
 */
public final boolean validateGet(final JsonObject requestBody, final boolean opFlag) {
    LOG.trace("Start LinkResourceValidator#ValidGet");
    boolean isValid = true;
    // validation for key: targetdb
    setInvalidParameter(VtnServiceJsonConsts.TARGETDB);
    if (requestBody.has(VtnServiceJsonConsts.TARGETDB)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString() != null
            && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString().isEmpty()) {
        isValid = VtnServiceJsonConsts.STATE
                .equalsIgnoreCase(requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString());
    } else {
        requestBody.remove(VtnServiceJsonConsts.TARGETDB);
        requestBody.addProperty(VtnServiceJsonConsts.TARGETDB, VtnServiceJsonConsts.STATE);
    }
    if (!opFlag) {
        if (requestBody.has(VtnServiceJsonConsts.OP)) {
            requestBody.remove(VtnServiceJsonConsts.OP);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.INDEX)) {
            requestBody.remove(VtnServiceJsonConsts.INDEX);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.MAX)) {
            requestBody.remove(VtnServiceJsonConsts.MAX);
        } else {
            LOG.debug("No need to remove");
        }
    } else {
        // validation for key: op
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.OP);
            isValid = validator.isValidOperation(requestBody);
        }
        // validation for key: index
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.INDEX);
            if (requestBody.has(VtnServiceJsonConsts.INDEX)
                    && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString() != null) {
                isValid = linkNameValidator(
                        requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString());
            }
        }
        // validation for key: max_repitition
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.MAX);
            isValid = validator.isValidMaxRepetition(requestBody);
            /*
             * if(requestBody.has(VtnServiceJsonConsts.MAX) &&
             * requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.MAX)
             * .getAsString() != null) { isValid =
             * validator.isValidMaxLengthNumber(requestBody
             * .getAsJsonPrimitive(VtnServiceJsonConsts.MAX).getAsString()
             * ); }
             */
        }
    }
    // validation for key: switch_id
    if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.SWITCH1ID);
        if (requestBody.has(VtnServiceJsonConsts.SWITCH1ID)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH1ID).getAsString() != null
                && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH1ID).getAsString().isEmpty()) {
            isValid = validator.isValidMaxLength(
                    requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH1ID).getAsString(),
                    VtnServiceJsonConsts.LEN_255);
        }
    }

    if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.SWITCH2ID);
        if (requestBody.has(VtnServiceJsonConsts.SWITCH2ID)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH2ID).getAsString() != null
                && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH2ID).getAsString().isEmpty()) {
            isValid = validator.isValidMaxLength(
                    requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.SWITCH2ID).getAsString(),
                    VtnServiceJsonConsts.LEN_255);
        }
    }
    // validation for key: Link Name
    if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.LINKNAME);
        if (requestBody.has(VtnServiceJsonConsts.LINKNAME)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.LINKNAME).getAsString() != null) {
            isValid = linkNameValidator(
                    requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.LINKNAME).getAsString());
        }
    }

    LOG.trace("Complete LinkResourceValidator#isValidGet");
    return isValid;
}

From source file:org.opendaylight.vtn.javaapi.validation.physical.SwitchPortResourceValidator.java

License:Open Source License

/**
 * Validate get request json for Port API.
 * //from  ww  w.j  a v a 2  s .  c  om
 * @param opFlag
 *            ,opflag set
 * @param requestBody
 *            the request Json object
 * @return true, if is valid get
 */
public final boolean validateGet(final JsonObject requestBody, final boolean opFlag) {
    LOG.trace("Start SwitchPortResourceValidator#ValidGet");
    boolean isValid = true;
    // validation for key: targetdb
    setInvalidParameter(VtnServiceJsonConsts.TARGETDB);
    if (requestBody.has(VtnServiceJsonConsts.TARGETDB)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString() != null
            && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString().isEmpty()) {
        isValid = VtnServiceJsonConsts.STATE
                .equalsIgnoreCase(requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString());
    } else {
        requestBody.remove(VtnServiceJsonConsts.TARGETDB);
        requestBody.addProperty(VtnServiceJsonConsts.TARGETDB, VtnServiceJsonConsts.STATE);
    }
    if (!opFlag) {
        if (requestBody.has(VtnServiceJsonConsts.OP)) {
            requestBody.remove(VtnServiceJsonConsts.OP);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.INDEX)) {
            requestBody.remove(VtnServiceJsonConsts.INDEX);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.MAX)) {
            requestBody.remove(VtnServiceJsonConsts.MAX);
        } else {
            LOG.debug("No need to remove");
        }
    } else {
        // validation for key: op
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.OP);
            isValid = validator.isValidOperationInfo(requestBody);
        }
        // validation for key: index
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.INDEX);
            if (requestBody.has(VtnServiceJsonConsts.INDEX)
                    && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString() != null
                    && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString().isEmpty()) {
                isValid = validator.isValidMaxLength(
                        requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString(),
                        VtnServiceJsonConsts.LEN_31);
            }
        }
        // validation for key: max_repitition
        if (isValid) {
            setInvalidParameter(VtnServiceJsonConsts.MAX);
            isValid = validator.isValidMaxRepetition(requestBody);
            /*
             * if(requestBody.has(VtnServiceJsonConsts.MAX) &&
             * requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.MAX)
             * .getAsString() != null) { isValid =
             * validator.isValidMaxLengthNumber(requestBody
             * .getAsJsonPrimitive(VtnServiceJsonConsts.MAX).getAsString()
             * ); }
             */
        }
    }
    if (isValid) {
        // validation for key: Port Name(Optional)
        setInvalidParameter(VtnServiceJsonConsts.PORTNAME);
        if (requestBody.has(VtnServiceJsonConsts.PORTNAME)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORTNAME).getAsString() != null
                && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORTNAME).getAsString().isEmpty()) {
            isValid = validator.isValidMaxLength(
                    requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORTNAME).getAsString(),
                    VtnServiceJsonConsts.LEN_31);
        }
    }

    if (isValid) {
        // validation for key: Port Id(Optional)
        setInvalidParameter(VtnServiceJsonConsts.PORT_ID);
        if (requestBody.has(VtnServiceJsonConsts.PORT_ID)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORT_ID).getAsString() != null
                && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORT_ID).getAsString().isEmpty()) {
            isValid = validator.isValidRange(
                    requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PORT_ID).getAsString(),
                    VtnServiceJsonConsts.LONG_VAL_0, VtnServiceJsonConsts.LONG_VAL_4294967295);
        }
    }
    LOG.trace("Complete SwitchPortResourceValidator#isValidGet");
    return isValid;
}

From source file:org.opendaylight.vtn.javaapi.validation.physical.SwitchResourceValidator.java

License:Open Source License

/**
 * Validate get request json for Switch API.
 * /*  ww  w.  j a  va 2s .c o m*/
 * @param requestBody
 *            , the request Json object .
 * @return true, if is valid get .
 * @param opFlag
 *            ,to reolve type of operations .
 */
public final boolean validateGet(final JsonObject requestBody, final boolean opFlag) {
    LOG.trace("Start SwitchResourceValidator#ValidateGet");
    boolean isValid = true;
    // validation for key: targetdb
    setInvalidParameter(VtnServiceJsonConsts.TARGETDB);
    if (requestBody.has(VtnServiceJsonConsts.TARGETDB)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString() != null
            && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString().isEmpty()) {
        isValid = VtnServiceJsonConsts.STATE
                .equalsIgnoreCase(requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.TARGETDB).getAsString());
    } else {
        requestBody.remove(VtnServiceJsonConsts.TARGETDB);
        requestBody.addProperty(VtnServiceJsonConsts.TARGETDB, VtnServiceJsonConsts.STATE);
    }
    if (!opFlag) {
        // validation for key: op
        setInvalidParameter(VtnServiceJsonConsts.OP);
        if (requestBody.has(VtnServiceJsonConsts.OP)
                && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString() != null
                && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString().isEmpty()) {
            final String operation = requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString();
            isValid = operation.equalsIgnoreCase(VtnServiceJsonConsts.DETAIL);
        } else {
            requestBody.remove(VtnServiceJsonConsts.OP);
            requestBody.addProperty(VtnServiceJsonConsts.OP, VtnServiceJsonConsts.NORMAL);
        }

        if (requestBody.has(VtnServiceJsonConsts.INDEX)) {
            requestBody.remove(VtnServiceJsonConsts.INDEX);
        } else {
            LOG.debug("No need to remove");
        }
        if (requestBody.has(VtnServiceJsonConsts.MAX)) {
            requestBody.remove(VtnServiceJsonConsts.MAX);
        } else {
            LOG.debug("No need to remove");
        }
    } else {
        if (isValid) {
            // validation for key: op
            setInvalidParameter(VtnServiceJsonConsts.OP);
            if (requestBody.has(VtnServiceJsonConsts.OP)
                    && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString() != null
                    && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString().isEmpty()) {
                final String operation = requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString();
                isValid = operation.equalsIgnoreCase(VtnServiceJsonConsts.DETAIL)
                        || operation.equalsIgnoreCase(VtnServiceJsonConsts.COUNT);
            } else {
                requestBody.remove(VtnServiceJsonConsts.OP);
                requestBody.addProperty(VtnServiceJsonConsts.OP, VtnServiceJsonConsts.NORMAL);
            }
        }
        if (isValid) {
            // validation for key: index
            setInvalidParameter(VtnServiceJsonConsts.INDEX);
            if (requestBody.has(VtnServiceJsonConsts.INDEX)
                    && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString() != null
                    && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString().isEmpty()) {
                isValid = validator.isValidMaxLength(
                        requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString(),
                        VtnServiceJsonConsts.LEN_255);
            }
        }
        if (isValid) {
            // validation for key: max_repitition
            setInvalidParameter(VtnServiceJsonConsts.MAX);
            isValid = validator.isValidMaxRepetition(requestBody);
            /*
             * if(requestBody.has(VtnServiceJsonConsts.MAX) &&
             * requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.MAX)
             * .getAsString() != null) { isValid =
             * validator.isValidMaxLengthNumber(requestBody
             * .getAsJsonPrimitive(VtnServiceJsonConsts.MAX).getAsString()
             * ); }
             */
        }
    }
    LOG.trace("Complete SwitchResourceValidator#ValidateGet");
    return isValid;
}

From source file:org.opendaylight.vtn.javaapi.validation.UserResourceValidator.java

License:Open Source License

/**
 * Validate put request Json for Set Password API.
 * //w  ww.ja  v a2 s  .c  o m
 * @param requestBody
 *            the request Json object
 * @return true, if successful
 */
private boolean validatePut(final JsonObject requestBody) {
    LOG.trace("Start UserResourceValidator#validatePut()");
    boolean isValid = false;
    // validation for password
    setInvalidParameter(VtnServiceJsonConsts.PASSWORD);
    if (requestBody.has(VtnServiceJsonConsts.PASSWORD)
            && requestBody.get(VtnServiceJsonConsts.PASSWORD) instanceof JsonObject
            && requestBody.get(VtnServiceJsonConsts.PASSWORD).getAsJsonObject()
                    .getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString() != null) {
        final String password = requestBody.get(VtnServiceJsonConsts.PASSWORD).getAsJsonObject()
                .get(VtnServiceJsonConsts.PASSWORD).getAsString();
        requestBody.remove(VtnServiceJsonConsts.PASSWORD);
        requestBody.addProperty(VtnServiceJsonConsts.PASSWORD, password);
    }
    if (requestBody.has(VtnServiceJsonConsts.PASSWORD)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString() != null
            && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString().isEmpty()) {
        isValid = validator.isValidMaxLength(
                requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString(),
                VtnServiceJsonConsts.LEN_72);
    } else {
        isValid = false;
    }
    LOG.trace("Complete UserResourceValidator#validatePut()");
    return isValid;
}

From source file:org.openecomp.sdc.be.servlets.RepresentationUtils.java

License:Open Source License

public static ArtifactDefinition convertJsonToArtifactDefinition(String content,
        Class<ArtifactDefinition> clazz) {

    JsonObject jsonElement = new JsonObject();
    ArtifactDefinition resourceInfo = null;
    try {/*from   w w w.  ja v a  2  s  .  c  o  m*/
        Gson gson = new Gson();
        jsonElement = gson.fromJson(content, jsonElement.getClass());
        JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE_FIELD);
        if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) {
            String groupValueUpper = artifactGroupValue.getAsString().toUpperCase();
            if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) {
                StringBuilder sb = new StringBuilder();
                for (String value : ArtifactGroupTypeEnum.getAllTypes()) {
                    sb.append(value).append(", ");
                }
                log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb.toString());
                return null;
            } else {
                jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD);
                jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, groupValueUpper);
            }
        }
        String payload = null;
        JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
        if (artifactPayload != null && !artifactPayload.isJsonNull()) {
            payload = artifactPayload.getAsString();
        }
        jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
        resourceInfo = gson.fromJson(jsonElement, clazz);
        resourceInfo.setPayloadData(payload);

    } catch (Exception e) {
        BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError,
                "Artifact Upload / Update");
        BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
        log.debug("Failed to convert the content {} to object. {}",
                content.substring(0, Math.min(50, content.length())), e);
    }

    return resourceInfo;
}

From source file:org.openhab.binding.km200.internal.handler.KM200SwitchProgramServiceHandler.java

License:Open Source License

/**
 * This function updates objects JSONData on the actual set switch points.
 *///from  ww w  .  jav  a 2s . c  o  m
public JsonObject getUpdatedJSONData(KM200ServiceObject parObject) {
    synchronized (switchMap) {
        boolean prepareNewOnly = false;
        JsonArray sPoints = new JsonArray();
        for (String day : days) {
            if (switchMap.get(getPositiveSwitch()).containsKey(day)
                    && switchMap.get(getNegativeSwitch()).containsKey(day)) {
                Integer j;
                Integer minDays = Math.min(switchMap.get(getPositiveSwitch()).get(day).size(),
                        switchMap.get(getNegativeSwitch()).get(day).size());
                for (j = 0; j < minDays; j++) {
                    JsonObject tmpObj = new JsonObject();
                    tmpObj.addProperty("dayOfWeek", day);
                    tmpObj.addProperty("setpoint", getPositiveSwitch());
                    tmpObj.addProperty("time", switchMap.get(getPositiveSwitch()).get(day).get(j));
                    sPoints.add(tmpObj);
                    tmpObj = new JsonObject();
                    tmpObj.addProperty("dayOfWeek", day);
                    tmpObj.addProperty("setpoint", getNegativeSwitch());
                    tmpObj.addProperty("time", switchMap.get(getNegativeSwitch()).get(day).get(j));
                    sPoints.add(tmpObj);
                }

                /* Check whether one object for a new cycle is already created */
                if (switchMap.get(getPositiveSwitch()).get(day).size() > minDays) {
                    JsonObject tmpObj = new JsonObject();
                    tmpObj.addProperty("dayOfWeek", day);
                    tmpObj.addProperty("setpoint", getPositiveSwitch());
                    tmpObj.addProperty("time", switchMap.get(getPositiveSwitch()).get(day).get(j));
                    sPoints.add(tmpObj);
                    prepareNewOnly = true;
                } else if (switchMap.get(getNegativeSwitch()).get(day).size() > minDays) {
                    JsonObject tmpObj = new JsonObject();
                    tmpObj.addProperty("dayOfWeek", day);
                    tmpObj.addProperty("setpoint", getNegativeSwitch());
                    tmpObj.addProperty("time", switchMap.get(getNegativeSwitch()).get(day).get(j));
                    sPoints.add(tmpObj);
                    prepareNewOnly = true;
                }
            }
        }
        logger.debug("New switching points: {}", sPoints);
        JsonObject switchRoot = parObject.getJSONData();
        switchRoot.remove("switchPoints");
        switchRoot.add("switchPoints", sPoints);
        parObject.setJSONData(switchRoot);
        /* Preparation for are new cycle, don't sent it to the device */
        if (prepareNewOnly) {
            return null;
        } else {
            return switchRoot;
        }
    }
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoDeviceSerializer.java

License:Open Source License

@Override
public JsonElement serialize(NeeoDevice device, @Nullable Type deviceType,
        @Nullable JsonSerializationContext jsonContext) {
    Objects.requireNonNull(device, "device cannot be null");
    Objects.requireNonNull(deviceType, "deviceType cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    final JsonObject jsonObject = new JsonObject();

    final NeeoThingUID uid = device.getUid();
    jsonObject.add("uid", jsonContext.serialize(uid));
    jsonObject.add("type", jsonContext.serialize(device.getType()));
    jsonObject.addProperty("manufacturer", device.getManufacturer());
    jsonObject.addProperty("name", device.getName());
    jsonObject.addProperty("specificName", device.getSpecificName());
    jsonObject.addProperty("iconName", device.getIconName());
    jsonObject.addProperty("driverVersion", device.getDriverVersion());

    final JsonArray channels = (JsonArray) jsonContext.serialize(device.getChannels());

    final NeeoDeviceTiming timing = device.getDeviceTiming();
    jsonObject.add("timing", jsonContext.serialize(timing == null ? new NeeoDeviceTiming() : timing));

    jsonObject.add("deviceCapabilities", jsonContext.serialize(device.getDeviceCapabilities()));

    jsonObject.addProperty("thingType", uid.getThingType());

    if (StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
        jsonObject.addProperty("thingStatus", uid.getThingType().toUpperCase());
    }//from   w w w . ja v a2  s .  com

    final ServiceContext localContext = context;
    if (localContext != null) {
        if (!StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
            final Thing thing = localContext.getThingRegistry().get(device.getUid().asThingUID());
            jsonObject.addProperty("thingStatus",
                    thing == null ? ThingStatus.UNKNOWN.name() : thing.getStatus().name());

            if (thing != null) {
                final ThingType thingType = localContext.getThingTypeRegistry()
                        .getThingType(thing.getThingTypeUID());

                if (thingType != null) {
                    for (JsonElement chnl : channels) {
                        JsonObject jo = (JsonObject) chnl;
                        if (jo.has("groupId") && jo.has("itemLabel")) {
                            final String groupId = jo.get("groupId").getAsString();
                            final String groupLabel = NeeoUtil.getGroupLabel(thingType, groupId);
                            if (StringUtils.isNotEmpty(groupLabel)) {
                                final JsonElement itemLabel = jo.remove("itemLabel");
                                jo.addProperty("itemLabel", groupLabel + "#" + itemLabel.getAsString());
                            } else if (StringUtils.isNotEmpty("groupId")) {
                                // have a groupid but no group definition found (usually error on binding)
                                // just default to "Others" like the Paperui does.
                                final JsonElement itemLabel = jo.remove("itemLabel");
                                jo.addProperty("itemLabel", "Others#" + itemLabel.getAsString());
                            }
                        }
                    }
                }
            }
        }
    }

    jsonObject.add("channels", channels);

    final NeeoService localService = service;
    if (localService != null) {
        List<String> foundKeys = new ArrayList<>();
        for (final NeeoBrainServlet servlet : localService.getServlets()) {
            final NeeoDeviceKeys servletKeys = servlet.getDeviceKeys();
            final Set<String> keys = servletKeys.get(device.getUid());
            foundKeys.addAll(keys);
        }
        jsonObject.add("keys", jsonContext.serialize(foundKeys));
    }

    return jsonObject;
}

From source file:org.openhab.io.neeo.internal.servletservices.NeeoBrainSearchService.java

License:Open Source License

/**
 * Does the search of all things and returns the results
 *
 * @param queryString the non-null, possibly empty query string
 * @param resp        the non-null response to write to
 * @throws IOException Signals that an I/O exception has occurred.
 *///from  ww w .j  a  v  a2 s  . c  om
private void doSearch(String queryString, HttpServletResponse resp) throws IOException {
    Objects.requireNonNull(queryString, "queryString cannot be null");
    Objects.requireNonNull(resp, "resp cannot be null");

    final int idx = StringUtils.indexOf(queryString, '=');

    if (idx >= 0 && idx + 1 < queryString.length()) {
        final String search = NeeoUtil.decodeURIComponent(queryString.substring(idx + 1));

        final List<JsonObject> ja = new ArrayList<>();
        search(search).stream().sorted(Comparator.comparing(TokenScoreResult<NeeoDevice>::getScore).reversed())
                .forEach(item -> {
                    final JsonObject jo = (JsonObject) gson.toJsonTree(item);

                    // transfer id from tokenscoreresult to neeodevice (as per NEEO API)
                    final int id = jo.getAsJsonPrimitive("id").getAsInt();
                    jo.remove("id");
                    jo.getAsJsonObject("item").addProperty("id", id);
                    ja.add(jo);
                });

        final String itemStr = gson.toJson(ja);
        logger.debug("Search '{}', response: {}", search, itemStr);
        NeeoUtil.write(resp, itemStr);
    }
}

From source file:org.openqa.grid.web.servlet.HubStatusServlet.java

License:Apache License

private JsonObject getResponse(HttpServletRequest request) throws IOException {
    JsonObject res = new JsonObject();
    res.addProperty("success", true);
    try {/* w  w  w.j  a  v a 2 s .  c o m*/
        if (request.getInputStream() != null) {
            JsonObject requestJSON = getRequestJSON(request);
            List<String> keysToReturn = null;

            if (request.getParameter("configuration") != null
                    && !"".equals(request.getParameter("configuration"))) {
                keysToReturn = Arrays.asList(request.getParameter("configuration").split(","));
            } else if (requestJSON != null && requestJSON.has("configuration")) {
                keysToReturn = new Gson().fromJson(requestJSON.getAsJsonArray("configuration"),
                        ArrayList.class);
            }

            Registry registry = getRegistry();
            JsonElement config = registry.getConfiguration().toJson();
            for (Map.Entry<String, JsonElement> entry : config.getAsJsonObject().entrySet()) {
                if (keysToReturn == null || keysToReturn.isEmpty() || keysToReturn.contains(entry.getKey())) {
                    res.add(entry.getKey(), entry.getValue());
                }
            }
            if (keysToReturn == null || keysToReturn.isEmpty()
                    || keysToReturn.contains("newSessionRequestCount")) {
                res.addProperty("newSessionRequestCount", registry.getNewSessionRequestCount());
            }

            if (keysToReturn == null || keysToReturn.isEmpty() || keysToReturn.contains("slotCounts")) {
                res.add("slotCounts", getSlotCounts());
            }
        }
    } catch (Exception e) {
        res.remove("success");
        res.addProperty("success", false);
        res.addProperty("msg", e.getMessage());
    }
    return res;

}