Example usage for com.google.gson JsonArray size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveActionMessageFactoryImpl.java

License:Open Source License

protected void handleActions(final JsonArray jsonArray, final ReceiveMessage result) {
    if (jsonArray.size() > 0) {
        final JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
        handleAction(jsonObject, result);
    }/* w ww  .j  a v  a 2s.c o  m*/
}

From source file:allout58.mods.techtree.tree.TechNodeGSON.java

License:Open Source License

@Override
public TechNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject obj = json.getAsJsonObject();
    final int id = obj.get("id").getAsInt();
    final String name = obj.get("name").getAsString();
    final int science = obj.get("scienceRequired").getAsInt();
    final String description = obj.get("description").getAsString();
    final ItemStack[] items = context.deserialize(obj.get("lockedItems"), ItemStack[].class);

    final TechNode node = new TechNode(id);
    //        ItemStack[] items = new ItemStack[] { new ItemStack(Items.apple), new ItemStack(Items.arrow), new ItemStack(Items.bow) };
    node.setup(name, science, description, items);

    final JsonArray jsonParentArray = obj.getAsJsonArray("parents");
    for (int i = 0; i < jsonParentArray.size(); i++) {
        node.addParentNode(jsonParentArray.get(i).getAsInt());
    }//from w ww.  j  av  a2  s .c o m

    return node;
}

From source file:ambari.interaction.NodeController.java

public static ArrayList<ComponentInformation> getListOfNodes() throws Exception {
    String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state";
    String responseJson = HttpURLConnectionExample.sendGet(url);
    System.out.print(responseJson);
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonTree = jsonParser.parse(responseJson);
    ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>();

    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonElement hostComponents = jsonObject.get("host_components");

        if (hostComponents.isJsonArray()) {
            JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray();
            System.out.println("\nStart");
            System.out.println(hostComponentsJsonArray);

            for (int i = 0; i < hostComponentsJsonArray.size(); i++) {
                JsonElement hostComponentsElem = hostComponentsJsonArray.get(i);

                if (hostComponentsElem.isJsonObject()) {
                    JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject();
                    JsonElement hostRolesElem = jsonObjectElem.get("HostRoles");

                    if (hostRolesElem.isJsonObject()) {
                        JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject();
                        JsonElement componentNameElem = hostRolesObjs.get("component_name");
                        JsonElement hostNameElem = hostRolesObjs.get("host_name");
                        JsonElement stateElem = hostRolesObjs.get("state");

                        listOfCompoents.add(new ComponentInformation(componentNameElem.toString(),
                                hostNameElem.toString(), stateElem.toString()));
                    }/*from  ww w  .  j av  a 2s . com*/
                }
            }
        }
    }

    return listOfCompoents;
}

From source file:angularBeans.remote.InvocationHandler.java

License:LGPL

private void genericInvoke(Object service, String methodName, JsonObject params, Map<String, Object> returns,
        long reqID, String UID, HttpServletRequest request)

        throws SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException {

    Object mainReturn = null;/*from w w w .j a va2 s .  c  om*/
    Method m = null;
    JsonElement argsElem = params.get("args");

    if (reqID > 0) {
        returns.put("reqId", reqID);
    }
    if (argsElem != null) {

        JsonArray args = params.get("args").getAsJsonArray();

        for (Method mt : service.getClass().getMethods()) {

            if (mt.getName().equals(methodName)) {
                m = mt;
                Type[] parameters = mt.getParameterTypes();

                if (parameters.length == args.size()) {

                    List<Object> argsValues = new ArrayList<>();

                    for (int i = 0; i < parameters.length; i++) {

                        Class typeClass;

                        String typeString = ((parameters[i]).toString());

                        if (typeString.startsWith("interface")) {

                            typeString = typeString.substring(10);
                            typeClass = Class.forName(typeString);
                        } else {
                            if (typeString.startsWith("class")) {

                                typeString = typeString.substring(6);
                                typeClass = Class.forName(typeString);
                            } else {
                                typeClass = builtInMap.get(typeString);
                            }
                        }

                        JsonElement element = args.get(i);

                        if (element.isJsonPrimitive()) {

                            String val = element.getAsString();

                            argsValues.add(CommonUtils.convertFromString(val, typeClass));

                        } else if (element.isJsonArray()) {

                            JsonArray arr = element.getAsJsonArray();

                            argsValues.add(util.deserialise(arrayTypesMap.get(typeString), arr));

                        } else {

                            argsValues.add(util.deserialise(typeClass, element));
                        }
                    }

                    if (!CommonUtils.isGetter(mt)) {
                        update(service, params);
                    }

                    try {
                        mainReturn = mt.invoke(service, argsValues.toArray());
                    } catch (Exception e) {
                        handleException(mt, e);
                        e.printStackTrace();
                    }
                }
            }
        }
    } else {

        for (Method mt : service.getClass().getMethods()) {

            if (mt.getName().equals(methodName)) {

                Type[] parameters = mt.getParameterTypes();

                // handling methods that took HttpServletRequest as parameter

                if (parameters.length == 1) {

                    //                   if(mt.getParameters()[0].getType()==HttpServletRequest.class)   
                    //                    {
                    //                      System.out.println("hehe...");
                    //                      mt.invoke(service, request);
                    //                  
                    //                    }

                } else {
                    if (!CommonUtils.isGetter(m)) {
                        update(service, params);
                    }
                    mainReturn = mt.invoke(service);
                }

            }
        }

    }

    ModelQueryImpl qImpl = (ModelQueryImpl) modelQueryFactory.get(service.getClass());

    Map<String, Object> scMap = new HashMap<>(qImpl.getData());

    returns.putAll(scMap);

    qImpl.getData().clear();

    if (!modelQueryFactory.getRootScope().getRootScopeMap().isEmpty()) {
        returns.put("rootScope", new HashMap<>(modelQueryFactory.getRootScope().getRootScopeMap()));
        modelQueryFactory.getRootScope().getRootScopeMap().clear();
    }

    String[] updates = null;

    if (m.isAnnotationPresent(NGReturn.class)) {

        if (mainReturn == null)
            mainReturn = "";

        NGReturn ngReturn = m.getAnnotation(NGReturn.class);
        updates = ngReturn.updates();

        if (ngReturn.model().length() > 0) {
            returns.put(ngReturn.model(), mainReturn);
            Map<String, String> binding = new HashMap<>();

            binding.put("boundTo", ngReturn.model());

            mainReturn = binding;
        }
    }

    if (m.isAnnotationPresent(NGPostConstruct.class)) {
        NGPostConstruct ngPostConstruct = m.getAnnotation(NGPostConstruct.class);
        updates = ngPostConstruct.updates();

    }

    if (updates != null) {
        if ((updates.length == 1) && (updates[0].equals("*"))) {

            List<String> upd = new ArrayList<>();
            for (Method met : service.getClass().getDeclaredMethods()) {

                if (CommonUtils.isGetter(met)) {

                    String fieldName = (met.getName()).substring(3);
                    String firstCar = fieldName.substring(0, 1);
                    upd.add((firstCar.toLowerCase() + fieldName.substring(1)));

                }
            }

            updates = new String[upd.size()];

            for (int i = 0; i < upd.size(); i++) {
                updates[i] = upd.get(i);
            }
        }
    }

    if (updates != null) {
        for (String up : updates) {

            String getterName = GETTER_PREFIX + up.substring(0, 1).toUpperCase() + up.substring(1);
            Method getter;
            try {
                getter = service.getClass().getMethod(getterName);
            } catch (NoSuchMethodException e) {
                getter = service.getClass()
                        .getMethod((getterName.replace(GETTER_PREFIX, BOOLEAN_GETTER_PREFIX)));
            }

            Object result = getter.invoke(service);
            returns.put(up, result);

        }
    }

    returns.put("mainReturn", mainReturn);

    if (!logger.getLogPool().isEmpty()) {
        returns.put("log", logger.getLogPool().toArray());
        logger.getLogPool().clear();
    }
}

From source file:app.abhijit.iter.data.source.StudentDataSource.java

License:Open Source License

private void processStudentSubjects(String response) {
    mFetchStudentSubjectsAsyncTask = null;

    JsonObject student = mJsonParser.parse(mLocalStore.getString(mSelectedRegistrationNumber, null))
            .getAsJsonObject();/*from w ww  .  j  a v  a2  s .c  om*/
    JsonObject subjects = new JsonObject();

    try {
        JsonArray studentSubjects = mJsonParser.parse(response).getAsJsonArray();
        for (int i = 0; i < studentSubjects.size(); i++) {
            if (!studentSubjects.get(i).getAsJsonObject().has("subjectcode")
                    || !studentSubjects.get(i).getAsJsonObject().has("subject")
                    || !studentSubjects.get(i).getAsJsonObject().has("totalpresentclass")
                    || !studentSubjects.get(i).getAsJsonObject().has("totalclasses")) {
                continue;
            }
            String code = studentSubjects.get(i).getAsJsonObject().get("subjectcode").getAsString();
            String name = studentSubjects.get(i).getAsJsonObject().get("subject").getAsString();
            int presentClasses = studentSubjects.get(i).getAsJsonObject().get("totalpresentclass").getAsInt();
            int totalClasses = studentSubjects.get(i).getAsJsonObject().get("totalclasses").getAsInt();
            if (totalClasses <= 0 || presentClasses < 0 || presentClasses > totalClasses)
                continue;
            long lastUpdated = new Date().getTime();
            int oldPresentClasses = presentClasses;
            int oldTotalClasses = totalClasses;
            if (student.has(STUDENT_SUBJECTS_KEY)
                    && student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().has(code)) {
                oldPresentClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                        .getAsJsonObject().get(STUDENT_SUBJECT_PRESENT_CLASSES_KEY).getAsInt();
                oldTotalClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                        .getAsJsonObject().get(STUDENT_SUBJECT_TOTAL_CLASSES_KEY).getAsInt();
                if (presentClasses == oldPresentClasses && totalClasses == oldTotalClasses) {
                    lastUpdated = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                            .getAsJsonObject().get(STUDENT_SUBJECT_LAST_UPDATED_KEY).getAsLong();
                }
            }
            JsonObject subject = new JsonObject();
            subject.addProperty(STUDENT_SUBJECT_CODE_KEY, code);
            subject.addProperty(STUDENT_SUBJECT_NAME_KEY, name);
            subject.addProperty(STUDENT_SUBJECT_PRESENT_CLASSES_KEY, presentClasses);
            subject.addProperty(STUDENT_SUBJECT_TOTAL_CLASSES_KEY, totalClasses);
            subject.addProperty(STUDENT_SUBJECT_OLD_PRESENT_CLASSES_KEY, oldPresentClasses);
            subject.addProperty(STUDENT_SUBJECT_OLD_TOTAL_CLASSES_KEY, oldTotalClasses);
            subject.addProperty(STUDENT_SUBJECT_LAST_UPDATED_KEY, lastUpdated);
            subjects.add(code, subject);
        }
    } catch (Exception e) {
        if (student.has(STUDENT_SUBJECTS_KEY)) {
            subjects = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject();
        } else {
            subjects = new JsonObject();
        }
    }

    student.add(STUDENT_SUBJECTS_KEY, subjects);
    student.addProperty(STUDENT_TIMESTAMP_KEY, new Date().getTime());
    mLocalStore.edit().putString(mSelectedRegistrationNumber, student.toString()).apply();

    fetch();
}

From source file:application.Genius.java

License:Open Source License

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");/*from   w ww.  j  a  va2s .c  o m*/
    JsonObject response = null;
    try {
        URL queryURL = new URL(
                String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8")));
        Connection connection = Jsoup.connect(queryURL.toExternalForm())
                .header("Authorization", "Bearer " + Keys.GENIUS).ignoreContentType(true);
        Document document = connection.userAgent(USER_AGENT).get();
        response = new JsonParser().parse(document.text()).getAsJsonObject();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200)
        return results;
    JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits");

    int processed = 0;
    while (processed < hits.size()) {
        JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result");
        String artist = song.getAsJsonObject("primary_artist").get("name").getAsString();
        String title = song.get("title").getAsString();
        String url = "http://genius.com/songs/" + song.get("id").getAsString();
        Lyrics l = new Lyrics();
        l.mArtist = artist;
        l.mTitle = title;
        l.mSourceUrl = url;
        l.mSource = "Genius";
        results.add(l);
        processed++;
    }
    return results;
}

From source file:arces.unibo.SEPA.commons.SPARQL.BindingsResults.java

License:Open Source License

public boolean isEmpty() {
    JsonArray bindings = getBindingsArray();
    if (bindings == null)
        return true;

    return (bindings.size() == 0);
}

From source file:arces.unibo.SEPA.commons.SPARQL.BindingsResults.java

License:Open Source License

public int size() {
    JsonArray bindings = getBindingsArray();
    if (bindings == null)
        return 0;
    return bindings.size();
}

From source file:at.ac.dbisinformatik.snowprofile.web.svgcreator.SVGCreator.java

License:Open Source License

/**
 * creates a SVG-Graph for given jsonDocument which includes ExtJS-SVG-Objects. The created SVG-Document will be converted in the given export type. 
 * /*  www  .ja v a  2s  . c  o  m*/
 * @param jsonDocument
 * @param exportType
 * @param profileID
 * @return
 * @throws TransformerException
 * @throws URISyntaxException
 * @throws TranscoderException
 * @throws IOException
 */
public static ByteArrayOutputStream svgDocument(JsonArray jsonDocument, String exportType, String profileID)
        throws TransformerException, URISyntaxException, TranscoderException, IOException {

    ByteArrayOutputStream ret = null;

    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    // Get the root element (the 'svg' element).
    Element svgRoot = doc.getDocumentElement();

    // Set the width and height attributes on the root 'svg' element.
    svgRoot.setAttributeNS(null, "width", "1500");
    svgRoot.setAttributeNS(null, "height", "1500");
    JsonArray items = jsonDocument;

    for (int i = 0; i < items.size(); ++i) {
        String type = items.get(i).getAsJsonObject().get("type").getAsString();
        Element element = null;
        org.w3c.dom.Text test = null;
        String path = "";
        String width = "";
        String height = "";
        String x = "";
        String y = "";
        String fill = "";
        String text = "";
        String font = "";
        String fontFamily = "";
        String fontSize = "";
        String degrees = "";
        String stroke = "";
        String opacity = "";
        String src = "";
        switch (type) {
        case "rect":
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();
            opacity = items.get(i).getAsJsonObject().get("opacity").getAsString();

            // Create the rectangle.
            element = doc.createElementNS(svgNS, "rect");
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            element.setAttributeNS(null, "opacity", opacity);
            break;

        case "path":
            path = items.get(i).getAsJsonObject().get("path").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();

            // Create the path.
            element = doc.createElementNS(svgNS, "path");
            element.setAttributeNS(null, "d", path);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            break;

        case "image":
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            src = System.class.getResource("/at/ac/dbisinformatik/snowprofile/web/resources/"
                    + items.get(i).getAsJsonObject().get("src").getAsString()).toString();

            // Create the path.
            element = doc.createElementNS(svgNS, "image");
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "xlink:href", src);
            break;

        case "text":
            text = items.get(i).getAsJsonObject().get("text").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            font = items.get(i).getAsJsonObject().get("font").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();

            // Transformation
            if (items.get(i).getAsJsonObject().get("rotate") != null) {
                JsonObject temp = items.get(i).getAsJsonObject().get("rotate").getAsJsonObject();
                degrees = temp.get("degrees").getAsString();
            }

            fontSize = font.split(" ")[0];
            fontFamily = font.split(" ")[1];

            // Create the text.
            test = doc.createTextNode(text);
            element = doc.createElementNS(svgNS, "text");
            element.setAttributeNS(null, "text", text);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "font-family", fontFamily);
            element.setAttributeNS(null, "font-size", fontSize);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            if (!degrees.equals("")) {
                // element.setAttributeNS(null, "transform",
                // "rotate(270 "+500+","+80+")");
            }
            element.appendChild(test);
            break;

        default:
            break;
        }

        // Attach the rectangle to the root 'svg' element.
        svgRoot.appendChild(element);
    }

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    switch (exportType) {
    case "png":
        ret = createPNG(inputStream);
        break;

    case "jpg":
        ret = createJPG(inputStream);
        break;

    case "pdf":
        ret = createPDF(inputStream);
        break;

    default:
        break;
    }
    return ret;
}

From source file:at.orz.arangodb.util.JsonUtils.java

License:Apache License

public static int[] toArray(JsonArray array) {
    int len = array.size();
    int[] iarray = new int[len];
    for (int i = 0; i < len; i++) {
        iarray[i] = array.get(i).getAsInt();
    }//  www . jav a2  s .  c  o m
    return iarray;
}