Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.blackducksoftware.integration.hub.api.report.ReportRestService.java

License:Apache License

/**
 * Gets the content of the report/*from w  w w . j a  v  a 2  s . c om*/
 *
 */
public VersionReport getReportContent(final String reportContentUrl)
        throws IOException, BDRestException, URISyntaxException {
    final HubRequest hubRequest = new HubRequest(getRestConnection());
    hubRequest.setMethod(Method.GET);
    hubRequest.setLimit(HubRequest.EXCLUDE_INTEGER_QUERY_PARAMETER);
    hubRequest.setUrl(reportContentUrl);

    final JsonObject json = hubRequest.executeForResponseJson();
    final JsonElement content = json.get("reportContent");
    final JsonArray reportConentArray = content.getAsJsonArray();
    final JsonObject reportFile = reportConentArray.get(0).getAsJsonObject();

    final VersionReport report = getRestConnection().getGson().fromJson(reportFile.get("fileContent"),
            VersionReport.class);

    return report;

}

From source file:com.blackducksoftware.integration.hub.HubIntRestService.java

License:Apache License

/**
 * Gets the content of the report/*from   w w  w .  j ava 2 s .c o m*/
 *
 */
public VersionReport getReportContent(final String reportContentUrl)
        throws IOException, BDRestException, URISyntaxException {
    final ClientResource resource = hubServicesFactory.getRestConnection()
            .createClientResource(reportContentUrl);
    try {
        resource.setMethod(Method.GET);

        hubServicesFactory.getRestConnection().handleRequest(resource);
        final int responseCode = resource.getResponse().getStatus().getCode();

        if (hubServicesFactory.getRestConnection().isSuccess(responseCode)) {
            final String response = hubServicesFactory.getRestConnection()
                    .readResponseAsString(resource.getResponse());

            final JsonObject json = hubServicesFactory.getRestConnection().getJsonParser().parse(response)
                    .getAsJsonObject();
            final JsonElement content = json.get("reportContent");
            final JsonArray reportConentArray = content.getAsJsonArray();
            final JsonObject reportFile = reportConentArray.get(0).getAsJsonObject();

            final VersionReport report = hubServicesFactory.getRestConnection().getGson()
                    .fromJson(reportFile.get("fileContent"), VersionReport.class);

            return report;
        } else if (responseCode == 412) {
            final String response = hubServicesFactory.getRestConnection()
                    .readResponseAsString(resource.getResponse());
            final JsonObject json = hubServicesFactory.getRestConnection().getJsonParser().parse(response)
                    .getAsJsonObject();
            final String errorMessage = json.get("errorMessage").getAsString();
            throw new BDRestException(errorMessage + " Error Code: " + responseCode, resource);
        } else {
            throw new BDRestException(
                    "There was a problem getting the content of this Report. Error Code: " + responseCode,
                    resource);
        }
    } finally {
        releaseResource(resource);
    }
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Detects the type of the given json element and deserializes its contents into the appropriate
 * component types.//from w  w w  .  j  a va  2s .co m
 *
 * @param json The json element to be deserialized
 *
 * @return The deserialized chat component
 */
private ChatComponent deserializeComponent(JsonElement json) {
    if (json.isJsonPrimitive()) {
        // Only text components can be raw primitives (strings):
        return this.deserializeTextComponent(json);
    } else if (json.isJsonArray()) {
        // Only text components can be json arrays:
        return this.deserializeComponentArray(json.getAsJsonArray());
    } else {
        return this.deserializeTextComponent(json);
    }
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Creates a text component given its JSON representation. Both the shorthand notation as
 * a raw string as well as the notation as a full-blown JSON object are supported.
 *
 * @param json The JSON element to be deserialized into a text component
 *
 * @return The deserialized TextComponent
 *//*from  w ww.j  av  a  2  s. co m*/
private TextComponent deserializeTextComponent(JsonElement json) {
    final TextComponent component = new TextComponent("");

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            component.setText(primitive.getAsString());
        }
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();

        if (object.has("text")) {
            JsonElement textElement = object.get("text");
            if (textElement.isJsonPrimitive()) {
                JsonPrimitive textPrimitive = textElement.getAsJsonPrimitive();
                if (textPrimitive.isString()) {
                    component.setText(textPrimitive.getAsString());
                }
            }
        }

        if (object.has("extra")) {
            JsonElement extraElement = object.get("extra");
            if (extraElement.isJsonArray()) {
                JsonArray extraArray = extraElement.getAsJsonArray();
                for (int i = 0; i < extraArray.size(); ++i) {
                    JsonElement fieldElement = extraArray.get(i);
                    component.addChild(this.deserializeComponent(fieldElement));
                }
            }
        }
    }

    return component;
}

From source file:com.buddycloud.channeldirectory.cli.Main.java

License:Apache License

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {

    JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE));
    JsonArray rootArray = rootElement.getAsJsonArray();

    Map<String, Query> queries = new HashMap<String, Query>();

    for (int i = 0; i < rootArray.size(); i++) {
        JsonObject queryElement = rootArray.get(i).getAsJsonObject();
        String queryName = queryElement.get("name").getAsString();
        String type = queryElement.get("type").getAsString();

        Query query = null;/* w w w  . j a  v  a  2  s  .  co m*/

        if (type.equals("solr")) {
            query = new QueryToSolr(queryElement.get("agg").getAsString(),
                    queryElement.get("core").getAsString(), queryElement.get("q").getAsString());
        } else if (type.equals("dbms")) {
            query = new QueryToDBMS(queryElement.get("q").getAsString());
        }

        queries.put(queryName, query);
    }

    LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet());
    Collections.sort(queriesNames);

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true)
            .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q'));

    options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true)
            .withDescription("Arguments for the query").create('a'));

    options.addOption(new Option("?", "help", false, "Print this message"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("help")) {
        printHelpAndExit(options);
    }

    String queryName = cmd.getOptionValue("q");
    String argsCmd = cmd.getOptionValue("a");

    Properties configuration = ConfigurationUtils.loadConfiguration();

    Query query = queries.get(queryName);
    if (query == null) {
        printHelpAndExit(options);
    }

    System.out.println(query.exec(argsCmd, configuration));

}

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }/*from  ww  w. j  av a  2 s.  c  o  m*/
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            Number num = prim.getAsNumber();
            // here you can handle double int/long values
            // and return any type you want
            // this solution will transform 3.0 float to long values
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.ca.dvs.utilities.raml.RamlUtil.java

License:Open Source License

/**
 * @param jsonString//from   w ww  .  j a v a2s . co m
 * @return the appropriate JsonElement object from the parsed jsonString
 */
private static Object getJsonElementValue(String jsonString) {

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(jsonString);

    if (jsonElement.isJsonObject()) {

        return jsonElement.getAsJsonObject();

    } else if (jsonElement.isJsonArray()) {

        return jsonElement.getAsJsonArray();

    } else if (jsonElement.isJsonNull()) {

        return jsonElement.getAsJsonNull();

    } else if (jsonElement.isJsonPrimitive()) {

        return jsonElement.getAsJsonPrimitive();

    } else {

        return null;

    }
}

From source file:com.canoo.cog.sonar.SonarResultParser.java

License:Apache License

List<SonarProject> parseProjects(String projectResultString) {
    List<SonarProject> sonarProjects = new ArrayList<>();

    JsonElement projects = jsonParser.parse(projectResultString);
    JsonArray projectArray = projects.getAsJsonArray();
    for (JsonElement projectJson : projectArray) {
        String key = projectJson.getAsJsonObject().get("key").getAsString();
        String name = projectJson.getAsJsonObject().get("name").getAsString();
        String version = projectJson.getAsJsonObject().get("version").getAsString();
        sonarProjects.add(new SonarProjectImpl(key, name, version));
    }// w ww . j a va 2  s.  c  o  m
    return sonarProjects;
}

From source file:com.canoo.cog.sonar.SonarResultParser.java

License:Apache License

CityModelImpl parseCity(String cityResultString) {

    JsonElement cityJson = jsonParser.parse(cityResultString);
    JsonArray allComponents = cityJson.getAsJsonArray();

    // Create city
    JsonObject cityObject = allComponents.get(0).getAsJsonObject();
    JsonToModelConverter jsonToModelConverter = new JsonToModelConverter();
    CityModelImpl city = jsonToModelConverter.convertToCity(cityObject);

    // Sort by name
    List<JsonObjectWrapper> javaElements = new ArrayList<>();
    for (JsonElement component : allComponents) {
        javaElements.add(new JsonObjectWrapper(component.getAsJsonObject()));
    }/*from w  w  w. j a  va2 s  .c o  m*/
    Collections.sort(javaElements);

    // Add neighborhoods
    for (JsonObjectWrapper component : javaElements) {
        JsonObject compObject = component.getObject();
        String scopeString = compObject.get("scope").getAsString();
        if (scopeString.equals("DIR")) {
            HoodModelImpl newHood = jsonToModelConverter.convertToHood(compObject);
            city.addHoodToCity(newHood);
        }
    }

    // Add buildings
    for (JsonObjectWrapper component : javaElements) {
        JsonObject compObject = component.getObject();
        String scopeString = compObject.get("scope").getAsString();
        String qualifierString = compObject.get("qualifier").getAsString();
        if (scopeString.equals("FIL") && !qualifierString.equals("UTS")) {
            BuildingModelImpl buildingModel = jsonToModelConverter.convertToBuilding(compObject);
            city.addBuildingToCity(buildingModel);
        }
    }

    // drop empty hoods
    city.removeEmptyHoods();

    return city;
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.ListParser.java

License:Apache License

@Override
public List<T> apply(JsonElement json) {
    if ((json == null) || (json.isJsonNull())) {
        return Collections.emptyList();
    } else {/*  ww  w  . j a  v  a  2  s .co m*/
        return StreamSupport.stream(json.getAsJsonArray().spliterator(), false).map(parseFunction)
                .collect(Collectors.toList());
    }
}