Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

In this page you can find the example usage for org.json JSONObject keys.

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.visionspace.jenkins.vstart.plugin.VSPluginHtmlWriter.java

public boolean doHtmlReport(AbstractBuild build, JSONArray jArrayReport) {

    try {/*from  w w w.  j  a va  2 s  . c om*/
        if (jArrayReport == null) {
            return false;
        }

        FilePath hPath = new FilePath(build.getWorkspace(), build.getWorkspace() + "/VSTART_HTML");
        if (!hPath.exists()) {
            hPath.mkdirs();
        }

        //Create file on workspace
        File htmlReportFile = new File(
                build.getWorkspace() + "/VSTART_HTML" + "/VSTART_REPORT_" + build.getNumber() + ".html");

        if (!htmlReportFile.createNewFile()) {
            return false;
        }

        //append on file with fileWriter
        FileWriter fileWriter = new FileWriter(htmlReportFile, true);
        BufferedWriter wp = new BufferedWriter(fileWriter);

        StringBuilder builder = new StringBuilder();

        //Begin document
        builder.append("<!DOCTYPE html>").append("\n");
        builder.append("<html>").append("\n");
        //Head
        builder.append("<head> " + "<meta charset='utf-8'>"
                + "<meta name='viewport' content='width=device-width, initial-scale=1'> "
                + "<link rel='stylesheet' href='" + Jenkins.getInstance().getRootUrl()
                + "/plugin/Vstart-Plugin/theme.min.css'>"
                + "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>"
                + "<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>"
                + "<style type='text/css'>" + ".center {" + "margin: auto;" + "width: 60%;" + "border:0px;"
                + "padding: 10px;" + "}" + "h3{" + "font-family: inherit;" + "color: #1faf8e;"
                + "line-height: 1.1;" + "}" + ".FAILED{" + "color: red;" + "}  " + ".PASSED{"
                + "color: #8ac007;" + "}" + "a#btn1 {" + "margin-top : 10px;" + "border: none;" + "}"
                + "</style>  " + "<title>VSTART Report #" + build.getNumber() + "</title>" + "</head>")
                .append("\n");

        //Body
        builder.append("<body>\n").append("\n");
        //Button
        builder.append("<div class=\"container-fluid\">\n").append("\n");
        builder.append("<div class='row'>\n").append("\n");
        builder.append("<div class='col-md-3'>\n").append("\n");
        builder.append("<a class=\"btn btn-primary\" href='" + build.getProject().getAbsoluteUrl()
                + "' id=\"btn1\">Back to Project</a>" + "</div>" + "</div>" + "</div>").append("\n");
        //Structure
        builder.append("<div class=\"container-fluid\">\n").append("\n");
        builder.append("<div class='row'>\n").append("\n");
        //Main column
        builder.append(
                "<div class='col-md-9'style=\"\n" + "    border-right: lightgray dashed 1px;\n" + "\">\n")
                .append("\n");

        //Header
        builder.append("<div class=\"container-fluid\">\n").append("\n");
        builder.append("<h1>VSTART Report #" + build.getNumber() + "</h1>").append("\n");
        //            builder.append("<p class='lead'>Started:" + build + "</p>").append("\n");
        builder.append("<p class='lead'>Duration:" + build.getDurationString() + "</p>").append("\n");
        builder.append("</div>\n").append("\n");

        boolean isFirstTime = true; //Control graph ids to communicate with javascript

        for (int i = 0; i < jArrayReport.length(); i++) {
            //get testcase jsonobject report
            JSONObject jsonReport = jArrayReport.getJSONObject(i);

            builder.append("        <div class=\"container-fluid\">\n" + "            <h2" + " id=\"testcase"
                    + i + "\">" + "Test Case - " + jsonReport.getString("testCaseName") + "</h2>").append("\n");

            //Graph
            Random rand = new Random();
            int id = rand.nextInt(1000) + 1;

            builder.append("<div class= 'row'>" + "<div class='col-md-12'>"
                    + "<div class='panel panel-default'>"
                    + "<div class='panel-heading'> Test Case Execution Graph </div>"
                    + "<div class='panel-body'>" + "                <div id='graph" + id
                    + "' style='/*display: block;*/ width: 100%; height: 600px;' class='center-block'></div>\n"
                    + "            </div>            \n" + "            </div>            \n"
                    + "            </div>            \n" + "            </div>            \n"
                    + "            </div>            \n").append("\n");
            builder.append("            <script type='text/javascript'>").append("\n");

            //if this is the first testcase, the object array must be initialized
            if (isFirstTime) {
                //create object
                builder.append("obj = {}").append("\n");
                //insert key and value
                builder.append("obj.graph" + id + " = "
                        + new JSONObject(jsonReport.getString("extendedGraph")).toString()).append("\n");
                //create array
                builder.append("var arr = []").append("\n");
                //push to array
                builder.append("arr.push(obj)").append("\n");
                //invert variable
                isFirstTime = false;
            } else {
                //create object
                builder.append("obj = {}").append("\n");
                //insert key and value
                builder.append("obj.graph" + id + " = "
                        + new JSONObject(jsonReport.getString("extendedGraph")).toString() + ";").append("\n");
                //push to array
                builder.append("arr.push(obj);").append("\n");
            }
            //            builder.append("var graphId =").append(Integer.toString(id)).append(";").append("\n");
            //            builder.append("data=").append(new JSONObject(jsonReport.getString("extendedGraph")).toString()).append("\n");
            builder.append("pathPrefix=").append(" '" + Jenkins.getInstance().getRootUrl()).append("' \n");
            builder.append("</script>\n"
                    + "            <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/cytoscape/2.4.6/cytoscape.js'></script>\n"
                    + "            <script type='text/javascript' src='" + Jenkins.getInstance().getRootUrl()
                    + "/plugin/Vstart-Plugin/dagre.js'></script>\n"
                    + "            <script type='text/javascript' src='" + Jenkins.getInstance().getRootUrl()
                    + "/plugin/Vstart-Plugin/DesignGraph.js'></script>\n"
                    + "            <script type='text/javascript' src='" + Jenkins.getInstance().getRootUrl()
                    + "/plugin/Vstart-Plugin/app.js'></script>").append("\n");

            //end of Graph
            //Table
            builder.append("<div class=\"container-fluid\">\n").append("\n");
            builder.append("<div class=\"row\">\n").append("\n");
            JSONArray jSteps = jsonReport.getJSONArray("steps");
            for (int j = 0; j < jSteps.length(); j++) {
                JSONObject json = jSteps.getJSONObject(j);

                builder.append("                <div class='col-lg-6 col-md-12'>\n"
                        + "                    <div class=\"panel panel-default\">\n"
                        + "                        <div class='panel-heading' style='overflow: auto;'> ")
                        .append("\n");
                builder.append("<h3 " + "id='step" + i + j + "'>" + "Step #" + j + " : "
                        + json.getString("scriptName").toString() + "</h3>" + "</div>").append("\n");
                builder.append("<table class='table'> \n" + "                            <tbody>").append("\n");

                //Script Language
                builder.append("<tr> \n"
                        + "                                    <td class='field-names'>Language: </td>" + "<td>"
                        + json.getString("scriptLanguage").toString() + "</td>\n</tr>").append("\n");

                //Test case status
                if (json.getString("status").equals("PASSED")) {
                    builder.append("                                <tr> \n"
                            + "                                    <td class='field-names'>Status: </td>\n"
                            + "                                    <td class='PASSED'>PASSED</td>\n"
                            + "                                </tr>").append("\n");
                } else if (json.getString("status").equals("FAILED")) {
                    builder.append("<tr> \n"
                            + "                                    <td class='field-names'>Status: </td>\n"
                            + "                                    <td class='FAILED'>FAILED</td>\n"
                            + "                                </tr>").append("\n");
                }

                //Script source code
                builder.append("<tr> \n"
                        + "                                    <td class='field-names'> Source: </td>")
                        .append("\n");
                builder.append("                                    <td> \n"
                        + "                                        <pre>" + json.getString("scriptSource")
                        + "</pre> \n" + "                                    </td> \n"
                        + "                                </tr>").append("\n");

                //Expected Return Value
                builder.append("<tr> \n"
                        + "                                    <td class='field-names'>Return Value (Expected): </td>")
                        .append("\n");
                builder.append(
                        "                                    <td>" + json.getString("expectedValue").toString()
                                + "</td>" + "                                </tr>")
                        .append("\n");

                //Print parameters table
                JSONObject jParam = json.getJSONObject("scriptParameters"); //Parameters JSONObject for iteration
                Iterator<?> keys = jParam.keys();

                builder.append("                                    <td class='field-names'>Parameters: </td>\n"
                        + "                                    <td>\n"
                        + "                                        <table class='table table-striped'>\n"
                        + "                                            <tbody>").append("\n");
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    if (jParam.get(key) instanceof String) {
                        builder.append("<tr>").append("\n");
                        builder.append("<td class='field-names'>").append("\n");
                        builder.append(key.toString()).append("</td>").append("\n");
                        builder.append("<td>").append("\n");
                        builder.append(jParam.get(key).toString()).append("</td>").append("\n");
                        builder.append("</tr>").append("\n");
                    }
                }
                builder.append("</tbody> \n </table> \n </td>").append("\n");

                //Script Output
                builder.append("                                <tr>\n"
                        + "                                    <td class="
                        + "'field-names'>Script Output: </td>").append("\n");
                builder.append("<td><pre>" + json.getString("scriptOutput").toString() + "</pre>" + "</tr>\n")
                        .append("\n");

                //Actual return value
                builder.append("                                <tr>\n"
                        + "                                    <td class='field-names'>Return Value (Actual): </td>"
                        + "                                    <td>"
                        + json.getString("returnedValue").toString() + "</td>"
                        + "                                </tr>").append("\n");

                //Close element
                builder.append("                            </tbody> \n" + "                        </table> \n"
                        + "                    </div>\n" + "                </div>").append("\n");

            }
            builder.append("            </div>\n").append("\n");
            builder.append("            </div>\n").append("\n");

            //add testbed panel
            builder.append("<div class=\"container-fluid\">\n").append("\n");
            builder.append("<div class=\"row\">\n").append("\n");
            builder.append("<div class=\"col-md-12\">\n").append("\n");
            builder.append("<div class='panel panel-default'>").append("");
            builder.append("<div class='panel-heading' id='testbed" + i + "'> TESTBED </div>").append("\n");
            builder.append("<table class='table table-hover table-striped machines'>").append("\n");
            builder.append("<thead>").append("\n");
            builder.append("<tr class='step-headers'>").append("\n");
            builder.append("<th>Machine</th>").append("\n");
            builder.append("<th>Label</th>").append("\n");
            builder.append("</tr>").append("\n");
            builder.append("<tbody>").append("\n");

            //Loop through JSONObject
            JSONObject jTestBed = jsonReport.getJSONObject("testBed");
            Iterator<?> testKeys = jTestBed.keys();

            while (testKeys.hasNext()) {
                String key = (String) testKeys.next();
                if (jTestBed.get(key) instanceof String) {
                    builder.append("<tr>").append("\n");
                    builder.append("<td>").append("\n");
                    builder.append(key).append("</td>").append("\n");
                    builder.append("<td>").append("\n");
                    builder.append(jTestBed.get(key).toString()).append("</td>").append("\n");
                    builder.append("</tr>").append("\n");
                }
            }
            builder.append("</tbody>").append("\n");
            builder.append("</table>").append("\n");
            builder.append("</div>").append("\n");
            builder.append("</div>").append("\n");
            builder.append("</div>").append("\n");
            builder.append("</div>").append("\n");

        }

        builder.append("</div>").append("\n");

        builder.append("<div class='col-md-3'>").append("\n");
        builder.append("<nav class='sidebar hidden-xs hidden-print hidden-sm affix'>").append("\n");
        //links to testcase information
        builder.append("<h4>VSTART Report #" + build.getNumber() + "</h4>");
        builder.append("<ul>").append("\n");
        for (int c = 0; c < jArrayReport.length(); c++) {
            JSONObject jsonReport = jArrayReport.getJSONObject(c);
            builder.append("<li>").append("\n");
            builder.append("<a href='#testcase" + c + "'>").append("\n");
            builder.append("<b>").append("\n");
            builder.append("Test Case: " + jsonReport.getString("testCaseName")).append("\n");
            builder.append("</b>").append("\n");
            builder.append("</a>").append("\n");

            //Steps
            builder.append("<ul>").append("\n");
            JSONArray jArray = jsonReport.getJSONArray("steps");
            for (int d = 0; d < jArray.length(); d++) {
                builder.append("<li>").append("\n");
                builder.append("<a href='#step" + c + d + "'>").append("\n");
                builder.append("Step #" + d + ":" + jArray.getJSONObject(d).getString("scriptName"))
                        .append("\n");
                builder.append("</a>").append("\n");
                builder.append("</li>").append("\n");
            }

            //testbed
            builder.append("<li>").append("\n");
            builder.append("<a href='#testbed" + c + "'>").append("\n");
            builder.append("Testbed").append("\n");
            builder.append("</a>").append("\n");
            builder.append("</li>").append("\n");

            builder.append("</ul>").append("\n");
            builder.append("</li>").append("\n");
        }

        builder.append("<li>").append("\n");
        builder.append("<a href=\"" + build.getProject().getAbsoluteUrl() + "\"> Back to Project </a></li>")
                .append("\n");

        builder.append("                        </ul>").append("\n");
        builder.append("                    </nav>").append("\n");
        builder.append("                </div>").append("\n");

        //Finish document
        builder.append("            </div>\n" + "        </div>\n" + "\n" + "    </body>\n" + "</html>")
                .append("\n");

        //Print to html file on project's workspace
        wp.write(builder.toString());

        wp.close();
        return true;
    } catch (IOException ex) {
        Logger.getLogger(VSPluginHtmlWriter.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginHtmlWriter.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:com.hichinaschool.flashcards.libanki.Tags.java

public void load(String json) {
    try {//from   w  ww. j a v a2  s . c  o  m
        JSONObject tags = new JSONObject(json);
        Iterator i = tags.keys();
        while (i.hasNext()) {
            String t = (String) i.next();
            mTags.put(t, tags.getInt(t));
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mChanged = false;
}

From source file:com.csipsimple.service.DownloadLibService.java

private boolean isCompatibleStack(JSONObject filter) throws SecurityException, NoSuchFieldException,
        ClassNotFoundException, IllegalArgumentException, IllegalAccessException, JSONException {

    //For each filter keys, we check if the filter is not invalid
    Iterator<?> iter = filter.keys();
    while (iter.hasNext()) {
        //Each filter key correspond to a android class which values has to be checked
        String class_filter = (String) iter.next();
        //Get this class
        Class<?> cls = Class.forName(class_filter);

        //Then for this class, we have to check if each static field matches defined regexp rule
        Iterator<?> cls_iter = filter.getJSONObject(class_filter).keys();

        while (cls_iter.hasNext()) {
            String field_name = (String) cls_iter.next();
            Field field = cls.getField(field_name);
            //Get the current value on the system
            String current_value = field.get(null).toString();
            //Get the filter for this value
            String regexp_filter = filter.getJSONObject(class_filter).getString(field_name);

            //Check if matches
            if (!Pattern.matches(regexp_filter, current_value)) {
                Log.d(THIS_FILE, "Regexp not match : " + current_value + " matches /" + regexp_filter + "/");
                return false;
            }/*from   w w w .  j  a  va2 s.c o  m*/
        }
    }
    return true;
}

From source file:org.lafs.hdfs.LAFS.java

@SuppressWarnings("unchecked")
@Override//from ww  w  . j a  v  a  2 s .co  m
public FileStatus[] listStatus(Path path) throws IOException {
    FileStatus[] ret = null;

    JSONArray ja = getJSONForPath(path);

    try {
        String flag = ja.getString(0);
        boolean isDir = flag.equals("dirnode");

        if (isDir) { // process directory
            String pathString = path.toString();
            if (!pathString.endsWith("/"))
                pathString = pathString + "/";

            JSONObject data = ja.getJSONObject(1);

            // get the status of each child
            ArrayList<FileStatus> stats = new ArrayList<>();
            JSONObject children = data.getJSONObject("children");
            Iterator<String> items = children.keys();
            while (items.hasNext()) {
                String name = items.next();

                FileStatus stat = getStatusFromJSON(children.getJSONArray(name), new Path(pathString + name));
                stats.add(stat);
            }

            ret = new FileStatus[stats.size()];
            ret = stats.toArray(ret);
        } else { // process a file   
            FileStatus stat = getStatusFromJSON(ja, path);
            ret = new FileStatus[1];
            ret[0] = stat;
        }

    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }

    return ret;
}

From source file:siminov.web.reader.WebSiminovDataReader.java

private WebSiminovData parseData(JSONObject data) throws SiminovException {

    if (data == null) {
        return null;
    }/* ww  w  . ja v a  2 s  .  c o  m*/

    String dataType = null;
    String dataValue = null;
    JSONArray values = null;
    JSONArray innerDatas = null;

    Iterator<String> keys = data.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_JSON_TYPE)) {
            dataType = (String) getValue(key, data);
        } else if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_JSON_CDATA_SECTION)
                || key.equalsIgnoreCase(WEB_SIMINOV_DATA_JSON_TEXT)) {
            dataValue = (String) getValue(key, data);
        } else if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_VALUE)) {

            try {
                values = data.getJSONArray(WEB_SIMINOV_DATA_VALUE);
            } catch (Exception exception) {
                Log.error(WebSiminovDataReader.class.getName(), "parseData",
                        "Exception caught while getting values array, " + exception.getMessage());
                throw new SiminovException(WebSiminovDataReader.class.getName(), "parseData",
                        "Exception caught while getting values array, " + exception.getMessage());
            }
        } else if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_DATA)) {

            try {
                innerDatas = data.getJSONArray(WEB_SIMINOV_DATA_DATA);
            } catch (Exception exception) {
                Log.error(WebSiminovDataReader.class.getName(), "parseData",
                        "Exception caught while getting datas array, " + exception.getMessage());
                throw new SiminovException(WebSiminovDataReader.class.getName(), "parseData",
                        "Exception caught while getting datas array, " + exception.getMessage());
            }
        }
    }

    WebSiminovData webSiminovData = new WebSiminovData();
    webSiminovData.setDataType(dataType);
    webSiminovData.setDataValue(dataValue);

    parseDataValue(webSiminovData, values);

    try {
        if (innerDatas != null && innerDatas.length() > 0) {
            for (int i = 0; i < innerDatas.length(); i++) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = innerDatas.getJSONObject(i);
                } catch (Exception exception) {
                    Log.error(WebSiminovDataReader.class.getName(), "parseData",
                            "Exception caught while geeting json object from datas, " + exception.getMessage());
                    throw new SiminovException(WebSiminovDataReader.class.getName(), "parseData",
                            "Exception caught while geeting json object from datas, " + exception.getMessage());
                }

                WebSiminovData webData = parseData(jsonObject);
                webSiminovData.addData(webData);
            }
        }
    } catch (SiminovException siminovException) {
        Log.error(WebSiminovDataReader.class.getName(), "parseData",
                "Exception caught while parsing data tag, " + siminovException.getMessage());
        throw siminovException;
    }

    return webSiminovData;
}

From source file:siminov.web.reader.WebSiminovDataReader.java

private void parseDataValue(WebSiminovData webSiminovData, JSONArray values) throws SiminovException {

    if (values == null || values.length() <= 0) {
        return;//from  ww  w .  j  a  v a  2  s.  c  o m
    }

    for (int i = 0; i < values.length(); i++) {

        JSONObject jsonObject = null;
        try {
            jsonObject = values.getJSONObject(i);
        } catch (Exception exception) {
            Log.error(WebSiminovDataReader.class.getName(), "parseData",
                    "Exception caught while geeting json object from values, " + exception.getMessage());
            throw new SiminovException(WebSiminovDataReader.class.getName(), "parseData",
                    "Exception caught while geeting json object from values, " + exception.getMessage());
        }

        String valueType = null;
        String value = null;

        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_JSON_TYPE)) {
                valueType = (String) getValue(key, jsonObject);
            } else if (key.equalsIgnoreCase(WEB_SIMINOV_DATA_JSON_TEXT)) {
                value = (String) getValue(key, jsonObject);
            }
        }

        WebSiminovValue webSiminovValue = new WebSiminovValue();
        webSiminovValue.setType(valueType);
        webSiminovValue.setValue(value);

        webSiminovData.addValue(webSiminovValue);

    }

}

From source file:com.google.enterprise.connector.ldap.JsonDocument.java

@SuppressWarnings("unchecked")
private static Iterator<String> getKeys(JSONObject jo) {
    return jo.keys();
}

From source file:cc.redpen.server.api.RedPenResource.java

/**
 * Validate a request encoded in JSON. Valid properties are:
 * <p>//  w  w  w.j  a v a  2  s. co m
 * document : the source text of the document
 * documentParser : specifies one of PLAIN, WIKI, or MARKDOWN
 * lang : the source document language (en, ja, etc)
 * format : the format of the results, eg: json, json2, plain etc
 * config : the redpen validator configuration
 *
 * @param requestJSON the request, in JSON
 * @return redpen validation errors
 * @throws RedPenException when failed to validate the json
 */
@Path("/validate/json")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
@WinkAPIDescriber.Description("Process a redpen JSON validation request and returns any redpen errors")
public Response validateDocumentJSON(JSONObject requestJSON) throws RedPenException {

    LOG.info("Validating document using JSON request");
    String documentParser = getOrDefault(requestJSON, "documentParser", DEFAULT_DOCUMENT_PARSER);
    String documentText = getOrDefault(requestJSON, "document", "");
    String format = getOrDefault(requestJSON, "format", DEFAULT_FORMAT);

    String lang = DEFAULT_LANG;

    Map<String, Map<String, String>> properties = new HashMap<>();
    JSONObject config = null;
    if (requestJSON.has("config")) {
        try {
            config = requestJSON.getJSONObject("config");
            lang = getOrDefault(config, "lang", DEFAULT_LANG);
            if (config.has("validators")) {
                JSONObject validators = config.getJSONObject("validators");
                Iterator keyIter = validators.keys();
                while (keyIter.hasNext()) {
                    String validator = String.valueOf(keyIter.next());
                    Map<String, String> props = new HashMap<>();
                    properties.put(validator, props);
                    JSONObject validatorConfig = validators.getJSONObject(validator);
                    if ((validatorConfig != null) && validatorConfig.has("properties")) {
                        JSONObject validatorProps = validatorConfig.getJSONObject("properties");
                        Iterator propsIter = validatorProps.keys();
                        while (propsIter.hasNext()) {
                            String propname = String.valueOf(propsIter.next());
                            props.put(propname, validatorProps.getString(propname));
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("Exception when processing JSON properties", e);
        }
    }

    RedPen redPen = new RedPenService(context).getRedPen(lang, properties);

    // override any symbols
    if ((config != null) && config.has("symbols")) {
        try {
            JSONObject symbols = config.getJSONObject("symbols");
            Iterator keyIter = symbols.keys();
            while (keyIter.hasNext()) {
                String symbolName = String.valueOf(keyIter.next());
                try {
                    SymbolType symbolType = SymbolType.valueOf(symbolName);
                    JSONObject symbolConfig = symbols.getJSONObject(symbolName);
                    Symbol originalSymbol = redPen.getConfiguration().getSymbolTable().getSymbol(symbolType);
                    if ((originalSymbol != null) && (symbolConfig != null) && symbolConfig.has("value")) {
                        String value = symbolConfig.has("value") ? symbolConfig.getString("value")
                                : String.valueOf(originalSymbol.getValue());
                        boolean spaceBefore = symbolConfig.has("before_space")
                                ? symbolConfig.getBoolean("before_space")
                                : originalSymbol.isNeedBeforeSpace();
                        boolean spaceAfter = symbolConfig.has("after_space")
                                ? symbolConfig.getBoolean("after_space")
                                : originalSymbol.isNeedAfterSpace();
                        String invalidChars = symbolConfig.has("invalid_chars")
                                ? symbolConfig.getString("invalid_chars")
                                : String.valueOf(originalSymbol.getInvalidChars());
                        if ((value != null) && !value.isEmpty()) {
                            redPen.getConfiguration().getSymbolTable().overrideSymbol(new Symbol(symbolType,
                                    value.charAt(0), invalidChars, spaceBefore, spaceAfter));
                        }
                    }

                } catch (IllegalArgumentException iae) {
                    LOG.error("Ignoring unknown SymbolType " + symbolName);
                }
            }
        } catch (Exception e) {
            LOG.error("Exception when processing JSON symbol overrides", e);
        }
    }
    Document parsedDocument = redPen.parse(DocumentParser.of(documentParser), documentText);

    List<ValidationError> errors = redPen.validate(parsedDocument);

    Formatter formatter = FormatterUtils.getFormatterByName(format);

    if (formatter == null) {
        throw new RedPenException(
                "Unsupported format: " + format + " - please use xml, plain, plain2, json or json2");
    }

    return responseTyped(formatter.format(parsedDocument, errors), format);
}

From source file:org.openqa.selendroid.server.inspector.view.InspectorView.java

private String displayCapabilities() throws JSONException {
    if (driver.getSession() != null) {
        StringBuffer capabilities = new StringBuffer();
        JSONObject capa = driver.getSession().getCapabilities();
        if (capa == null) {
            return "No capabilities available.";
        }//  w w  w. j a  v  a2 s.  c  o m

        for (Iterator<String> keyIter = capa.keys(); keyIter.hasNext();) {
            String key = keyIter.next();
            capabilities.append("<p><b>" + key + "</b>: " + capa.get(key) + "</p>");
        }
        return capabilities.toString();
    }
    return "No capabilities available. Model = null";
}

From source file:org.qi4j.library.shiro.web.servlet.Qi4jShiroServletFilter.java

private void applyFilterChain(Application application) throws JSONException {

    String filterChainsConfig = getFilterConfig().getInitParameter(FILTER_CHAINS_PARAM);
    NullArgumentException.validateNotEmpty(FILTER_CHAINS_PARAM, filterChainsConfig);

    JSONObject filterChainsJson = new JSONObject(filterChainsConfig);

    Ini ini = new Ini();
    Section urls = ini.addSection("urls");
    Iterator it = filterChainsJson.keys();
    while (it.hasNext()) {
        String eachUrl = (String) it.next();
        urls.put(eachUrl, (String) filterChainsJson.get(eachUrl));
    }/*from ww  w  .  j  a  va  2s.c  o m*/

    Section filters = ini.addSection("filters");
    filters.put("authcBasic.applicationName", application.name());
    filters.put("authcX509", X509AuthenticationFilter.class.getName());

    IniFilterChainResolverFactory filterChainResolverFactory = new IniFilterChainResolverFactory(ini);
    filterChainResolverFactory.setFilterConfig(getFilterConfig());
    setFilterChainResolver(filterChainResolverFactory.getInstance());
}