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:mml.handler.get.MMLGetMMLHandler.java

/**
 * Debug: Check that the corcode stil ranges do not go beyond text end
 * @param stil the stil markup as text//from w ww. java 2s  .  c o m
 * @param text the text it refers to
 * @return true if it was OK, else false
 */
boolean verifyCorCode(String stil, String text) {
    JSONObject jObj = (JSONObject) JSONValue.parse(stil);
    JSONArray ranges = (JSONArray) jObj.get(JSONKeys.RANGES);
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject range = (JSONObject) ranges.get(i);
        offset += ((Number) range.get("reloff")).intValue();
        int len = ((Number) range.get("len")).intValue();
        if (offset + len > text.length())
            return false;
    }
    return true;
}

From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java

/**
 * If a column has transforms in the mapping, apply them to the input raw text
 * @param raw - untransformed string//  w ww.  ja  va2  s . c om
 * @param mappingJson - single mapping entry
 * @return
 */
private String applyTransforms(String raw, JSONObject mappingJson) {
    if (mappingJson.containsKey("transformList")) {
        String ret = raw;
        JSONArray transforms = (JSONArray) mappingJson.get("transformList");
        for (int i = 0; i < transforms.size(); i += 1) {
            ret = transformsAvailable.get((String) transforms.get(i)).applyTransform(ret);
        }
        return ret;

    } else {
        return raw;
    }
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function receives the revisions as a JSON string and obtains the
 * details for the revisions in a list of strings.
 * /*from  w w w .  j a  v  a  2  s. c  o m*/
 * @param revisionStr
 *            the string containing the revisions.
 * 
 * @return a vector with JSON strings describing the updated data sets.
 */
public static Vector<String> getUpdatedDatasets(String revisionStr) {

    // check the parameters
    if (revisionStr == null) {
        return null;
    }

    // the vector to return
    Vector<String> toreturnVector = new Vector<String>();

    // parse the JSON string and obtain an array of JSON objects
    Object obj = JSONValue.parse(revisionStr);
    JSONArray array = (JSONArray) obj;

    // prepare the URL string
    String CKANurl = url + "/api/rest/revision/";

    // iterate over the JSON objects
    for (int i = 0; i < array.size(); i++) {
        String revisionUrl = CKANurl + array.get(i).toString();

        // read the information for the revision from the CKAN API
        URL RevisionUrlInstance;
        String revisionDescriptionStr = "";
        try {

            // open a connection to the CKAN API
            RevisionUrlInstance = new URL(revisionUrl);
            URLConnection RevisionUrlInstanceConnection = RevisionUrlInstance.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(RevisionUrlInstanceConnection.getInputStream()));

            // read the output from the API
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                revisionDescriptionStr += inputLine;
            }
            in.close();

            // the description
            toreturnVector.add(revisionDescriptionStr);

        }
        // process exceptions
        catch (MalformedURLException e) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + CKANurl + "\" !!!");
            toreturnVector.add(null);
            continue;
        } catch (IOException e) {
            toreturnVector.add(null);
            continue;
        }
    }

    return toreturnVector;
}

From source file:eu.serco.dhus.plugin.sral.SralPlugin.java

public Object process(Object input) {
    List<Response> result = new ArrayList<Response>();

    String filename = input.toString();
    if (filename == null) {
        System.out.println("[ERROR]: null filename. Process aborted.");
        return result;
    }// ww w.  j  a  va 2 s  .  c  o m
    try {
        String productType = filename.substring(4, 15);
        String startTime = filename.substring(16, 31);
        String stopTime = filename.substring(32, 47);
        if (map.containsKey(productType)) {
            List<Request> requestList = retrieveRequests(productType, startTime, stopTime);
            List<RequestTask> tasks = new ArrayList<RequestTask>();
            for (Request aux_request : requestList) {
                Response response = new Response();
                response.setMandatory(aux_request.getMandatory());
                logger.info("requestList.size() " + requestList.size());
                logger.info("aux_request.getRequests().size() " + aux_request.getRequests().size());
                List<InputRequest> requestsMap = aux_request.getRequests();

                for (InputRequest inReqs : requestsMap) {

                    tasks.add(new RequestTask(inReqs.getUrl(), inReqs.getType(), inReqs.getRetrievalMode(),
                            hashedString, SralPlugin.executor));
                    logger.info("url added to tasks list " + inReqs);
                }
                while (!tasks.isEmpty()) {
                    List<Object> responses = new ArrayList<Object>();
                    logger.info("tasks size..... " + tasks.size());

                    for (Iterator<RequestTask> it = tasks.iterator(); it.hasNext();) {
                        RequestTask task = it.next();
                        OutputResponse outRes = new OutputResponse();
                        if (task.isDone()) {
                            String req = task.getRequest();
                            String type = task.getRequestType();
                            logger.info("Request task.getRequest() " + req);
                            String res = task.getResponse();
                            logger.info("Response task.getResponse() " + res);
                            JSONArray jsonResponse = (JSONArray) new JSONParser().parse(res);
                            JSONArray jsonResult;
                            logger.info("How is the response?????" + jsonResponse);
                            if (jsonResponse != null) {
                                logger.info("How long is the response?????" + jsonResponse.size());
                            }
                            if (task.getRetrievalMode().equalsIgnoreCase("LatestValidityClosest")
                                    && jsonResponse != null && jsonResponse.size() > 0) {
                                jsonResult = getLatestValidityClosestInput(startTime, stopTime, jsonResponse);
                            } else {
                                jsonResult = jsonResponse;
                            }
                            outRes.setResponse(jsonResult);
                            outRes.setType(type);
                            responses.add(outRes);

                            it.remove();
                        }
                    }
                    response.setFiles(responses);
                    //avoid tight loop in "main" thread
                    if (!tasks.isEmpty())
                        Thread.sleep(100);
                }
                result.add(response);
            }

        }
    } catch (Exception e) {
        logger.error("[ERROR]: Problems occurred during file processing: " + e.getMessage());
        e.printStackTrace();
    }
    return result;
}

From source file:net.matthewauld.racetrack.server.WrSQL.java

@SuppressWarnings("unchecked")
public String getJSONString(String query, String[] args) throws SQLException {
    connect();// w w w .  j  ava 2 s  . c o  m
    ps = con.prepareStatement(query);
    for (int i = 0; i < args.length; i++) {
        ps.setString(i + 1, args[i]);
    }

    rs = ps.executeQuery();
    JSONObject json = new JSONObject();
    JSONArray riders = new JSONArray();
    while (rs.next()) {
        JSONObject riderJSON = new JSONObject();
        riderJSON.put("id", rs.getInt("id"));
        riderJSON.put("first_name", rs.getString("first_name"));
        riderJSON.put("last_name", rs.getString("last_name"));
        riders.add(riderJSON);
    }
    if (riders.size() == 0) {
        json.put("riders", null);
    } else {
        json.put("riders", riders);
    }

    return json.toJSONString();
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];//from   www .  ja v a  2  s  .  co m
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = "42";
    String profile = (String) PERSIST.get("profile");
    JSONObject providerProfile = (JSONObject) JSONValue.parse(profile);
    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:hoot.services.controllers.job.JobResourceTest.java

/**
 * Tests the processChainJob failure by _execReflection
 *
 * @throws Exception//from   ww  w .j  av  a2  s . com
 */
@Test
@Category(UnitTest.class)
public void testProcessChainJobFailure() throws Exception {
    // Create Mock JobStatusManager Class
    JobStatusManager mockJobStatusManager = Mockito.mock(JobStatusManager.class);
    Mockito.doNothing().when(mockJobStatusManager).addJob(Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).updateJob(Matchers.anyString(), Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).setComplete(Matchers.anyString(), Matchers.anyString());
    Mockito.doNothing().when(mockJobStatusManager).setFailed(Matchers.anyString(), Matchers.anyString());

    // Mock child info
    JSONObject mockChild = new JSONObject();
    mockChild.put("id", "test_child_123_FAIL");
    mockChild.put("detail", "processing");
    mockChild.put("status", "running");

    JobResource real = new JobResource();
    JobResource spy = Mockito.spy(real);

    // so I use this to avoid actual call
    Mockito.doReturn(Response.ok().build()).when(spy).processJob(Matchers.anyString(), Matchers.anyString());
    Mockito.doReturn(mockJobStatusManager).when(spy).createJobStatusMananger(Matchers.any(Connection.class));

    // failure point
    Mockito.doThrow(new Exception("Mock failure for testing Process Chain Job failure. (Not real failure!!!)"))
            .when(spy).execReflection(Matchers.anyString(), Matchers.any(JSONObject.class),
                    Matchers.any(JobStatusManager.class));

    try {
        String jobStr = "[{\"caller\":\"FileUploadResource\",\"exec\":\"makeetl\","
                + "\"params\":[{\"INPUT\":\"upload\\/81898818-2ca3-4a15-9421-50eb91952586\\/GroundPhotos.shp\"},"
                + "{\"INPUT_TYPE\":\"OGR\"},{\"TRANSLATION\":\"translations\\/UTP.js\"},{\"INPUT_NAME\":\"GroundPhotos\"}],"
                + "\"exectype\":\"make\"},{\"class\":\"hoot.services.controllers.ingest.RasterToTilesService\","
                + "\"method\":\"ingestOSMResource\",\"params\":[{\"isprimitivetype\":\"false\",\"value\":\"GroundPhotos\","
                + "\"paramtype\":\"java.lang.String\"}],\"exectype\":\"reflection\"}]";

        spy.processChainJob("test_job_id_1234_FAIL", jobStr);

        // sleep for a couple of secs to make sure that all threads spawned by the the call to spy.processChainJob() finish
        Thread.sleep(2000);
    } catch (WebApplicationException wex) {
        Response res = wex.getResponse();
        Assert.assertEquals(500, res.getStatus());
    }

    // There should be one success for first part being completed. Second
    // would be setFailed which updates db directly so update is not called.
    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(2)).updateJob(Matchers.anyString(), argCaptor.capture());

    JSONParser parser = new JSONParser();

    List<String> args = argCaptor.getAllValues();
    JSONObject status = (JSONObject) parser.parse(args.get(0));
    JSONArray children = (JSONArray) status.get("children");
    JSONObject child = (JSONObject) children.get(0);

    Assert.assertEquals("processing", child.get("detail").toString());
    Assert.assertEquals("running", child.get("status").toString());

    status = (JSONObject) parser.parse(args.get(1));
    children = (JSONArray) status.get("children");
    Assert.assertEquals(1, children.size());

    child = (JSONObject) children.get(0);
    Assert.assertEquals("success", child.get("detail").toString());
    Assert.assertEquals("complete", child.get("status").toString());

    // Check for setFailed invocation
    ArgumentCaptor<String> setFailedArgCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(1)).setFailed(Matchers.anyString(),
            setFailedArgCaptor.capture());

    args = setFailedArgCaptor.getAllValues();
    status = (JSONObject) parser.parse(args.get(0));
    children = (JSONArray) status.get("children");

    Assert.assertEquals(1, children.size());

    child = (JSONObject) children.get(0);
    Assert.assertEquals("Mock failure for testing Process Chain Job failure. (Not real failure!!!)",
            child.get("detail").toString());
    Assert.assertEquals("failed", child.get("status").toString());
}

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

public synchronized void updateWhiteList(JSONArray object) {

    // Load the storage directory
    File charactersDirectory = new File(inst.getDataFolder().getPath() + "/characters");
    if (!charactersDirectory.exists())
        charactersDirectory.mkdir();//from w w w .ja  v  a 2  s.  c om
    log.info("Updating white list...");

    if (!loadCharacters((JSONObject[]) object.toArray(new JSONObject[object.size()]))) {
        log.info("No changes detected.");
        return;
    }

    // Remove outdated JSON backup files
    for (File file : charactersDirectory.listFiles(filenameFilter)) {
        file.delete();
    }

    // Create new JSON backup file
    BufferedWriter out = null;

    File characterList = new File(charactersDirectory, "character-list.json");
    try {
        if (characterList.createNewFile()) {
            out = new BufferedWriter(new FileWriter(characterList));
            out.write(object.toJSONString());
        } else {
            log.warning("Could not create the new character list offline file!");
        }
    } catch (IOException ignored) {
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
    }

    log.info("The white list has updated successfully.");
}

From source file:com.titankingdoms.nodinchan.mobjockeys.MobJockeys.java

/**
 * Checks for update of the library//from   w w w .  j  ava  2 s  .c  o  m
 */
private void updateLib() {
    PluginManager pm = getServer().getPluginManager();

    NCBL libPlugin = (NCBL) pm.getPlugin("NC-BukkitLib");

    File destination = new File(getDataFolder().getParentFile().getParentFile(), "lib");
    destination.mkdirs();

    File lib = new File(destination, "NC-BukkitLib.jar");
    File pluginLib = new File(getDataFolder().getParentFile(), "NC-BukkitLib.jar");

    boolean inPlugins = false;
    boolean download = false;

    try {
        URL url = new URL("http://bukget.org/api/plugin/nc-bukkitlib");

        JSONObject jsonPlugin = (JSONObject) new JSONParser().parse(new InputStreamReader(url.openStream()));
        JSONArray versions = (JSONArray) jsonPlugin.get("versions");

        if (libPlugin == null) {
            getLogger().log(Level.INFO, "Missing NC-Bukkit lib");
            inPlugins = true;
            download = true;

        } else {
            double currentVer = Double.parseDouble(libPlugin.getDescription().getVersion());
            double newVer = currentVer;

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    newVer = Double
                            .parseDouble(((String) version.get("name")).split(" ")[1].trim().substring(1));
                    break;
                }
            }

            if (newVer > currentVer) {
                getLogger().log(Level.INFO, "NC-Bukkit lib outdated");
                download = true;
            }
        }

        if (download) {
            System.out.println("Downloading NC-Bukkit lib...");

            String dl_link = "";

            for (int ver = 0; ver < versions.size(); ver++) {
                JSONObject version = (JSONObject) versions.get(ver);

                if (version.get("type").equals("Release")) {
                    dl_link = (String) version.get("dl_link");
                    break;
                }
            }

            if (dl_link == null)
                throw new Exception();

            URL link = new URL(dl_link);
            ReadableByteChannel rbc = Channels.newChannel(link.openStream());

            if (inPlugins) {
                FileOutputStream output = new FileOutputStream(pluginLib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
                pm.loadPlugin(pluginLib);

            } else {
                FileOutputStream output = new FileOutputStream(lib);
                output.getChannel().transferFrom(rbc, 0, 1 << 24);
            }

            getLogger().log(Level.INFO, "Downloaded NC-Bukkit lib");
        }

    } catch (Exception e) {
        System.out.println("Failed to check for library update");
    }
}

From source file:be.appfoundry.custom.google.android.gcm.server.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, String, int)} for more info.
 *
 * @return result of the post, or {@literal null} if the GCM service was
 * unavailable or any network exception caused the request to fail,
 * or if the response contains more than one result.
 * @throws InvalidRequestException  if GCM didn't returned a 200 status.
 * @throws IllegalArgumentException if to is {@literal null}.
 */// w  w w  .j a  v  a  2s  .co  m
public Result sendNoRetry(Message message, String to) throws IOException {
    nonNull(to);
    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    messageToMap(message, jsonRequest);
    jsonRequest.put(JSON_TO, to);
    String responseBody = makeGcmHttpRequest(jsonRequest);
    if (responseBody == null) {
        return null;
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        Result.Builder resultBuilder = new Result.Builder();
        if (jsonResponse.containsKey("results")) {
            // Handle response from message sent to specific device.
            JSONArray jsonResults = (JSONArray) jsonResponse.get("results");
            if (jsonResults.size() == 1) {
                JSONObject jsonResult = (JSONObject) jsonResults.get(0);
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                resultBuilder.messageId(messageId).canonicalRegistrationId(canonicalRegId).errorCode(error);
            } else {
                logger.log(Level.WARNING, "Found null or " + jsonResults.size() + " results, expected one");
                return null;
            }
        } else if (to.startsWith(TOPIC_PREFIX)) {
            if (jsonResponse.containsKey(JSON_MESSAGE_ID)) {
                // message_id is expected when this is the response from a topic message.
                Long messageId = (Long) jsonResponse.get(JSON_MESSAGE_ID);
                resultBuilder.messageId(messageId.toString());
            } else if (jsonResponse.containsKey(JSON_ERROR)) {
                String error = (String) jsonResponse.get(JSON_ERROR);
                resultBuilder.errorCode(error);
            } else {
                logger.log(Level.WARNING,
                        "Expected " + JSON_MESSAGE_ID + " or " + JSON_ERROR + " found: " + responseBody);
                return null;
            }
        } else if (jsonResponse.containsKey(JSON_SUCCESS) && jsonResponse.containsKey(JSON_FAILURE)) {
            // success and failure are expected when response is from group message.
            int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
            int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
            List<String> failedIds = null;
            if (jsonResponse.containsKey("failed_registration_ids")) {
                JSONArray jFailedIds = (JSONArray) jsonResponse.get("failed_registration_ids");
                failedIds = new ArrayList<String>();
                for (int i = 0; i < jFailedIds.size(); i++) {
                    failedIds.add((String) jFailedIds.get(i));
                }
            }
            resultBuilder.success(success).failure(failure).failedRegistrationIds(failedIds);
        } else {
            logger.warning("Unrecognized response: " + responseBody);
            throw newIoException(responseBody, new Exception("Unrecognized response."));
        }
        return resultBuilder.build();
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}