Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:importer.Archive.java

/**
 * Using the project version info set long names for each short name
 * @param docid the project docid//from w ww  .  ja va2s .  co  m
 * @throws ImporterException 
 */
public void setVersionInfo(String docid) throws ImporterException {
    try {
        String project = Connector.getConnection().getFromDb(Database.PROJECTS, docid);
        if (project == null) {
            String[] parts = docid.split("/");
            if (parts.length == 3)
                docid = parts[0] + "/" + parts[1];
            else
                throw new Exception("Couldn't find project " + docid);
            project = Connector.getConnection().getFromDb(Database.PROJECTS, docid);
            if (project == null)
                throw new Exception("Couldn't find project " + docid);
        }
        JSONObject jObj = (JSONObject) JSONValue.parse(project);
        if (jObj.containsKey(JSONKeys.VERSIONS)) {
            JSONArray versions = (JSONArray) jObj.get(JSONKeys.VERSIONS);
            for (int i = 0; i < versions.size(); i++) {
                JSONObject version = (JSONObject) versions.get(i);
                Set<String> keys = version.keySet();
                Iterator<String> iter = keys.iterator();
                while (iter.hasNext()) {
                    String key = iter.next();
                    nameMap.put(key, (String) version.get(key));
                }
            }
        }
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:librarysystem.JSONHandlerElsiever.java

public List<Journal> parseJson() {
    //  String elsevier = "http://api.elsevier.com/content/search/scidir?apiKey=" + KEY + "&query=ttl(neural)";
    try {//w  ww  .ja v  a  2  s  .  c  o  m
        //URL uri = new URL(elsevier);

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(readUrl(url));
        JSONObject jsonObject = (JSONObject) obj;
        JSONObject searchObj = (JSONObject) jsonObject.get("search-results");

        if (searchObj.containsKey("entry")) {
            JSONArray entryarray = (JSONArray) searchObj.get("entry");
            Journal j = null;// new Journal();
            blist = new ArrayList<Journal>();
            //JSONArray autharray = null;

            for (int i = 0; i < entryarray.size(); i++) {
                j = new Journal();
                JSONObject jnext = (JSONObject) entryarray.get(i);

                j.setID(0);
                j.setAbstract(jnext.get("prism:teaser").toString());
                j.setPublication(jnext.get("prism:publicationName").toString());
                j.settitle(jnext.get("dc:title").toString());
                j.setisbn(jnext.get("prism:issn").toString());
                j.setYear(jnext.get("prism:coverDisplayDate").toString());
                String auths = "";

                if (jnext.containsKey("authors")) {
                    JSONObject jauthors = (JSONObject) jnext.get("authors");
                    JSONArray autharray = (JSONArray) jauthors.get("author");

                    for (int x = 0; x < autharray.size(); x++) {
                        JSONObject anext = (JSONObject) autharray.get(x);
                        auths = auths + " " + anext.get("given-name") + " " + anext.get("surname");
                    }
                    j.setauthors(auths);
                } else
                    j.setauthors("");

                blist.add(j);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return blist;
}

From source file:main.java.gov.wa.wsdot.candidate.evaluation.App.java

/**
 * Returns an ArrayList of Camera objects that are within a given radius of
 * users location.//from   w w w . j ava 2  s  .  c o m
 * 
 * @param jArray    JSONArray with WSDOT camera data
 * @param userLat   users current latitude
 * @param userLong  users current longitude
 * @param radius    max distance to look for cameras
 * @return          ArrayList of cameras within max distance of users location
 */
private ArrayList<Camera> scanCameras(JSONArray jArray, double userLat, double userLong, int radius) {

    JSONObject jObj1;
    JSONObject jObj2;
    double camLat;
    double camLong;
    double dist;
    ArrayList<Camera> cameras = new ArrayList<Camera>();

    for (int i = 0; i < jArray.size(); i++) {
        jObj1 = (JSONObject) jArray.get(i);
        jObj2 = (JSONObject) jObj1.get("CameraLocation");
        camLat = (double) jObj2.get("Latitude");
        camLong = (double) jObj2.get("Longitude");
        dist = getDistance(userLat, userLong, camLat, camLong);
        if (dist < radius) {
            cameras.add(new Camera(jObj1.get("Title").toString(), dist));
        }
    }
    return cameras;
}

From source file:net.bashtech.geobot.JSONUtil.java

public static String whatShouldIPlay(String userID) {
    String api_key = BotManager.getInstance().SteamAPIKey;

    try {//from  www. j ava2 s . com
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager
                .getRemoteContent("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key="
                        + api_key + "&steamid=" + userID + "&format=json&include_appinfo=1"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONObject response = (JSONObject) (jsonObject.get("response"));
        JSONArray games = (JSONArray) response.get("games");

        if (games.size() > 0) {
            int randomGame = (int) (Math.random() * games.size() - 1);
            JSONObject index0 = (JSONObject) games.get(randomGame);
            String randomGameName = (String) index0.get("name");
            return randomGameName;
        } else {
            return "User has no games";

        }

    } catch (Exception ex) {
        System.out.println("Failed to query Steam API");
        return "Error querying API";
    }
}

From source file:es.alrocar.jpe.writer.handler.MiniJPEWriterHandler.java

/**
 * {@inheritDoc}/*ww w .jav a2s  . c o  m*/
 */
public Object endPoint(Object point, String from, String to) {
    JSONArray coords = ((JSONArray) ((LinkedHashMap) point).get("coordinates"));

    try {
        double[] xy = GeotoolsUtils.transform(from, to, new double[] {
                Double.valueOf(String.valueOf(coords.get(0))), Double.valueOf(String.valueOf(coords.get(1))) });
        if (xy != null) {
            coords.set(0, xy[0]);
            coords.set(1, xy[1]);
            ((LinkedHashMap) point).put("coordinates", coords);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return point;
}

From source file:cc.pinel.mangue.storage.MangaStorage.java

public Collection getMangas() {
    Collection mangas = new ArrayList();

    JSONArray jsonMangas = null;
    try {//from  w  w  w. ja  v  a  2s.co  m
        jsonMangas = (JSONArray) readJSON().get("mangas");
    } catch (Exception e) {
        // ignored
    }
    if (jsonMangas == null)
        jsonMangas = new JSONArray();

    for (int i = 0; i < jsonMangas.size(); i++) {
        JSONObject jsonManga = (JSONObject) jsonMangas.get(i);
        mangas.add(new Manga(jsonManga.get("id").toString(), jsonManga.get("name").toString(),
                jsonManga.get("path").toString()));
    }

    return mangas;
}

From source file:matrix.CreateUrlMatrix.java

public void urlMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweetsUrls.json"), "ISO-8859-9"));
    JSONArray a = (JSONArray) jParser.parse(in);
    File fout = new File("/Users/nSabri/Desktop/urlMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < a.size(); i++) {

        for (int j = 0; j < a.size(); j++) {

            JSONObject tweet1 = (JSONObject) a.get(i);
            JSONObject tweet2 = (JSONObject) a.get(j);
            String tweetUrl1 = tweet1.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl1);
            String tweetUrl2 = tweet2.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl2);

            double CosSimValue = cossim.Cosine_Similarity_Score(tweetUrl1, tweetUrl2);
            CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue));
            bw.write(Double.toString(CosSimValue) + ", ");

        }/*from  www . j a  v  a2s .c  om*/
        bw.newLine();
    }
    bw.close();

}

From source file:control.ParametrizacionServlets.InsertarAsociacionContratos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w ww  .  j  a v  a 2  s. com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        objectErrores = new JSONObject();
        arrayErrores = new JSONArray();

        //Obtenemos el numero de contrato
        Double contratoPadre = Double.parseDouble(request.getParameter("contrato"));

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("contratosAsignados");
        Object obj = JSONValue.parse(puntos);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            //Obtenemos el contrato hijo
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Double contratoHijo = Double.parseDouble((String) jsonObject.get("contratoAsignado"));

            //Creamos el manager y guardamos la informacion.
            AsociacionContratos manager = new AsociacionContratos();
            int error = manager.insertar(contratoPadre, contratoHijo);

            /*
            Obtenemos la respuesta del procedimiento y Validamos si el contrato padre 
            es valido, si no lo es no registramos nada y enviamos el error.
            */
            if (error == 2) {

                guardarErrores(error, contratoPadre);
                escribirJSON(response);

                break;

            } else if (error == 4) { //Si el hijo no es valido, registramos el error y 
                                     //enviamos el listado a la vista al finalizar el for.

                guardarErrores(error, contratoHijo);

            }

        }

        escribirJSON(response);

    } catch (Exception ex) {
        JSONObject respError = new JSONObject();
        respError.put("error", 0);
        arrayErrores.add(respError);
        escribirJSON(response);
    }

}

From source file:control.ParametrizacionServlets.ActualizarAsociacionContratos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w. j av a 2 s .c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        //Obtenemos el numero de contrato
        Double contratoPadre = Double.parseDouble(request.getParameter("contrato"));

        //Obtenemos la cadena con la informacion y la convertimos en un
        //JSONArray
        String puntos = request.getParameter("contratosAsignados");
        Object obj = JSONValue.parse(puntos);
        JSONArray jsonArray = new JSONArray();
        jsonArray = (JSONArray) obj;

        //Recorremos el JSONArray y obtenemos la informacion.
        for (int i = 0; i < jsonArray.size(); i++) {

            //Obtenemos el contrato hijo
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Double contratoHijo = Double.parseDouble((String) jsonObject.get("contratoAsignado"));
            String codigo = (String) jsonObject.get("codigo");

            //Creamos el manager y guardamos la informacion.
            AsociacionContratos manager = new AsociacionContratos();
            int error = manager.actualizar(contratoPadre, contratoHijo, codigo);

            /*
            Obtenemos la respuesta del procedimiento y Validamos si el contrato padre 
            es valido, si no lo es no registramos nada y enviamos el error.
            */
            if (error == 2) {

                guardarErrores(error, contratoPadre);
                escribirJSON(response);

                break;

            } else if (error == 4) { //Si el hijo no es valido, registramos el error y 
                                     //enviamos el listado a la vista al finalizar el for.

                guardarErrores(error, contratoHijo);

            }

        }

        escribirJSON(response);

    } catch (Exception ex) {

        JSONObject respError = new JSONObject();
        respError.put("error", 0);
        arrayErrores.add(respError);
        escribirJSON(response);

    }

}

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

/**
 * Tests processChainJob in happy route// w w  w  . ja v a  2  s  .  c  o  m
 *
 * @throws Exception
 */
@Test
@Category(UnitTest.class)
public void testProcessChainJob() 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");
    mockChild.put("detail", "processing");
    mockChild.put("status", "running");

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

    Mockito.doReturn(Response.ok().build()).when(spy).processJob(Matchers.anyString(),
            Matchers.any(String.class));
    Mockito.doReturn(mockJobStatusManager).when(spy).createJobStatusMananger(Matchers.any(Connection.class));
    Mockito.doReturn(mockChild).when(spy).execReflection(Matchers.anyString(), Matchers.any(JSONObject.class),
            Matchers.any(JobStatusManager.class));

    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", jobStr);

    // sleep for a couple of secs to make sure that all threads spawned by the call to spy.processChainJob() finish
    Thread.sleep(2000);

    class validParam2Matcher extends ArgumentMatcher<JSONObject> {

        @Override
        public boolean matches(Object argument) {
            JSONObject param = (JSONObject) argument;
            boolean val1 = param.get("class").toString()
                    .equals("hoot.services.controllers.ingest.RasterToTilesService");
            boolean val2 = param.get("method").toString().equals("ingestOSMResource");
            boolean val3 = param.get("exectype").toString().equals("reflection");

            JSONArray params = (JSONArray) param.get("params");
            JSONObject innerParam = (JSONObject) params.get(0);
            boolean val4 = innerParam.get("isprimitivetype").toString().equals("false");
            boolean val5 = innerParam.get("value").toString().equals("GroundPhotos");
            boolean val6 = innerParam.get("paramtype").toString().equals("java.lang.String");

            return val1 && val2 && val3 && val4 && val5 && val6;
        }
    }

    Mockito.verify(spy).execReflection(Matchers.matches("test_job_id_1234"),
            Matchers.argThat(new validParam2Matcher()), Matchers.any(JobStatusManager.class));

    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(3)).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());

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

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

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

    ArgumentCaptor<String> setCompleteArgCaptor = ArgumentCaptor.forClass(String.class);

    Mockito.verify(mockJobStatusManager, Mockito.times(1)).setComplete(Matchers.anyString(),
            setCompleteArgCaptor.capture());

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

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

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

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