Example usage for org.json.simple JSONArray size

List of usage examples for org.json.simple JSONArray size

Introduction

In this page you can find the example usage for org.json.simple JSONArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:me.neatmonster.spacertk.actions.ServerActions.java

/**
 * Restarts the server if it's emtpy/*  w  ww  .  j av  a  2s.c o  m*/
 * @param save If the server should be saved before restarting
 * @return If successful
 */
@Action(aliases = { "restartIfEmpty", "restartServerIfEmpty" })
public boolean restartIfEmpty(final Boolean save) {
    final JSONArray players = (JSONArray) JSONValue.parse(Utilities.sendMethod("getPlayers", "[]"));
    if (players == null || players.size() == 0)
        RemoteToolkit.restart(save);
    return true;
}

From source file:co.mcme.animations.animations.MCMEAnimation.java

private void loadTriggers() {
    JSONArray interactions = (JSONArray) animationConfiguration.get("interactions");

    for (int i = 0; i < interactions.size(); i++) {
        JSONObject interaction = (JSONObject) interactions.get(i);
        JSONObject interactionType = (JSONObject) interaction.get("block_interaction");

        if (null != interactionType) {
            //BLOCK INTERACTION
            int frame = ((Long) interactionType.get("frame")).intValue();
            JSONArray blocks = (JSONArray) interactionType.get("blocks");
            ArrayList<Vector> blocksArray = new ArrayList<Vector>();
            for (int j = 0; j < blocks.size(); j++) {
                JSONObject coordsObj = (JSONObject) blocks.get(j);
                JSONArray coords = (JSONArray) coordsObj.get("block");
                Vector v = new Vector(((Long) coords.get(0)).intValue(), ((Long) coords.get(1)).intValue(),
                        ((Long) coords.get(2)).intValue());
                blocksArray.add(v);/*from   w  w  w.  java2 s .  co m*/
            }
            if (blocksArray.size() > 0) {
                BlockInteractTrigger bit = new BlockInteractTrigger(this, blocksArray, frame);
                MCMEAnimations.triggers.add(bit);
            }
            continue;
        }

        interactionType = (JSONObject) interaction.get("shape_interaction");

        if (null != interactionType) {
            //SHAPE INTERACTION
            int frame = ((Long) interactionType.get("frame")).intValue();
            ShapeInteractTrigger sit = new ShapeInteractTrigger(this, frame);
            MCMEAnimations.triggers.add(sit);
            continue;
        }

        interactionType = (JSONObject) interaction.get("player_chat");

        if (null != interactionType) {
            //PLAYER CHAT
            int frame = ((Long) interactionType.get("frame")).intValue();
            double distance = ((Double) interactionType.get("distance"));
            String message = (String) interactionType.get("message");
            PlayerChatTrigger pct = new PlayerChatTrigger(this, frame, distance, message);
            MCMEAnimations.triggers.add(pct);
            continue;
        }

        interactionType = (JSONObject) interaction.get("always_active");

        if (null != interactionType) {
            //ALWAYS ACTIVE
            AlwaysActiveTrigger aat = new AlwaysActiveTrigger(this);
            MCMEAnimations.triggers.add(aat);
            continue;
        }

    }
}

From source file:cc.pinel.mangue.ui.ChaptersPanel.java

/**
 * Loads all chapters from the given manga.
 * //from  ww  w.  j ava2 s  . co m
 * @param manga the manga
 */
public void loadChapters(final Manga manga) {
    if (this.manga != null && this.manga.getId().equals(manga.getId()))
        return;

    this.manga = manga;
    rememberManga();

    new StorageHandler(main.getContext(), "Loading mangas...") {
        /**
         * {@inheritDoc}
         */
        public void handleRun() throws Exception {
            final String lastChapterNumber = new StateStorage(main.getContext()).getChapter(manga.getId());

            final ConnectivityHandler handler = new ConnectivityHandler(main.getContext(),
                    "Loading chapters...") {
                /**
                 * {@inheritDoc}
                 */
                public void handleConnected() throws Exception {
                    JSONParser parser = new JSONParser();
                    JSONArray chapters = (JSONArray) parser
                            .parse(IOUtils.toString(new URL(manga.getAllChaptersLink()).openStream()));

                    chaptersPages.removeAllItems();
                    for (int i = chapters.size() - 1; i >= 0; i--) {
                        JSONObject chapter = (JSONObject) chapters.get(i);
                        String chapterNumber = chapter.get("chapter").toString();
                        String chapterName = StringUtils.unescapeHtml(chapter.get("chapter_name").toString());
                        String chapterTitle = chapterNumber
                                + (chapterName != null && chapterName.length() != 0 ? ": " + chapterName : "");

                        final KWTSelectableLabel chapterLabel = new KWTSelectableLabel(chapterTitle);
                        chapterLabel.setName(chapterNumber);
                        chapterLabel.setFocusable(true);
                        chapterLabel.setEnabled(true);
                        chapterLabel.addActionListener(chapterListener);

                        // last read chapter
                        if (lastChapterNumber != null && chapterNumber.equals(lastChapterNumber))
                            highlightLabel(chapterLabel);

                        chaptersPages.addItem(chapterLabel);
                    }

                    EventQueue.invokeAndWait(new Runnable() {
                        public void run() {
                            chaptersPages.first();

                            requestFocus();
                            repaint();
                        }
                    });
                }
            };

            main.getContext().getConnectivity().submitSingleAttemptConnectivityRequest(handler, true);
        }
    }.start();
}

From source file:de.ingrid.iplug.dsc.utils.BwstrLocUtil.java

/**
 * Get the center coordinate from the parsed response.
 * //from www  .j a  v a2 s  .  com
 * @param parsedResponse
 * @return The center in Double[centerLon, centerLat].
 */
public Double[] getCenter(JSONObject parsedResponse) {

    Double[] result = null;

    try {
        JSONObject re = (JSONObject) ((JSONArray) parsedResponse.get("result")).get(0);
        JSONArray coordinates = (JSONArray) ((JSONObject) re.get("geometry")).get("coordinates");
        int maxNoOfCoordinates = 0;
        Double centerLon = null;
        Double centerLat = null;
        for (int i = 0; i < coordinates.size(); i++) {
            JSONArray a = (JSONArray) coordinates.get(i);
            maxNoOfCoordinates += a.size();
        }
        int cnt = 0;
        int centerCnt = ((int) (maxNoOfCoordinates / 2));

        for (Object c : coordinates) {
            JSONArray a = (JSONArray) c;
            for (Object cc : a) {
                cnt++;
                JSONArray aa = (JSONArray) cc;
                double lon = (Double) aa.get(0);
                double lat = (Double) aa.get(1);
                if (cnt == centerCnt) {
                    centerLon = lon;
                    centerLat = lat;
                    break;
                }
            }
        }

        result = new Double[] { centerLon, centerLat };
    } catch (Exception e) {
        log.error("Error parsing BwstrLoc response: " + parsedResponse.toJSONString(), e);
    }

    return result;
}

From source file:de.ingrid.external.gemet.GEMETClient.java

/**
 * Check whether the given concept has the given relation to any object.
 * //  w  ww.ja  v a2s  .  c  o  m
 * @param conceptUri
 *            relation from
 * @param relation
 *            relation type
 * @return true or false
 */
private boolean hasRelation(String conceptUri, ConceptRelation relation, String language) {
    JSONArray concepts = getAllConceptRelatives(conceptUri, relation, language);
    return (concepts.size() > 0);
}

From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java

/**
 * {@inheritDoc}/*  w  w w.ja v a  2 s .co  m*/
 * 
 * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#getCollectionContents(java.lang.String)
 */
@Override
public URI[] getCollectionContents(String collectionId) throws NotFoundException {
    String urlSuffix = UrlSupport.concat(new String[] { "list", collectionId + ".json" });
    HttpGet get = new HttpGet(urlSuffix);
    HttpResponse response = getResponse(get, SC_OK, SC_NOT_FOUND);
    try {
        if (response != null) {
            if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                throw new NotFoundException();
            } else {
                String json = EntityUtils.toString(response.getEntity());
                JSONArray jsonArray = (JSONArray) JSONValue.parse(json);
                URI[] uris = new URI[jsonArray.size()];
                for (int i = 0; i < jsonArray.size(); i++) {
                    uris[i] = new URI((String) jsonArray.get(i));
                }
                return uris;
            }
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException();
    } finally {
        closeConnection(response);
    }
    throw new RuntimeException("Error getting collection contents");
}

From source file:co.mcme.animations.animations.MCMEAnimation.java

private void loadActions() {
    JSONArray actions = (JSONArray) animationConfiguration.get("actions");
    if (null != actions) {
        for (int i = 0; i < actions.size(); i++) {
            JSONObject action = (JSONObject) actions.get(i);

            JSONObject actionType = (JSONObject) action.get("explosion");
            if (null != actionType) {
                int frame = ((Long) actionType.get("frame")).intValue();
                ExplosionAction exp = new ExplosionAction(this, frame);
                MCMEAnimations.actions.add(exp);
            }//www.j  a  v a2  s. c o  m

            actionType = (JSONObject) action.get("move_players");
            if (null != actionType) {
                int frame = ((Long) actionType.get("frame")).intValue();
                //                    JSONArray direction = (JSONArray) actionType.get("direction");
                //                    if (null != direction) {
                //                        double x = (Double) direction.get(0);
                //                        double y = (Double) direction.get(1);
                //                        double z = (Double) direction.get(2);
                //
                //                        com.sk89q.worldedit.Vector v = new com.sk89q.worldedit.Vector(x, y, z);
                //                        MovePlayersAction mpa = new MovePlayersAction(this, frame, v);
                MovePlayersAction mpa = new MovePlayersAction(this, frame);
                MCMEAnimations.actions.add(mpa);
                //                    }
            }

            actionType = (JSONObject) action.get("chain_animation");
            if (null != actionType) {
                int frame = ((Long) actionType.get("frame")).intValue();
                String target = (String) actionType.get("target");
                ChainAnimationAction caa = new ChainAnimationAction(this, frame, target);
                MCMEAnimations.actions.add(caa);
            }

            actionType = (JSONObject) action.get("sound");
            if (null != actionType) {
                int frame = ((Long) actionType.get("frame")).intValue();
                String sound = (String) actionType.get("sound");
                double radius = (Double) actionType.get("radius");
                PlaySoundAction psa = new PlaySoundAction(this, frame, sound, radius);
                MCMEAnimations.actions.add(psa);
            }
        }
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_metric_exceptions() throws Exception {
    // GIVEN//from   w ww  .j a  va2 s  .c o m
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, ExceptionDocumentation> exsNameToDescriptionMap = new HashMap<String, ExceptionDocumentation>();
    addException("invalid_parameter", "Please add valid parameter", 400, "The parameter is invalid",
            exsNameToDescriptionMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(1);

        JSONArray exsParam = (JSONArray) obj.get("exceptions");
        for (int i = 0; i < exsParam.size(); i++) {
            JSONObject currentParam = (JSONObject) exsParam.get(i);
            String currentName = (String) currentParam.get("name");
            ExceptionDocumentation correctCurrentParam = exsNameToDescriptionMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("condition"), correctCurrentParam.getCondition());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("code"), new Long(correctCurrentParam.getCode()));
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_stream_exceptions() throws Exception {
    // GIVEN/*  w  w  w.j  av  a 2s.  c  o m*/
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, ExceptionDocumentation> exsNameToDescriptionMap = new HashMap<String, ExceptionDocumentation>();
    addException("invalid_since_until", "Since/until parameter must be within the last 30 days", 400,
            "The period is invalid", exsNameToDescriptionMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(0);

        JSONArray exsParam = (JSONArray) obj.get("exceptions");
        for (int i = 0; i < exsParam.size(); i++) {
            JSONObject currentParam = (JSONObject) exsParam.get(i);
            String currentName = (String) currentParam.get("name");
            ExceptionDocumentation correctCurrentParam = exsNameToDescriptionMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("condition"), correctCurrentParam.getCondition());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("code"), new Long(correctCurrentParam.getCode()));
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.skelril.aurora.authentication.AuthComponent.java

private synchronized void loadBackupWhiteList() {

    File charactersDirectory = new File(inst.getDataFolder().getPath() + "/characters");
    File characterFile = new File(charactersDirectory, "character-list.json");
    if (!characterFile.exists()) {
        log.warning("No offline file found!");
        return;//w  w  w  .  j  a  va  2 s. c o  m
    }

    BufferedReader reader = null;
    JSONParser parser = new JSONParser();

    try {
        reader = new BufferedReader(new FileReader(characterFile));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        JSONArray characterArray = ((JSONArray) parser.parse(builder.toString()));
        loadCharacters((JSONObject[]) characterArray.toArray(new JSONObject[characterArray.size()]));
    } catch (IOException e) {
        log.warning("Could not read file: " + characterFile.getName() + ".");
    } catch (ParseException p) {
        log.warning("Could not parse file: " + characterFile.getName() + ".");
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }

    log.info("The offline file has been loaded.");
}