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.eclipse.dirigible.ide.template.ui.js.service.ScriptingGenerationWorker.java

License:Open Source License

protected void setParametersToModel(JsonObject parametersObject, JavascriptServiceTemplateModel model,
        TemplateType[] templates) throws GenerationException {

    // template type
    if (parametersObject.has(PARAM_TEMPLATE_TYPE)) {
        String templateType = parametersObject.get(PARAM_TEMPLATE_TYPE).getAsString();
        for (TemplateType template : templates) {
            if (template.getLocation()
                    .substring(ScriptingServiceTemplateTypeDiscriminator.getTemplatesPath().length())
                    .indexOf(templateType + ICommonConstants.SEPARATOR) == 0) {
                model.setTemplate(template);
                break;
            }//from   w w  w  .j av a  2s .c o  m
        }
        if (model.getTemplate() == null) {
            throw new GenerationException(
                    String.format(TEMPLATE_S_DOES_NOT_EXIST_IN_THIS_INSTANCE, templateType));
        }
    } else {
        throw new GenerationException(
                String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_TEMPLATE_TYPE));
    }

    // file name
    if (parametersObject.has(PARAM_FILE_NAME)) {
        model.setFileName(parametersObject.get(PARAM_FILE_NAME).getAsString());
    } else {
        throw new GenerationException(
                String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_FILE_NAME));
    }

    // project name
    if (parametersObject.has(PARAM_PROJECT_NAME)) {
        String projectName = parametersObject.get(PARAM_PROJECT_NAME).getAsString();
        IProject project = getWorkspace().getRoot().getProject(projectName);
        if (!project.exists()) {
            try {
                project.create(new LogProgressMonitor());
            } catch (CoreException e) {
                throw new GenerationException(e);
            }
        }
        model.setTargetContainer(project.getFullPath().toString());
    } else {
        throw new GenerationException(
                String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_PROJECT_NAME));
    }

    // package name
    if (parametersObject.has(PARAM_PACKAGE_NAME)) {
        String packageName = parametersObject.get(PARAM_PACKAGE_NAME).getAsString();
        model.setProjectPackageName(
                ICommonConstants.ARTIFACT_TYPE.SCRIPTING_SERVICES + IRepository.SEPARATOR + packageName);
        model.setPackageName(packageName);
    } else {
        throw new GenerationException(
                String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_PACKAGE_NAME));
    }

    // columns
    if (parametersObject.has(PARAM_COLUMNS)) {
        List<TableColumn> columnDefinitions = new ArrayList<TableColumn>();
        JsonArray columns = parametersObject.get(PARAM_COLUMNS).getAsJsonArray();
        Iterator<JsonElement> iter = columns.iterator();
        while (iter.hasNext()) {
            JsonElement columnElement = iter.next();
            if (columnElement.isJsonObject()) {
                JsonObject columnObject = columnElement.getAsJsonObject();
                if (columnObject.get(PARAM_COLUMN_NAME) == null) {
                    throw new GenerationException(
                            String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_COLUMN_NAME));
                }
                if (columnObject.get(PARAM_COLUMN_TYPE) == null) {
                    throw new GenerationException(
                            String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_COLUMN_TYPE));
                }
                if (columnObject.get(PARAM_COLUMN_PRIMARY_KEY) == null) {
                    throw new GenerationException(String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED,
                            PARAM_COLUMN_PRIMARY_KEY));
                }
                if (columnObject.get(PARAM_COLUMN_VISIBLE) == null) {
                    throw new GenerationException(
                            String.format(MANDATORY_PARAMETER_S_HAS_NOT_BEEN_PROVIDED, PARAM_COLUMN_VISIBLE));
                }
                TableColumn columnDefinition = new TableColumn(
                        columnObject.get(PARAM_COLUMN_NAME).getAsString(),
                        DBSupportedTypesMap.getTypeNumber(columnObject.get(PARAM_COLUMN_TYPE).getAsString()),
                        columnObject.get(PARAM_COLUMN_PRIMARY_KEY).getAsBoolean(),
                        columnObject.get(PARAM_COLUMN_VISIBLE).getAsBoolean());
                columnDefinitions.add(columnDefinition);
            }
        }

        model.setTableColumns(columnDefinitions.toArray(new TableColumn[] {}));
    } else {
        checkIfRequired(model, PARAM_COLUMNS);
    }

    // table name
    if (parametersObject.has(PARAM_TABLE_NAME)) {
        model.setTableName(parametersObject.get(PARAM_TABLE_NAME).getAsString());
    } else {
        checkIfRequired(model, PARAM_TABLE_NAME);
    }

    // table type
    if (parametersObject.has(PARAM_TABLE_TYPE)) {
        model.setTableType(parametersObject.get(PARAM_TABLE_TYPE).getAsString());
    } else {
        checkIfRequired(model, PARAM_TABLE_TYPE);
    }

}

From source file:org.eclipse.dirigible.runtime.command.CommandDataParser.java

License:Open Source License

/**
        //from w  w  w .  j a  v a2s .c  o  m
{
    "description":"test command printing the os name and version",
    "contentType":"plain/text",
    "useContent":"false",
    "workDir":".",
    "commands": 
   [
       {
           "osName": "Linux",
           "command":"bash -c \"cat /proc/version\""
       }
       ,
       {
           "osName": "Windows",
           "command":"cmd /c \"systeminfo\""
       }
   ],
    "envAdd":
   [
       {
          "name":"java.env1",
           "value":"toBeAdded"
       }
   ],
    "envRemove":
   [
       {
           "name":"java.env2"
       }
   ]
}
        
 */

public static CommandData parseCommandData(String commandSource) throws IllegalArgumentException {
    JsonParser parser = new JsonParser();
    JsonObject commandObject = (JsonObject) parser.parse(commandSource);
    CommandData commandData = new CommandData();
    commandData.setDescription(commandObject.get("description").getAsString());
    commandData.setContentType(commandObject.get("contentType").getAsString());
    commandData.setUseContent(commandObject.get("useContent").getAsBoolean());
    commandData.setWorkDir(commandObject.get("workDir").getAsString());
    JsonArray commandsData = commandObject.get("commands").getAsJsonArray();
    Iterator<JsonElement> iter = commandsData.iterator();
    while (iter.hasNext()) {
        CommandLineData commandLineData = new CommandLineData();
        JsonObject object = (JsonObject) iter.next();
        commandLineData.setOsName(object.get("osName").getAsString());
        commandLineData.setCommand(object.get("command").getAsString());
        commandData.getCommands().add(commandLineData);
    }

    JsonArray envAddData = commandObject.get("envAdd").getAsJsonArray();
    iter = envAddData.iterator();
    while (iter.hasNext()) {
        JsonObject object = (JsonObject) iter.next();
        commandData.getEnvAdd().put(object.get("name").getAsString(), object.get("value").getAsString());
    }

    JsonArray envRemoveData = commandObject.get("envRemove").getAsJsonArray();
    iter = envRemoveData.iterator();
    while (iter.hasNext()) {
        JsonObject object = (JsonObject) iter.next();
        commandData.getEnvRemove().add(object.get("name").getAsString());
    }

    validateCommandData(commandData);

    return commandData;
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapter.java

License:Open Source License

/**
 * Convert the JsonElement into the parameters object corresponding to the call made
 * by method. If the result is already converted, does nothing.
 *
 * @param params//from  ww w  . ja  v  a 2 s.  c o  m
 *            json element to read from
 * @param method
 *            method name of request
 * @return correctly typed object if the correct expected type can be
 *         determined, or params unmodified if no conversion can be done.
 */
protected Object parseParams(Object params, String method) {
    if (isNull(params)) {
        return null;
    }
    if (!(params instanceof JsonElement)) {
        return params;
    }
    JsonElement rawParams = (JsonElement) params;
    Type[] parameterTypes = getParameterTypes(method);
    if (parameterTypes.length == 1) {
        return fromJson(rawParams, parameterTypes[0]);
    }
    if (parameterTypes.length > 1 && rawParams instanceof JsonArray) {
        JsonArray array = (JsonArray) rawParams;
        List<Object> parameters = new ArrayList<Object>(Math.max(array.size(), parameterTypes.length));
        int index = 0;
        Iterator<JsonElement> iterator = array.iterator();
        while (iterator.hasNext()) {
            Type parameterType = index < parameterTypes.length ? parameterTypes[index] : null;
            Object parameter = fromJson(iterator.next(), parameterType);
            parameters.add(parameter);
            index++;
        }
        while (index < parameterTypes.length) {
            parameters.add(null);
            index++;
        }
        return parameters;
    }
    return rawParams;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.JSonSupport.java

License:Open Source License

public JSonSupport() {
    TypeToken<Map<Id, PatchSetApproval>> approvalMapType = new TypeToken<Map<ApprovalCategory.Id, PatchSetApproval>>() {
    };/*from   ww  w.  java 2s  . c om*/
    ExclusionStrategy exclustionStrategy = new ExclusionStrategy() {

        public boolean shouldSkipField(FieldAttributes f) {
            // commentLinks requires instantiation of com.google.gwtexpui.safehtml.client.RegexFindReplace which is not on classpath
            if (f.getDeclaredClass() == List.class && f.getName().equals("commentLinks") //$NON-NLS-1$
                    && f.getDeclaringClass() == GerritConfig.class) {
                return true;
            }
            if (f.getDeclaredClass() == Map.class && f.getName().equals("given")) { //$NON-NLS-1$
                //return true;
            }
            // GSon 2.1 fails to deserialize the SubmitType enum
            if (f.getDeclaringClass() == Project.class && f.getName().equals("submitType")) { //$NON-NLS-1$
                return true;
            }
            return false;
        }

        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
    gson = JsonServlet.defaultGsonBuilder()
            .registerTypeAdapter(JSonResponse.class, new JSonResponseDeserializer())
            .registerTypeAdapter(Edit.class, new JsonDeserializer<Edit>() {
                public Edit deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    if (json.isJsonArray()) {
                        JsonArray array = json.getAsJsonArray();
                        if (array.size() == 4) {
                            return new Edit(array.get(0).getAsInt(), array.get(1).getAsInt(),
                                    array.get(2).getAsInt(), array.get(3).getAsInt());
                        }
                    }
                    return new Edit(0, 0);
                }
            })
            // ignore GerritForge specific AuthType "TEAMFORGE" which is unknown to Gerrit
            .registerTypeAdapter(AuthType.class, new JsonDeserializer<AuthType>() {

                @Override
                public AuthType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    String jsonString = json.getAsString();
                    if (jsonString != null) {
                        try {
                            return AuthType.valueOf(jsonString);
                        } catch (IllegalArgumentException e) {
                            // ignore the error since the connector does not make use of AuthType
                            //GerritCorePlugin.logWarning("Ignoring unkown authentication type: " + jsonString, e);
                        }
                    }
                    return null;
                }
            })
            .registerTypeAdapter(approvalMapType.getType(), new JsonDeserializer<Map<Id, PatchSetApproval>>() {

                @Override
                public Map<Id, PatchSetApproval> deserialize(JsonElement json, Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
                    // Gerrit 2.2: the type of PatchSetPublishDetail.given changed from a map to a list
                    Map<Id, PatchSetApproval> map = new HashMap<ApprovalCategory.Id, PatchSetApproval>();
                    if (json.isJsonArray()) {
                        JsonArray array = json.getAsJsonArray();
                        for (Iterator<JsonElement> it = array.iterator(); it.hasNext();) {
                            JsonElement element = it.next();
                            Id key = context.deserialize(element, Id.class);
                            if (key.get() != null) {
                                // Gerrit < 2.1.x: json is map
                                element = it.next();
                            }
                            PatchSetApproval value = context.deserialize(element, PatchSetApproval.class);
                            if (key.get() == null) {
                                // Gerrit 2.2: json is a list, deduct key from value
                                key = value.getCategoryId();
                            }
                            map.put(key, value);
                        }
                    }
                    return map;
                }
            }).setExclusionStrategies(exclustionStrategy).create();
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.climate.jsonResponseContainer.impl.AssignedSensors.java

License:Open Source License

private void init(JsonObject jObject) {
    if (jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()) != null
            && jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()).isJsonArray()) {
        JsonArray jArray = jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()).getAsJsonArray();
        if (jArray.size() != 0) {
            sensors = new LinkedList<AssignSensorType>();
            Iterator<JsonElement> iter = jArray.iterator();
            while (iter.hasNext()) {
                JsonObject assignedSensor = iter.next().getAsJsonObject();
                Short sensorType = null;
                String meterDSUID = null;
                if (assignedSensor.get(JSONApiResponseKeysEnum.SENSOR_TYPE.getKey()) != null) {
                    sensorType = assignedSensor.get(JSONApiResponseKeysEnum.SENSOR_TYPE.getKey()).getAsShort();
                }// w ww.  j  a v  a  2s .  co  m
                if (assignedSensor.get(JSONApiResponseKeysEnum.DSUID_LOWER_CASE.getKey()) != null) {
                    meterDSUID = assignedSensor.get(JSONApiResponseKeysEnum.DSUID_LOWER_CASE.getKey())
                            .getAsString();
                }
                sensors.add(new AssignSensorType(SensorEnum.getSensor(sensorType), meterDSUID));
            }
        }
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.climate.jsonResponseContainer.impl.SensorValues.java

License:Open Source License

private void init(JsonObject jObject) {
    if (jObject.get(JSONApiResponseKeysEnum.VALUES.getKey()).isJsonArray()) {
        JsonArray jArray = jObject.get(JSONApiResponseKeysEnum.VALUES.getKey()).getAsJsonArray();
        if (jArray.size() != 0) {
            Iterator<JsonElement> iter = jArray.iterator();
            while (iter.hasNext()) {
                JsonObject cachedSensorValue = iter.next().getAsJsonObject();
                super.addSensorValue(cachedSensorValue, false);
            }/*from  w w w.  j ava2 s  .c o m*/
        }
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.DsAPIImpl.java

License:Open Source License

@Override
public List<TemperatureControlStatus> getApartmentTemperatureControlStatus(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_TEMPERATURE_CONTROL_STATUS)
            .addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            if (jArray.size() != 0) {
                List<TemperatureControlStatus> list = new ArrayList<TemperatureControlStatus>(jArray.size());
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    TemperatureControlStatus tContStat = new TemperatureControlStatus(
                            iter.next().getAsJsonObject());
                    list.add(tContStat);
                }//ww w  .j a  v  a  2  s  .c o m
                return list;
            }
        }
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.DsAPIImpl.java

License:Open Source License

@Override
public HashMap<Integer, TemperatureControlConfig> getApartmentTemperatureControlConfig(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_TEMPERATURE_CONTROL_CONFIG)
            .addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            if (jArray.size() != 0) {
                HashMap<Integer, TemperatureControlConfig> map = new HashMap<Integer, TemperatureControlConfig>(
                        jArray.size());/*w w w .  j  ava  2  s. co m*/
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    TemperatureControlConfig tContConf = new TemperatureControlConfig(
                            iter.next().getAsJsonObject());
                    map.put(tContConf.getZoneID(), tContConf);
                }
                return map;
            }
        }
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.DsAPIImpl.java

License:Open Source License

@Override
public HashMap<Integer, TemperatureControlValues> getApartmentTemperatureControlValues(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_TEMPERATURE_CONTROL_VALUES)
            .addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            if (jArray.size() != 0) {
                HashMap<Integer, TemperatureControlValues> map = new HashMap<Integer, TemperatureControlValues>(
                        jArray.size());//w  ww.  j a  va  2 s  . c o  m
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    TemperatureControlValues tContVal = new TemperatureControlValues(
                            iter.next().getAsJsonObject());
                    map.put(tContVal.getZoneID(), tContVal);
                }
                return map;
            }
        }
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.DsAPIImpl.java

License:Open Source License

@Override
public HashMap<Integer, AssignedSensors> getApartmentAssignedSensors(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_ASSIGNED_SENSORS).addParameter(ParameterKeys.TOKEN, sessionToken)
            .buildRequestString());/*from www .  jav  a2  s. co  m*/
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            if (jArray.size() != 0) {
                HashMap<Integer, AssignedSensors> map = new HashMap<Integer, AssignedSensors>(jArray.size());
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    AssignedSensors assignedSensors = new AssignedSensors(iter.next().getAsJsonObject());
                    map.put(assignedSensors.getZoneID(), assignedSensors);
                }
                return map;
            }
        }
    }
    return null;
}