Example usage for org.json.simple.parser ParseException toString

List of usage examples for org.json.simple.parser ParseException toString

Introduction

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

Prototype

public String toString() 

Source Link

Usage

From source file:Networking.Networking.java

/**
 * Receives data via UDP (calling {@see #recvUDP}) and 
 * parses it to {@code JSONObject}. Gets from this {@code JSONObject}
 * information about time of sending (with key 
 * {@see edu.cvut.vorobvla.bap.BapJSONKeys#KEY_BROADCAST_TIMESTAMP}).
 * If the data is up-to-date (time of sending is greater then
 * {@see #broadcastLatestTimestamp}) sets {@see #broadcastLatestTimestamp}
 * to the time of sending and returns the parsed JSONObject. Otherwise
 * returns {@code null}/*from   w  w  w.j av  a2s  .com*/
 * @return {@code JSONObject} with game info normally, {@code null}
 * if the information is invalid ({@code ParseException occurs}) or not
 * up-to-date.
 */
public JSONObject recvGameInfo() {
    System.out.println("recvGameInfo");
    String str = new String(recvUDP().getData());
    try {
        JSONObject jobj = (JSONObject) parser.parse(str);
        long tstmp = (long) jobj.get(BapJSONKeys.KEY_BROADCAST_TIMESTAMP);
        if (tstmp < broadcastLatestTimestamp) {
            System.out.println("Timestamp ignore");
            return null;
            //ignore info that is not up-to-date
        }
        broadcastLatestTimestamp = tstmp;
        System.out.println(jobj);
        return jobj;
    } catch (ParseException ex) {
        System.out.println("ParseException " + ex.toString());
        return null;
    }
}

From source file:org.restsql.core.impl.serial.JsonRequestDeserializer.java

@Override
public WriteResponse execWrite(HttpRequestAttributes httpAttributes, Type requestType,
        List<RequestValue> resIds, SqlResource sqlResource, String requestBody, RequestLogger requestLogger)
        throws SqlResourceException {
    final Handler handler = new Handler(httpAttributes, requestType, resIds, sqlResource, requestLogger);
    try {/*from w  w  w  .j  a  va 2s  . c om*/
        final JSONParser parser = new JSONParser();
        parser.parse(requestBody, handler);
    } catch (final ParseException exception) {
        throw new InvalidRequestException("Error parsing request body: " + exception.toString());
    }
    final SqlResourceException handlerException = handler.getHandlerException();
    if (handlerException != null) {
        throw handlerException;
    }
    return handler.getWriteResponse();
}

From source file:qhindex.servercomm.ServerDataCache.java

public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) {
    JSONObject obj = new JSONObject();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut)
            .setConnectionRequestTimeout(AppHelper.connectionTimeOut)
            .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    HttpPost httpPost = new HttpPost(url);

    String dataStr = data.toJSONString();
    dataStr = dataStr.replaceAll("null", "\"\"");

    if (sentAdminNotification == true) {
        try {/*w  w  w  . j ava2s.  com*/
            AdminMail adminMail = new AdminMail();
            adminMail.sendMailToAdmin("Data to send to the server.", dataStr);
        } catch (Exception ex) { // Catch any problem during this step and continue 
            Debug.print("Could not send admin notification e-mail: " + ex);
        }
    }
    Debug.print("DATA REQUEST: " + dataStr);
    StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8));
    jsonData.setChunked(true);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(jsonData);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase());
            resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase() + "\n";
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output = new String();
        String line;
        while ((line = br.readLine()) != null) {
            output += line;
        }
        output = output.substring(output.indexOf('{'));
        try {
            obj = (JSONObject) new JSONParser().parse(output);
        } catch (ParseException pEx) {
            Debug.print(
                    "Could not parse internet response. It is possible the cache server fail to deliver the content: "
                            + pEx.toString());
            resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n";
        }
    } catch (IOException ioEx) {
        Debug.print("Could not handle the internet request: " + ioEx.toString());
        resultsMsg += "Could not handle the internet request.\n";
    }
    return obj;
}

From source file:report.Report.java

/**
 * Initialize the IXDocReport struct with the JSON
 * @param jsonText The JSON text.//from  w w  w  .j a  v  a  2  s  .com
 * @throws IOException If the template or output file can't be opened or written.
 * @throws GeneratorException 
 */
private void buildFromJson(String jsonText) throws GeneratorException {
    // Parses the JSON text:
    JSONObject json;
    try {
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(jsonText);
    } catch (ParseException e) {
        throw new GeneratorException(GeneratorError.JSON_ERROR,
                "Error while parsing the JSON file:" + e.toString());
    }

    // Initializes the template file and creates the report object:
    try {
        InputStream in = new FileInputStream(template);
        report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
    } catch (XDocReportException e) {
        throw new GeneratorException(GeneratorError.TEMPLATE_ERROR,
                "Error with the template file:" + e.toString());
    } catch (FileNotFoundException e) {
        throw new GeneratorException(GeneratorError.PARAMETER_ERROR, "Template file does not exists.");
    } catch (IOException e) {
        throw new GeneratorException(GeneratorError.IO_ERROR, "I/O error...");
    }

    // Creates the FieldsMetadata.
    metadata = new FieldsMetadata();

    // Creates the report context:
    try {
        context = report.createContext();
    } catch (XDocReportException e) {
        throw new GeneratorException(GeneratorError.CONTEXT_ERROR,
                "Error while creating the context:" + e.toString());
    }

    Iterator<?> iter = json.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
        BuilderFactory.getBuilder(entry.toString()).build((JSONObject) entry.getValue(), metadata, context);
    }

    // Links the FieldsMetaData to the report.
    report.setFieldsMetadata(metadata);
}

From source file:uk.co.didz.hypersignsbukkit.HyperSignsBukkit.java

/**
 * Attempt to load signs. If the data file doesn't exist, create it.
 *//*from   w ww.j a  v  a  2  s .  co m*/
protected void loadSignsData() {
    log.info("Loading signs:");

    loadedSigns = new HashMap<Location, URL>();

    if (!getDataFolder().exists()) {
        getDataFolder().mkdirs();
    }

    File signsFile = new File(getDataFolder(), "signs.json");
    try {
        if (signsFile.createNewFile() == true) {
            log.info("Created data file signs.json successfully.");
            return;
        }
    } catch (IOException e) {
        log.severe("Unable to create signs.json. Disabling plugin.");
        e.printStackTrace();
        pm.disablePlugin(this);
        return;
    }

    if (signsFile.length() == 0) {
        log.info("No signs loaded. (signs.json is empty)");
        return;
    }

    FileReader fileReader;
    try {
        fileReader = new FileReader(signsFile);
    } catch (FileNotFoundException e) {
        // Shouldn't happen cause the file was created up there ^
        return;
    }

    JSONParser parser = new JSONParser();
    Object array;

    try {
        array = parser.parse(fileReader);
    } catch (ParseException pe) {
        log.severe("Unable to parse signs.json! Disabling plugin.");
        log.severe(pe.toString());
        pm.disablePlugin(this);
        return;
    } catch (IOException e) {
        log.severe("IOException while trying to parse signs.json! Disabling plugin.");
        e.printStackTrace();
        pm.disablePlugin(this);
        return;
    }

    // Ensure that the root element is an array
    JSONArray arr;
    try {
        arr = (JSONArray) array;
    } catch (ClassCastException e) {
        log.severe("Error while loading signs.json, the root element isn't an array! Disabling plugin.");
        e.printStackTrace();
        pm.disablePlugin(this);
        return;
    }

    int blockNum = 0; // For error messages
    for (Object object : arr) {
        JSONObject obj;
        try {
            obj = (JSONObject) object;
        } catch (ClassCastException e) {
            log.warning("Found a non-object in the blocks list while loading signs.json. Skipping.");
            continue;
        }

        blockNum++;

        if (!obj.containsKey("world") || !obj.containsKey("x") || !obj.containsKey("y") || !obj.containsKey("z")
                || !obj.containsKey("url")) {
            log.warning("Missing data for block #" + blockNum + " while loading signs.json. Skipping.");
            continue;
        }

        String worldName, urlString;
        int x, y, z;
        try {
            worldName = (String) obj.get("world");
            x = ((Number) obj.get("x")).intValue();
            y = ((Number) obj.get("y")).intValue();
            z = ((Number) obj.get("z")).intValue();
            urlString = (String) obj.get("url");
        } catch (ClassCastException e) {
            log.warning("Found malformed data for a block while loading signs.json. Skipping.");
            continue;
        }

        assert (worldName != null && urlString != null);

        // Ensure world for this block exists
        World world = getServer().getWorld(worldName);
        if (world == null) {
            log.warning("The world '" + worldName + "' for block #" + blockNum
                    + " doesn't exist on the server. Skipping.");
            continue;
        }

        Location location = new Location(world, x, y, z);

        // Make sure the URL is valid
        URL url = validateURL(urlString);
        if (url == null) {
            log.warning("The URL for block #" + blockNum + "is invalid. Skipping.");
            continue;
        }

        loadedSigns.put(location.clone(), url);
    }

    log.info(loadedSigns.size() + " signs loaded.");
}

From source file:yui.classes.YUILoader.java

private JSONObject _loadJSONConfObject(String configFile) {
    InputStream in = IOUtils.loadResource(configFile);
    Object obj = null;//from w  w  w. ja va2 s. co  m
    if (in == null) {
        throw new RuntimeException(
                "suitable YUI metadata file: [" + this._jsonConfigFile + "]  Could not be found or Loaded");
    }
    // convert inputStream to String
    String j = IOUtils.convertStreamToString(in);
    // convert json String to Java Object
    try {
        logger.debug("Starting to Parse JSON String to Java ");
        obj = parser.parse(j);
        if (obj == null) {
            throw new RuntimeException("Parsing Resulted in null or 0 sized Object, that means configFile "
                    + configFile + "probably is empty");
        }

        if (!(obj instanceof JSONObject)) {
            throw new RuntimeException("parse JSON file resulted in Object other than JSONObject,"
                    + obj.getClass().getName() + " but,this method strictly expects JSONObject ");
        }
        //yui_current = (JSONObject) obj;
        logger.trace("configuration file contains: \n\r  " + obj);

    } catch (ParseException pe) {
        logger.error("position: " + pe.getPosition());
        logger.error(pe.toString());
        throw new RuntimeException("Error Occured while parsing YUI json configuration file position: "
                + pe.getPosition() + " \n stack trace", pe);
    }

    return (JSONObject) obj;
}