Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:me.timothy.ddd.entities.EntityManager.java

public void loadEntities(File file) throws IOException, ParseException {
    logger.printf(Level.INFO, "Loading entities from %s (exists: %b)", file.getCanonicalPath(), file.exists());
    JSONArray jsonArray;//w ww  .j  a  v a  2s. c o m
    try (FileReader fr = new FileReader(file)) {
        JSONParser parser = new JSONParser();
        jsonArray = (JSONArray) parser.parse(fr);
    }

    for (int i = 0; i < jsonArray.size(); i++) {
        EntityInfo ei = new EntityInfo();
        ei.loadFrom((JSONObject) jsonArray.get(i));
        logger.trace(ei.toString());
        entities.add(new Entity(ei));
    }
    logger.printf(Level.INFO, "Successfully loaded %d entities", entities.size());
}

From source file:models.Snack.java

public static ArrayList getsnackList() throws IOException {
    ArrayList<Snack> snackList = new ArrayList();

    try {/*w  ww .j  a  v a2  s.c  om*/

        InputStream input = new URL(url).openStream();
        String genreJson = IOUtils.toString(input);

        JSONParser parser = new JSONParser();

        JSONArray tileJson = (JSONArray) parser.parse(genreJson);

        for (Object object : tileJson) {
            JSONObject aJson = (JSONObject) object;

            long id = (Long) aJson.get("id");
            String name = (String) aJson.get("name");
            boolean opt = (Boolean) aJson.get("optional");
            String loc = (String) aJson.get("purchaseLocations");
            long count = (Long) aJson.get("purchaseCount");
            String date = (String) aJson.get("lastPurchaseDate");
            JSONArray imgSize = (JSONArray) aJson.get("size");
            snackList.add(new Snack(id, name, opt, loc, count, date));

        }

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

    return snackList;
}

From source file:eumetsat.pn.elasticsearch.ElasticsearchFeeder.java

protected void indexDirContent(Path aSrcDir) {
    log.info("Indexing dir content {}", aSrcDir);

    JSONParser parser = new JSONParser();

    YamlNode endpointConfig = this.config.get("endpoint");

    log.info("Endpoint configuration: {}", endpointConfig);

    Settings settings = ImmutableSettings.settingsBuilder()
            .put("cluster.name", endpointConfig.get("cluster.name").asTextValue()).build();

    try (TransportClient client = new TransportClient(settings);) {
        client.addTransportAddress(new InetSocketTransportAddress(endpointConfig.get("host").asTextValue(),
                endpointConfig.get("port").asIntValue()));
        int cpt = 0;
        Collection<File> inputFiles = FileUtils.listFiles(aSrcDir.toFile(), new String[] { "json" }, false);
        log.info("Indexing {} files...", inputFiles.size());

        for (File file : inputFiles) {

            try {
                String jsonStr = FileUtils.readFileToString(file);
                JSONObject jsObj = (JSONObject) parser.parse(jsonStr);

                String index = endpointConfig.get("index").asTextValue();
                String type = endpointConfig.get("type").asTextValue();

                String id = (String) jsObj.get(FILE_IDENTIFIER_PROPERTY);
                log.debug("Adding {} (type: {}) to {}", id, type, index);
                IndexResponse response = client.prepareIndex(index, type, id).setSource(jsObj.toJSONString())
                        .execute().actionGet();

                cpt++;/*  w w  w.  j a v a 2s . c o  m*/

                if (response.isCreated()) {
                    log.trace("Response: {} | version: {}", response.getId(), response.getVersion());
                } else {
                    log.warn("NOT created! ResponseResponse: {}", response.getId());
                }
            } catch (IOException | ParseException e) {
                log.error("Error with json file ", file, e);
            }
        }

        log.info("Indexed {} of {} files.", cpt, inputFiles.size());
    } catch (RuntimeException e) {
        log.error("Error indexing json files.", e);
    }
}

From source file:ch.newscron.newscronjsp.RegistrationUtils.java

public String checkURLValidity(String registrationURL) throws ParseException {
    String encodedPart = registrationURL.split("/")[4];
    String url = Encryption.decode(encodedPart.trim());

    if (url == null) {
        return "<p> Invalid URL </p>";
    }/*w  w  w  .ja  v a2  s . c  o  m*/

    else if (url.equals("")) {
        return "<p> Corrupt URL - invalid data! </p>";
    }

    else { //url is not corrupt - check date validity
        JSONParser parser = new JSONParser();
        JSONObject newobj = (JSONObject) parser.parse(url);
        String val = newobj.get("val").toString();
        return "<p> [URL valid until: " + val + " ]</p>";
    }
}

From source file:com.stratio.deep.aerospike.AerospikeJavaRDDFT.java

/**
 * Imports dataset./*from ww w.  j a v  a  2  s .c  om*/
 *
 * @throws java.io.IOException
 */
private static void dataSetImport() throws IOException, ParseException {
    URL url = Resources.getResource(DATA_SET_NAME);
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(url.getFile()));
    JSONObject jsonObject = (JSONObject) obj;

    String id = (String) jsonObject.get("id");
    JSONObject metadata = (JSONObject) jsonObject.get("metadata");
    JSONArray cantos = (JSONArray) jsonObject.get("cantos");

    Key key = new Key(NAMESPACE_ENTITY, SET_NAME, id);
    Bin binId = new Bin("id", id);
    Bin binMetadata = new Bin("metadata", metadata);
    Bin binCantos = new Bin("cantos", cantos);
    aerospike.put(null, key, binId, binMetadata, binCantos);
    aerospike.createIndex(null, NAMESPACE_ENTITY, SET_NAME, "id_idx", "id", IndexType.STRING);

    Key key2 = new Key(NAMESPACE_CELL, SET_NAME, 3);
    Bin bin_id = new Bin("_id", "3");
    Bin bin_number = new Bin("number", 3);
    Bin bin_text = new Bin("message", "new message test");
    aerospike.put(null, key2, bin_id, bin_number, bin_text);
    aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "num_idx", "number", IndexType.NUMERIC);
    aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "_id_idx", "_id", IndexType.STRING);
}

From source file:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {// w  ww .  j  ava2  s  .c  om
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.UserGroupTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    UserGroupType userGroupType = new UserGroupType();
    JSONParser parser = new JSONParser();

    UserGroup userGroup = prepareData().get(0);
    HttpEntity document = userGroupType.createDocument(userGroup);
    JSONObject userGroupObject = (JSONObject) parser.parse(EntityUtils.toString(document));

    String actual = userGroupObject.get("title").toString();
    String excepted = "Administrator";
    assertEquals("UserGroup value for title key doesn't match to given plain text!", excepted, actual);

    actual = userGroupObject.get("permission").toString();
    excepted = "1";
    assertEquals("UserGroup value for permission key doesn't match to given plain text!", excepted, actual);

    actual = userGroupObject.get("users").toString();
    excepted = "[{\"id\":\"1\"},{\"id\":\"2\"}]";
    assertEquals("UserGroup value for users key doesn't match to given plain text!", excepted, actual);

    userGroup = prepareData().get(1);// w w w.  j a v  a2 s .c o m
    document = userGroupType.createDocument(userGroup);
    userGroupObject = (JSONObject) parser.parse(EntityUtils.toString(document));

    actual = String.valueOf(userGroupObject.get("title"));
    excepted = "Random";
    assertEquals("UserGroup value for title key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userGroupObject.get("permission"));
    excepted = "4";
    assertEquals("UserGroup value for permission key doesn't match to given plain text!", excepted, actual);

    actual = String.valueOf(userGroupObject.get("users"));
    excepted = "[]";
    assertEquals("UserGroup value for users key doesn't match to given plain text!", excepted, actual);
}

From source file:logistify.core.ModuloGoogleApiMatrix.java

public Object[] getDistanciaTiempo(Punto origen, Punto destino) {

    Object enCache[] = this.buscarEnCache(origen, destino);
    if (enCache != null)
        return enCache;
    if (origen.equals(destino)) {
        Object result[] = { origen, destino, 0, 0 };
        cache.add(result);/*w w  w  . j  a  v a2  s.c  om*/
        return result;
    }

    //ARMA URL EN FORMATO VALIDO
    String url = this.armarURL(origen.getDireccion(), destino.getDireccion());

    //OBTIENE EL JSON EN TEXTO PLANO
    String jsonPlano = this.readUrl(url);
    this.contador++;
    //System.out.println("CANT CONSULTAS: "+contador);
    //SE CREA EL PARSER DE JSON Y EMPIEZA A OBTENER DATOS
    JSONParser parser = new JSONParser();

    try {
        //PARSEA EL CODIGO PLANO
        Object obj = parser.parse(jsonPlano);

        //OBTIENE UN OBJETO JSON 
        JSONObject jsonObject = (JSONObject) obj;

        //OBTIENE EL ARRAY DENTRO DEL OBJETO jsonObject, CONTENIDO EN LA VAR DE NOMBRE ROWS DEL JSON jsonObject
        JSONArray rows = (JSONArray) jsonObject.get("rows");

        //OBTIENE EL 1ER ELEMENTO DEL ARRAY rows, UN OBJETO JSON
        JSONObject jsonElemObj = (JSONObject) rows.get(0);

        //OBTIENE EL ARRAY DENTRO DEL OBJETO jsonElemObj, CONTENIDO EN LA VAR DE NOMBRE ELEMENTS DEL JSON
        JSONArray elements = (JSONArray) jsonElemObj.get("elements");

        //OBTIENE EL 1ER ELEMENTO DEL ARRAY elements, UN OBJETO JSON
        JSONObject dataJson = (JSONObject) elements.get(0);

        //OBTIENE EL OBJETO DENTRO DEL OBJETO dataJson, CONTENIDO EN LA VAR DE NOMBRE DISTANCE DEL JSON
        JSONObject distanceObj = (JSONObject) dataJson.get("distance");

        //OBTIENE EL VALOR DENTRO DEL OBJETO distanceObj, CONTENIDO EN LA VAR DE VALUE DEL JSON
        long valueDI = (long) distanceObj.get("value");

        //OBTIENE EL OBJETO DENTRO DEL OBJETO dataJson, CONTENIDO EN LA VAR DE NOMBRE DURATION DEL JSON
        JSONObject durationObj = (JSONObject) dataJson.get("duration");

        //OBTIENE EL VALOR DENTRO DEL OBJETO durationObj, CONTENIDO EN LA VAR DE VALUE DEL JSON
        long valueDU = (long) durationObj.get("value");

        //ASIGNACION DE VALORES OBTENIDOS A VARIABLES
        int distance = (int) valueDI;
        int duration = (int) valueDU;

        //ARMA SEGMENTO CON LOS DATOS OBTENIDOS Y LO DEVUELVE
        Object result[] = { origen, destino, distance, duration };
        cache.add(result);
        return result;

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

    //return new Segmento(origen, destino, 15000, 1520);
}

From source file:edu.vt.vbi.patric.jbrowse.CRResultSet.java

public CRResultSet(String pin, BufferedReader br) {
    pinGenome = pin.replace("fig|", "").split(".peg.[0-9]*")[0];

    try {//from www . j  ava  2 s  .c  o  m
        if (br != null) {
            JSONObject res = (JSONObject) (new JSONParser()).parse(br);

            LOGGER.trace("CompareRegionViewer result: {}", res.toJSONString());

            JSONArray tracks = (JSONArray) res.get(pin);
            genomeNames = new HashSet<>();
            genomeIds = new HashSet<>();
            defaultTracks = new ArrayList<>();
            trackMap = new HashMap<>();

            for (Object track : tracks) {
                JSONObject tr = (JSONObject) track;

                if (((JSONArray) tr.get("features")).size() > 0) {
                    CRTrack crTrk = new CRTrack(tr);
                    trackMap.put(crTrk.getRowID(), crTrk);
                    genomeNames.add(crTrk.getGenomeName());
                    genomeIds.add(crTrk.getGenomeID());
                    if (pinGenome.equals(crTrk.getGenomeID())) {
                        pinStrand = crTrk.findFeature(pin).getStrand();
                    }
                }
            }
        } else {
            LOGGER.error("BufferedReader is null");
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:com.owly.srv.RemoteBasicStatItfImpl.java

public boolean getStatusRemoteServer(String ipSrv, int clientPort) {

    URL url = null;//  ww  w. ja  v  a 2 s  .  c  om
    BufferedReader reader = null;
    StringBuilder stringBuilder;
    JSONObject objJSON = new JSONObject();
    JSONParser objParser = new JSONParser();
    String statusServer = "Enable";

    // Check status of remote server with healthCheck
    logger.debug("Check status of remote server with healthCheck");
    // Url to send to remote server
    // for example :
    // http://135.1.128.127:5000/healthCheck

    String urlToSend = "http://" + ipSrv + ":" + clientPort + "/healthCheck";
    logger.debug("URL for HTTP request :  " + urlToSend);

    HttpURLConnection connection;
    try {

        url = new URL(urlToSend);
        connection = (HttpURLConnection) url.openConnection();

        // just want to do an HTTP GET here
        connection.setRequestMethod("GET");

        // uncomment this if you want to write output to this url
        // connection.setDoOutput(true);

        // give it 2 second to respond
        connection.setReadTimeout(1 * 1000);
        connection.connect();

        // read the output from the server
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }

        logger.debug("Response received : " + stringBuilder.toString());
        // map the response into a JSON object
        objJSON = (JSONObject) objParser.parse(stringBuilder.toString());
        // Check the response of the sever with the previous request
        String resServer = (String) objJSON.get("StatusServer");

        // If we dont receive the correct health checl we will save the
        // disable state in the database
        if (resServer.equals("OK")) {
            statusServer = "Enable";
        } else {
            statusServer = "Disable";
        }

        logger.debug("Status of the Server: " + statusServer);

    } catch (MalformedURLException e1) {
        logger.error("MalformedURLException : " + e1.getMessage());
        logger.error("Exception ::", e1);
        statusServer = "Disable";
        logger.debug("Status of the Server: " + statusServer);

    } catch (IOException e1) {
        logger.error("IOException : " + e1.toString());
        logger.error("Exception ::", e1);
        e1.printStackTrace();
        statusServer = "Disable";
        logger.debug("Status of the Server: " + statusServer);

    } catch (ParseException e1) {
        logger.error("ParseException : " + e1.toString());
        logger.error("Exception ::", e1);
        statusServer = "Disable";
        logger.debug("Status of the Server: " + statusServer);

    } finally {
        logger.debug("Save Status of Server in Database: " + statusServer);

    }

    if (statusServer.equals("Enable")) {
        return true;
    } else {
        return false;
    }

}