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:com.stackmob.example.geopoints.WriteGeo.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    LoggerService logger = serviceProvider.getLoggerService(WriteGeo.class);
    Map<String, SMObject> feedback = new HashMap<String, SMObject>();
    Map<String, String> errMap = new HashMap<String, String>();

    String user = "";
    String latitude = "";
    String longitude = "";

    JSONParser parser = new JSONParser();
    try {/* w  ww .jav a 2s .  c om*/
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;
        user = (String) jsonObject.get("user_name");
        latitude = (String) jsonObject.get("Latitude");
        longitude = (String) jsonObject.get("Longitude");
    } catch (ParseException pe) {
        logger.error(pe.getMessage(), pe);
        return Util.badRequestResponse(errMap, pe.getMessage());
    }

    if (Util.hasNulls(user, latitude, longitude)) {
        return Util.badRequestResponse(errMap, "Please fill in all parameters correctly");
    }

    DataService ds = serviceProvider.getDataService();
    List<SMUpdate> update = new ArrayList<SMUpdate>();
    Map<String, SMValue> geoPoint = new HashMap<String, SMValue>();
    SMObject result;

    try {
        geoPoint.put("lat", new SMDouble(Double.parseDouble(latitude)));
        geoPoint.put("lon", new SMDouble(Double.parseDouble(longitude)));
        update.add(new SMSet("position", new SMObject(geoPoint)));
    } catch (NumberFormatException nfe) {
        logger.error(nfe.getMessage(), nfe);
        return Util.badRequestResponse(errMap, nfe.getMessage());
    }

    try {
        result = ds.updateObject("user", new SMString(user), update);
        feedback.put("Updated object", result);
    } catch (InvalidSchemaException ise) {
        return Util.internalErrorResponse("invalid_schema", ise, errMap); // http 500 - internal server error
    } catch (DatastoreException dse) {
        return Util.internalErrorResponse("datastore_exception", dse, errMap); // http 500 - internal server error
    }

    return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}

From source file:csparql_shim.SocketStream.java

/**
 * start listening on a socket and forwarding to csparql
 * stream in defined windows to allow comparison with cqels
 *///w  ww.j av a  2 s.com
@Override
public void run() {
    ServerSocket ssock = null;
    Socket sock = null;
    try {
        ssock = new ServerSocket(this.port);
        sock = ssock.accept();

        DataInputStream is = new DataInputStream(sock.getInputStream());
        JSONParser parser = new JSONParser();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        int windowcount = 1;

        //loop for streaming in data
        while ((line = reader.readLine()) != null && !stop) {

            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                final RdfQuadruple q = new RdfQuadruple((String) array.get(0), (String) array.get(1),
                        (String) array.get(2), System.currentTimeMillis());
                this.put(q);
                System.out.println("triple sent at: " + System.currentTimeMillis());
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:client.InterfaceJeu.java

/**
 * Creates new form InterfaceJeu/*w ww  .  java 2  s  .co  m*/
 * @param cl
 */
public InterfaceJeu(Client cl) {
    initComponents();
    this.c = cl;
    this.infosJoueurs = new JSONArray();
    this.cartes = new JSONArray();
    this.cartesJouables = new JSONArray();
    parser = new JSONParser();
    this.imgCartes = new ArrayList();
    this.imgCartesPosees = new ArrayList();
    this.cartesSelectionnees = new ArrayList();
    this.cartesJouablesString = new ArrayList();
    this.jButton1.setVisible(false);
    this.jButton2.setVisible(false);
    tourName = "";
    interSession = false;
    DefaultCaret caret = (DefaultCaret) this.txtAreaChatLect.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}

From source file:com.telefonica.fiware.commons.openstack.auth.OpenStackKeystoneV2Test.java

/**
 * Configure test//from w ww .  j a v a2  s  . c  om
 */
@Before
public void setUp() {

    if (serviceCatalogJSON == null) {
        JSONParser parser = new JSONParser();
        Object obj = null;
        try {
            obj = parser.parse(
                    new FileReader(this.getClass().getResource("/service_catalog_apiV2.json").getPath()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        serviceCatalogJSON = JSONObject.fromObject(obj.toString());
    }
}

From source file:org.opencastproject.adminui.endpoint.UsersEndpointTest.java

@Test
public void testGetAllUsers() throws ParseException, IOException {
    InputStream stream = UsersEndpointTest.class.getResourceAsStream("/users.json");
    InputStreamReader reader = new InputStreamReader(stream);
    JSONObject expected = (JSONObject) new JSONParser().parse(reader);

    JSONObject actual = (JSONObject) parser
            .parse(given().log().all().expect().statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON)
                    .body("total", equalTo(4)).body("offset", equalTo(0)).body("limit", equalTo(100))
                    .body("results", hasSize(4)).when().get(rt.host("/users.json")).asString());

    ServiceEndpointTestsUtil.testJSONObjectEquality(expected, actual);
}

From source file:com.unilever.audit.services2.NewUser.java

@POST
@Path("AddUser")
@Produces("application/json")
@Consumes("text/plain")
public String NewUser(String json) throws IOException {
    boolean status = true;
    String error = null;/*w  w w  . j  a v  a2  s.  c om*/
    Map<String, Object> hm = new HashMap<String, Object>();

    JSONObject result = new JSONObject();
    Merchandisers merchandiser;
    try {
        JSONObject user = (JSONObject) new JSONParser().parse(json);

        ////////////check if this user already exist bec w cant check it from internal exception
        hm.put("email", (String) user.get("email"));
        merchandiser = (Merchandisers) merchandisersFacadeREST.findOneByQuery("Merchandisers.checkMerchandiser",
                hm);
        //////////if dont exist 
        if (merchandiser == null) {
            merchandiser = (Merchandisers) merchandisersFacadeREST.findOneByQuery("Merchandisers.findByEmail",
                    hm);
            if (merchandiser != null) {
                merchandiser.setActive("Y");
                merchandiser.setPassword((String) user.get("password"));
                try {
                    merchandisersFacadeREST.edit(merchandiser);
                    status = true;
                    error = "User registered successfully, Congrats :)";
                } catch (TransactionRequiredException ex) {
                    status = false;
                    error = "Can't add merchandiser problem with server";
                } catch (IllegalArgumentException ex) {
                    status = false;
                    error = "Wrong data Please try again";
                }
            } else {
                status = false;
                error = "Your email is not registered in our system, Please contact the system admin.";
            }
        } else {
            status = true;
            error = "You are already active please login directly.";
        }
    } catch (Exception e) {
        Logger.getLogger(NewUser.class.getName()).log(Level.SEVERE, null, e);
    }
    result.put("status", status);
    result.put("error", error);
    System.out.println("----------------" + result.toString());
    return result.toString();
}

From source file:models.GeoModel.java

private ArrayList<Address> search(String places) {
    //parser rhe return JSON
    ArrayList<Address> addresses = new ArrayList<Address>();
    JSONParser parser = new JSONParser();

    String json = this.searh(places);

    try {//from   www  . j a va  2s  .c  om
        JSONObject response = (JSONObject) parser.parse(json);

        JSONObject contentList = (JSONObject) response.get("content");

        for (int i = 0; i < contentList.size(); i++) {
            JSONObject context = (JSONObject) contentList.get(String.valueOf(i));

            JSONObject postage = (JSONObject) context.get("postage");
            String address = (String) context.get("address");
            JSONObject location = (JSONObject) context.get("location");

            Address addr;
            addr = new Address();

            addr.addr = address;
            addr.postcode = postage.get("postcode").toString();
            addr.town = postage.get("town").toString();
            try {
                addr.lat = Double.parseDouble(location.get("lat").toString());
                addr.lng = Double.parseDouble(location.get("lng").toString());
            } catch (NullPointerException err) {
                err.printStackTrace();
            }
            addresses.add(addr);

        }

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

    return addresses;

}

From source file:edu.ucsf.rbvi.CyAnimator.internal.io.LoadSessionListener.java

public void handleEvent(SessionLoadedEvent e) {
    // Reset CyAnimator
    FrameManager.reset();//w w w . j  a v  a2s  .c o  m

    // Get the session
    CySession session = e.getLoadedSession();
    /*
    System.out.println("Session: "+session);
    for (String s: session.getAppFileListMap().keySet()) {
       System.out.println(s+":");
       for (File f: session.getAppFileListMap().get(s)) {
    System.out.println("File: "+f);
       }
    }
    */
    if (!session.getAppFileListMap().containsKey("CyAnimator"))
        return;

    // System.out.println("We have animation information!");

    // Ask the user if they want to load the frames?
    //
    try {
        File frameListFile = session.getAppFileListMap().get("CyAnimator").get(0);
        FileReader reader = new FileReader(frameListFile);
        BufferedReader bReader = new BufferedReader(reader);
        JSONParser parser = new JSONParser();
        Object jsonObject = parser.parse(bReader);

        // For each root network, get the 
        if (jsonObject instanceof JSONArray) {
            for (Object obj : (JSONArray) jsonObject) {
                try {
                    FrameManager.restoreFramesFromSession(registrar, session, (JSONObject) obj);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        bReader.close();
        reader.close();
    } catch (FileNotFoundException fnf) {
        System.out.println("File not found exception: " + fnf.getMessage());
    } catch (IOException ioe) {
        System.out.println("IO exception: " + ioe.getMessage());
    } catch (ParseException pe) {
        System.out.println("Unable to parse JSON file: " + pe.getMessage());
        pe.printStackTrace();
    }

}

From source file:com.emuneee.camerasyncmanager.util.GeocodeHelper.java

public static List<Camera> geocodeCameras(List<Camera> cameras, long sleep) throws Exception {
    List<Camera> geocoded = new ArrayList<Camera>(cameras.size());
    int count = 1;

    // loop through and geocode each camera
    for (Camera camera : cameras) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(sGeocodeUrl).append("?");
        urlBuilder.append(sLatLng).append("=");
        urlBuilder.append(camera.getLatitude()).append(",").append(camera.getLongitude());
        urlBuilder.append("&").append(sSensor);
        sLogger.debug("Geocode URL " + urlBuilder.toString());

        try {/*from ww  w  . j a  v a2s . c  o  m*/
            // retry
            String data = null;
            int retryCount = 0;

            while (data == null && retryCount < sRetryCount) {
                if (retryCount > 0) {
                    sLogger.info("Retrying geocoding");
                }
                data = HttpHelper.getStringDataFromUrl(urlBuilder.toString());
                Thread.sleep(sleep);
                retryCount++;
            }

            if (data == null) {
                sLogger.warn("Unable to geocode the camera, no data returned " + camera);
            } else if (data != null && data.contains("OVER_QUERY_LIMIT")) {
                sLogger.warn("Unable to geocode the camera, query limit exceeded " + camera);
                throw new Exception("Unable to geocode the camera, query limit exceeded");
            } else {
                JSONObject jsonObj = (JSONObject) new JSONParser().parse(data);
                JSONArray resultsArr = (JSONArray) jsonObj.get("results");

                if (resultsArr.size() > 0) {

                    for (int i = 0; i < resultsArr.size(); i++) {
                        JSONObject result = (JSONObject) resultsArr.get(i);

                        // loop through the address components
                        JSONArray addressComponents = (JSONArray) result.get("address_components");
                        for (Object compObj : addressComponents) {
                            JSONObject component = (JSONObject) compObj;
                            String shortName = (String) component.get("short_name");
                            JSONArray types = (JSONArray) component.get("types");

                            // loop through the types
                            for (Object typeObj : types) {
                                String type = (String) typeObj;

                                if (type.equalsIgnoreCase("administrative_area_level_3")) {
                                    camera.setArea(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("locality")) {
                                    camera.setCity(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("administrative_area_level_1")) {
                                    camera.setState(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("country")) {
                                    camera.setCountry(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("postal_code")) {
                                    camera.setZipCode(shortName);
                                    break;
                                }
                            }
                        }

                        if (camera.containsAllRequiredData()) {
                            break;
                        } else {
                            sLogger.info(
                                    "Some required data is missing, moving to the next address component set");
                        }
                    }
                }

                if (camera.containsAllRequiredData()) {
                    geocoded.add(camera);
                    sLogger.info("Camera " + count++ + " of " + cameras.size() + " geocoded");
                    sLogger.debug("Geocoded camera " + camera);
                    sLogger.debug("Sleeping for " + sleep + " milliseconds");
                } else {
                    sLogger.warn(
                            "Some required data is missing and geocoding results have been exhausted for camera: "
                                    + camera);
                }
            }
        } catch (InterruptedException e) {
            sLogger.error("Error geocoding address");
            sLogger.error(e.getMessage());
        } catch (ParseException e) {
            sLogger.error("Error geocoding address");
            sLogger.error(e.getMessage());
        }
    }

    return geocoded;
}

From source file:com.aerospike.load.Parser.java

/**
 * Process column definitions in JSON formated file and create two lists for metadata and bindata and one list for metadataLoader
 * @param file Config file name//from  w w  w.ja  v  a  2 s  . c  o m
 * @param metadataLoader Map of metadata for loader to use, given in config file
 * @param metadataColumnDefs List of column definitions for metadata of bins like key,set 
 * @param binColumnDefs List of column definitions for bins
 * @param params User given parameters
 * @throws ParseException 
 * @throws IOException 
 */
public static boolean processJSONColumnDefinitions(File file, HashMap<String, String> metadataConfigs,
        List<ColumnDefinition> metadataColumnDefs, List<ColumnDefinition> binColumnDefs, Parameters params) {
    boolean processConfig = false;
    if (params.verbose) {
        log.setLevel(Level.DEBUG);
    }
    try {
        // Create parser object
        JSONParser jsonParser = new JSONParser();

        // Read the json config file
        Object obj;
        obj = jsonParser.parse(new FileReader(file));

        JSONObject jobj;
        // Check config file contains metadata for datafile
        if (obj == null) {
            log.error("Empty config File");
            return processConfig;
        } else {
            jobj = (JSONObject) obj;
            log.debug("Config file contents:" + jobj.toJSONString());
        }

        // Get meta data of loader
        // Search for input_type
        if ((obj = getJsonObject(jobj, Constants.VERSION)) != null) {
            metadataConfigs.put(Constants.VERSION, obj.toString());
        } else {
            log.error("\"" + Constants.VERSION + "\"  Key is missing in config file");
            return processConfig;
        }

        if ((obj = getJsonObject(jobj, Constants.INPUT_TYPE)) != null) {

            // Found input_type, check for csv 
            if (obj instanceof String && obj.toString().equals(Constants.CSV_FILE)) {
                // Found csv format
                metadataConfigs.put(Constants.INPUT_TYPE, obj.toString());

                // Search for csv_style
                if ((obj = getJsonObject(jobj, Constants.CSV_STYLE)) != null) {
                    // Found csv_style
                    JSONObject cobj = (JSONObject) obj;

                    // Number_Of_Columns in data file
                    if ((obj = getJsonObject(cobj, Constants.COLUMNS)) != null) {
                        metadataConfigs.put(Constants.COLUMNS, obj.toString());
                    } else {
                        log.error("\"" + Constants.COLUMNS + "\"  Key is missing in config file");
                        return processConfig;
                    }

                    // Delimiter for parsing data file
                    if ((obj = getJsonObject(cobj, Constants.DELIMITER)) != null)
                        metadataConfigs.put(Constants.DELIMITER, obj.toString());

                    // Skip first row of data file if it contains column names
                    if ((obj = getJsonObject(cobj, Constants.IGNORE_FIRST_LINE)) != null)
                        metadataConfigs.put(Constants.IGNORE_FIRST_LINE, obj.toString());

                } else {
                    log.error("\"" + Constants.CSV_STYLE + "\"  Key is missing in config file");
                    return processConfig;
                }
            } else {
                log.error("\"" + obj.toString() + "\"  file format is not supported in config file");
                return processConfig;
            }

        } else {
            log.error("\"" + Constants.INPUT_TYPE + "\"  Key is missing in config file");
            return processConfig;
        }

        // Get metadata of records
        // Get key definition of records
        if ((obj = getJsonObject(jobj, Constants.KEY)) != null) {
            metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.KEY));
        } else {
            log.error("\"" + Constants.KEY + "\"  Key is missing in config file");
            return processConfig;
        }

        // Get set definition of records. Optional because we can get "set" name from user.
        if ((obj = getJsonObject(jobj, Constants.SET)) != null) {
            if (obj instanceof String) {
                metadataColumnDefs.add(new ColumnDefinition(Constants.SET, obj.toString(), true, true, "string",
                        "string", null, -1, -1, null, null));
            } else {
                metadataColumnDefs.add(getColumnDefs((JSONObject) obj, Constants.SET));
            }
        }

        // Get bin column definitions 
        JSONArray binList;
        if ((obj = getJsonObject(jobj, Constants.BINLIST)) != null) {
            // iterator for bins
            binList = (JSONArray) obj;
            Iterator<?> i = binList.iterator();
            // take each bin from the JSON array separately
            while (i.hasNext()) {
                JSONObject binObj = (JSONObject) i.next();
                binColumnDefs.add(getColumnDefs(binObj, Constants.BINLIST));
            }

        } else {
            return processConfig;
        }
        log.info(String.format("Number of columns: %d(metadata) + %d(bins)", (metadataColumnDefs.size()),
                binColumnDefs.size()));
        processConfig = true;
    } catch (IOException ie) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config i/o Error: " + ie.toString());
        if (log.isDebugEnabled()) {
            ie.printStackTrace();
        }
    } catch (ParseException pe) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config parsing Error: " + pe.toString());
        if (log.isDebugEnabled()) {
            pe.printStackTrace();
        }

    } catch (Exception e) {
        log.error("File:" + Utils.getFileName(file.getName()) + " Config unknown Error: " + e.toString());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    }

    return processConfig;
}