List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:nl.hnogames.domoticzapi.Parsers.UpdateDownloadReadyParser.java
@SuppressWarnings("SpellCheckingInspection") @Override/* w ww . j a v a2 s . c o m*/ public void parseResult(String result) { try { JSONObject response = new JSONObject(result); boolean updateDownloadUpdateReady; if (response.has("downloadok")) updateDownloadUpdateReady = response.getBoolean("downloadok"); else updateDownloadUpdateReady = false; receiver.onUpdateDownloadReady(updateDownloadUpdateReady); } catch (JSONException error) { receiver.onError(error); error.printStackTrace(); } }
From source file:ch.unine.vauchers.fuseerasure.codes.Codec.java
public Codec(JSONObject json) throws JSONException { this.json = json; this.id = json.getString("id"); this.parityLength = json.getInt("parity_length"); this.stripeLength = json.getInt("stripe_length"); this.erasureCodeClass = json.getString("erasure_code"); this.parityDirectory = json.getString("parity_dir"); this.priority = json.getInt("priority"); this.description = getJSONString(json, "description", ""); this.isDirRaid = Boolean.parseBoolean(getJSONString(json, "dir_raid", "false")); this.tmpParityDirectory = getJSONString(json, "tmp_parity_dir", "/tmp" + this.parityDirectory); this.tmpHarDirectory = getJSONString(json, "tmp_har_dir", "/tmp" + this.parityDirectory + "_har"); this.simulateBlockFix = json.getBoolean("simulate_block_fix"); checkDirectory(parityDirectory);//from w w w .j a v a 2 s . c o m checkDirectory(tmpParityDirectory); checkDirectory(tmpHarDirectory); }
From source file:org.vufind.MaterialsRequest.java
/** * If a title has been added to the catalog, add *///w w w .j av a 2s . com private void generateHolds() { processLog.addNote("Generating holds for materials requests that have arrived"); //Get a list of requests to generate holds for try { PreparedStatement requestsToEmailStmt = vufindConn.prepareStatement( "SELECT materials_request.*, cat_username, cat_password FROM materials_request inner join user on user.id = materials_request.createdBy WHERE placeHoldWhenAvailable = 1 and holdsCreated = 0 and status IN ('owned', 'purchased')"); PreparedStatement setHoldsCreatedStmt = vufindConn .prepareStatement("UPDATE materials_request SET holdsCreated=1 where id =?"); ResultSet requestsToCreateHolds = requestsToEmailStmt.executeQuery(); //For each request, while (requestsToCreateHolds.next()) { boolean holdCreated = false; //Check to see if the title has been received based on the ISBN or OCLC Number String requestId = requestsToCreateHolds.getString("id"); String requestIsbn = requestsToCreateHolds.getString("isbn"); String requestIssn = requestsToCreateHolds.getString("issn"); String requestUpc = requestsToCreateHolds.getString("upc"); String requestOclcNumber = requestsToCreateHolds.getString("oclcNumber"); String holdPickupLocation = requestsToCreateHolds.getString("holdPickupLocation"); String cat_username = requestsToCreateHolds.getString("cat_username"); String cat_password = requestsToCreateHolds.getString("cat_password"); String recordId = null; //Search for the isbn if ((requestIsbn != null && requestIsbn.length() > 0) || (requestIssn != null && requestIssn.length() > 0) || (requestUpc != null && requestUpc.length() > 0) || (requestOclcNumber != null && requestOclcNumber.length() > 0)) { URL searchUrl; if (requestIsbn != null && requestIsbn.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIsbn + "&type=isn"); } else if (requestIssn != null && requestIssn.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIssn + "&type=isn"); } else if (requestUpc != null && requestUpc.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestUpc + "&type=isn"); } else { searchUrl = new URL(vufindUrl + "/API/SearchAPI?method=search&lookfor=oclc" + requestOclcNumber + "&type=allfields"); } Object searchDataRaw = searchUrl.getContent(); if (searchDataRaw instanceof InputStream) { String searchDataJson = Util.convertStreamToString((InputStream) searchDataRaw); try { JSONObject searchData = new JSONObject(searchDataJson); JSONObject result = searchData.getJSONObject("result"); if (result.getInt("recordCount") > 0) { //Found a record JSONArray recordSet = result.getJSONArray("recordSet"); JSONObject firstRecord = recordSet.getJSONObject(0); recordId = firstRecord.getString("id"); } } catch (JSONException e) { logger.error("Unable to load search result", e); processLog.incErrors(); processLog.addNote("Unable to load search result " + e.toString()); } } else { logger.error("Error searching for isbn " + requestIsbn); processLog.incErrors(); processLog.addNote("Error searching for isbn " + requestIsbn); } } if (recordId != null) { //Place a hold on the title for the user URL placeHoldUrl; if (recordId.matches("econtentRecord\\d+")) { placeHoldUrl = new URL(vufindUrl + "/API/UserAPI?method=placeEContentHold&username=" + cat_username + "&password=" + cat_password + "&recordId=" + recordId); } else { placeHoldUrl = new URL( vufindUrl + "/API/UserAPI?method=placeHold&username=" + cat_username + "&password=" + cat_password + "&bibId=" + recordId + "&campus=" + holdPickupLocation); } logger.info("Place Hold URL: " + placeHoldUrl); Object placeHoldDataRaw = placeHoldUrl.getContent(); if (placeHoldDataRaw instanceof InputStream) { String placeHoldDataJson = Util.convertStreamToString((InputStream) placeHoldDataRaw); try { JSONObject placeHoldData = new JSONObject(placeHoldDataJson); JSONObject result = placeHoldData.getJSONObject("result"); holdCreated = result.getBoolean("success"); if (holdCreated) { logger.info("hold was created successfully."); processLog.incUpdated(); } else { logger.info("hold could not be created " + result.getString("holdMessage")); processLog.incErrors(); processLog.addNote("hold could not be created " + result.getString("holdMessage")); } } catch (JSONException e) { logger.error("Unable to load results of placing the hold", e); processLog.incErrors(); processLog.addNote("Unable to load results of placing the hold " + e.toString()); } } } if (holdCreated) { //Mark that the hold was created setHoldsCreatedStmt.setString(1, requestId); setHoldsCreatedStmt.executeUpdate(); } } } catch (Exception e) { logger.error("Error generating holds for purchased requests ", e); processLog.incErrors(); processLog.addNote("Error generating holds for purchased requests " + e.toString()); } }
From source file:com.projectgoth.mywebrtcdemo.RoomParametersFetcher.java
private void roomHttpResponseParse(String response) { Log.d(TAG, "Room response: " + response); try {//from www .j a v a2s . c o m LinkedList<IceCandidate> iceCandidates = null; SessionDescription offerSdp = null; JSONObject roomJson = new JSONObject(response); String result = roomJson.getString("result"); if (!result.equals("SUCCESS")) { events.onSignalingParametersError("Room response error: " + result); return; } response = roomJson.getString("params"); roomJson = new JSONObject(response); String roomId = roomJson.getString("room_id"); String clientId = roomJson.getString("client_id"); String wssUrl = roomJson.getString("wss_url"); String wssPostUrl = roomJson.getString("wss_post_url"); boolean initiator = (roomJson.getBoolean("is_initiator")); if (!initiator) { iceCandidates = new LinkedList<IceCandidate>(); String messagesString = roomJson.getString("messages"); JSONArray messages = new JSONArray(messagesString); for (int i = 0; i < messages.length(); ++i) { String messageString = messages.getString(i); JSONObject message = new JSONObject(messageString); String messageType = message.getString("type"); Log.d(TAG, "GAE->C #" + i + " : " + messageString); if (messageType.equals("offer")) { offerSdp = new SessionDescription(SessionDescription.Type.fromCanonicalForm(messageType), message.getString("sdp")); } else if (messageType.equals("candidate")) { IceCandidate candidate = new IceCandidate(message.getString("id"), message.getInt("label"), message.getString("candidate")); iceCandidates.add(candidate); } else { Log.e(TAG, "Unknown message: " + messageString); } } } Log.d(TAG, "RoomId: " + roomId + ". ClientId: " + clientId); Log.d(TAG, "Initiator: " + initiator); Log.d(TAG, "WSS url: " + wssUrl); Log.d(TAG, "WSS POST url: " + wssPostUrl); LinkedList<PeerConnection.IceServer> iceServers = iceServersFromPCConfigJSON( roomJson.getString("pc_config")); boolean isTurnPresent = false; for (PeerConnection.IceServer server : iceServers) { Log.d(TAG, "IceServer: " + server); if (server.uri.startsWith("turn:")) { isTurnPresent = true; break; } } // Request TURN servers. if (!isTurnPresent) { LinkedList<PeerConnection.IceServer> turnServers = requestTurnServers( roomJson.getString("turn_url")); for (PeerConnection.IceServer turnServer : turnServers) { Log.d(TAG, "TurnServer: " + turnServer); iceServers.add(turnServer); } } SignalingParameters params = new SignalingParameters(iceServers, initiator, clientId, wssUrl, wssPostUrl, offerSdp, iceCandidates); events.onSignalingParametersReady(params); } catch (JSONException e) { events.onSignalingParametersError("Room JSON parsing error: " + e.toString()); } catch (IOException e) { events.onSignalingParametersError("Room IO error: " + e.toString()); } }
From source file:org.kavaproject.kavatouch.internal.JSONDeviceConfiguration.java
public JSONDeviceConfiguration(Resources resources, int id) { InputStream jsonStream = resources.openRawResource(id); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int ctr;/*from ww w . ja va 2 s.c o m*/ try { ctr = jsonStream.read(); while (ctr != -1) { byteArrayOutputStream.write(ctr); ctr = jsonStream.read(); } jsonStream.close(); } catch (IOException e) { throw new Error(e); } try { JSONObject jConfiguration = new JSONObject(byteArrayOutputStream.toString()); flipYAxis = jConfiguration.getBoolean("flipYAxis"); useIPadTheme = jConfiguration.getBoolean("useIPadTheme"); JSONArray jDeviceModifiers = jConfiguration.getJSONArray("deviceModifiers"); for (int i = 0; i < jDeviceModifiers.length(); i++) { deviceModifiers.add(jDeviceModifiers.getString(i)); } JSONArray jImageScaleModifiers = jConfiguration.getJSONArray("imageScaleModifiers"); for (int i = 0; i < jImageScaleModifiers.length(); i++) { imageScaleModifiers.add(ImageScaleModifier.createFromJSON(jImageScaleModifiers.getJSONObject(i))); } double scale = jConfiguration.optDouble("scale"); if (Double.isNaN(scale)) { DisplayMetrics displayMetrics = resources.getDisplayMetrics(); this.scale = displayMetrics.density; } else { this.scale = (float) scale; } } catch (JSONException e) { throw new Error(e); } }
From source file:hongik.android.project.best.StoreActivity.java
public void drawPage() throws Exception { String query = "func=storereview" + "&license=" + license; DBConnector conn = new DBConnector(query); conn.start();/*from w w w. jav a 2s .com*/ conn.join(); JSONObject jsonResult = conn.getResult(); boolean result = jsonResult.getBoolean("result"); if (!result) return; final JSONObject store = jsonResult.getJSONArray("store").getJSONObject(0); JSONArray menu = null; if (!jsonResult.isNull("menu")) menu = jsonResult.getJSONArray("menu"); JSONArray review = null; if (!jsonResult.isNull("review")) review = jsonResult.getJSONArray("review"); //Draw Store Information Lat = Double.parseDouble(store.getString("LAT")); Lng = Double.parseDouble(store.getString("LNG")); sname = store.getString("SNAME"); ((TextViewPlus) findViewById(R.id.store_storename)).setText(sname); ((TextViewPlus) findViewById(R.id.store_address)).setText(store.getString("ADDR")); ImageLoader imgLoader = new ImageLoader(store.getString("IMG")); imgLoader.start(); try { imgLoader.join(); Bitmap storeImg = imgLoader.getBitmap(); ((ImageView) findViewById(R.id.store_image)).setImageBitmap(storeImg); } catch (InterruptedException e) { Toast.makeText(this, "Can not bring " + license + "store's image", Toast.LENGTH_SHORT).show(); Log.e("StoreInfo", "Can not bring " + license + "store's image"); } //Draw Menu Table if (menu != null) { TableRow motive = (TableRow) menuTable.getChildAt(1); for (int i = 0; i < menu.length(); i++) { JSONObject json = menu.getJSONObject(i); TableRow tbRow = new TableRow(this); TextViewPlus[] tbCols = new TextViewPlus[3]; final String[] elements = new String[2]; elements[0] = json.getString("ITEM#"); elements[1] = json.getString("PRICE"); imgLoader = new ImageLoader(json.getString("IMG")); imgLoader.start(); imgLoader.join(); ImageView img = new ImageView(this); Bitmap bitmap = imgLoader.getBitmap(); img.setImageBitmap(bitmap); img.setLayoutParams(motive.getChildAt(0).getLayoutParams()); img.setScaleType(ImageView.ScaleType.FIT_XY); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent storeIntent = new Intent(originActivity, MenuActivity.class); storeIntent.putExtra("LICENSE", license); storeIntent.putExtra("MENU", elements[0]); startActivity(storeIntent); } }); tbRow.addView(img); for (int j = 0; j < 2; j++) { tbCols[j] = new TextViewPlus(this); tbCols[j].setText(elements[j]); tbCols[j].setLayoutParams(motive.getChildAt(j + 1).getLayoutParams()); tbCols[j].setGravity(Gravity.CENTER); tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(), "InterparkGothicBold.ttf")); tbCols[j].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent storeIntent = new Intent(originActivity, MenuActivity.class); storeIntent.putExtra("LICENSE", license); storeIntent.putExtra("MENU", elements[0]); startActivity(storeIntent); } }); Log.i("StoreMenu", "COL" + j + ":" + elements[j]); tbRow.addView(tbCols[j]); } menuTable.addView(tbRow); } } menuTable.removeViewAt(1); //Draw Review Table if (review != null) { TableRow motive = (TableRow) reviewTable.getChildAt(1); int rowCnt = 5; if (review.length() < 5) rowCnt = review.length(); for (int i = 0; i < rowCnt; i++) { JSONObject json = review.getJSONObject(i); final String[] elements = new String[4]; elements[0] = Double.parseDouble(json.getString("GRADE")) + ""; elements[1] = json.getString("NOTE"); elements[2] = json.getString("CID#"); elements[3] = json.getString("DAY"); TableRow tbRow = new TableRow(this); TextViewPlus[] tbCols = new TextViewPlus[4]; if (elements[1].length() > 14) elements[1] = elements[1].substring(0, 14) + "..."; for (int j = 0; j < 4; j++) { tbCols[j] = new TextViewPlus(this); tbCols[j].setText(elements[j]); tbCols[j].setLayoutParams(motive.getChildAt(j).getLayoutParams()); tbCols[j].setGravity(Gravity.CENTER); tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(), "InterparkGothicBold.ttf")); tbCols[j].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent reviewIntent = new Intent(originActivity, ReviewDetailActivity.class); reviewIntent.putExtra("ACCESS", "STORE"); reviewIntent.putExtra("CID", elements[2]); reviewIntent.putExtra("LICENSE", license); Log.i("StoreReview", "StartActivity"); startActivity(reviewIntent); } }); Log.i("StoreMenu", "COL" + j + ":" + elements[j]); tbRow.addView(tbCols[j]); } reviewTable.addView(tbRow); } } reviewTable.removeViewAt(1); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.store_map); mapFragment.getMapAsync(this); }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
@Override public void onTextMessage(WebSocket websocket, String message) { JSONObject content = new JSONObject(message); int opCode = content.getInt("op"); if (!content.isNull("s")) { api.setResponseTotal(content.getInt("s")); }// w w w .j a v a 2 s .com switch (opCode) { case WebSocketCode.DISPATCH: handleEvent(content); break; case WebSocketCode.HEARTBEAT: LOG.debug("Got Keep-Alive request (OP 1). Sending response..."); sendKeepAlive(); break; case WebSocketCode.RECONNECT: LOG.debug("Got Reconnect request (OP 7). Closing connection now..."); close(); break; case WebSocketCode.INVALIDATE_SESSION: LOG.debug("Got Invalidate request (OP 9). Invalidating..."); final boolean isResume = content.getBoolean("d"); // When d: true we can wait a bit and then try to resume again //sending 4000 to not drop session int closeCode = isResume ? 4000 : 1000; if (isResume) LOG.debug("Session can be recovered... Closing and sending new RESUME request"); else if (!handleIdentifyRateLimit) // this can also mean we got rate limited in IDENTIFY (no need to invalidate then) invalidate(); close(closeCode); break; case WebSocketCode.HELLO: LOG.debug("Got HELLO packet (OP 10). Initializing keep-alive."); final JSONObject data = content.getJSONObject("d"); setupKeepAlive(data.getLong("heartbeat_interval")); if (!data.isNull("_trace")) updateTraces(data.getJSONArray("_trace"), "HELLO", WebSocketCode.HELLO); break; case WebSocketCode.HEARTBEAT_ACK: LOG.trace("Got Heartbeat Ack (OP 11)."); api.setPing(System.currentTimeMillis() - heartbeatStartTime); break; default: LOG.debug("Got unknown op-code: " + opCode + " with content: " + message); } }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
protected void handleEvent(JSONObject raw) { String type = raw.getString("t"); long responseTotal = api.getResponseTotal(); if (type.equals("GUILD_MEMBER_ADD")) ((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")) .modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), 1); if (type.equals("GUILD_MEMBER_REMOVE")) ((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")) .modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), -1); //If initiating, only allows READY, RESUMED, GUILD_MEMBERS_CHUNK, GUILD_SYNC, and GUILD_CREATE through. // If we are currently chunking, we don't allow GUILD_CREATE through anymore. if (initiating && !(type.equals("READY") || type.equals("GUILD_MEMBERS_CHUNK") || type.equals("RESUMED") || type.equals("GUILD_SYNC") || (!chunkingAndSyncing && type.equals("GUILD_CREATE")))) { //If we are currently GuildStreaming, and we get a GUILD_DELETE informing us that a Guild is unavailable // convert it to a GUILD_CREATE for handling. JSONObject content = raw.getJSONObject("d"); if (!chunkingAndSyncing && type.equals("GUILD_DELETE") && content.has("unavailable") && content.getBoolean("unavailable")) { type = "GUILD_CREATE"; raw.put("t", "GUILD_CREATE").put("jda-field", "This event was originally a GUILD_DELETE but was converted to GUILD_CREATE for WS init Guild streaming"); } else {//from www .jav a 2 s .co m LOG.debug("Caching " + type + " event during init!"); cachedEvents.add(raw); return; } } // // // Needs special handling due to content of "d" being an array // if(type.equals("PRESENCE_REPLACE")) // { // JSONArray presences = raw.getJSONArray("d"); // LOG.trace(String.format("%s -> %s", type, presences.toString())); // PresenceUpdateHandler handler = new PresenceUpdateHandler(api, responseTotal); // for (int i = 0; i < presences.length(); i++) // { // JSONObject presence = presences.getJSONObject(i); // handler.handle(presence); // } // return; // } JSONObject content = raw.getJSONObject("d"); LOG.trace(String.format("%s -> %s", type, content.toString())); try { switch (type) { //INIT types case "READY": //LOG.debug(String.format("%s -> %s", type, content.toString())); already logged on trace level processingReady = true; handleIdentifyRateLimit = false; sessionId = content.getString("session_id"); if (!content.isNull("_trace")) updateTraces(content.getJSONArray("_trace"), "READY", WebSocketCode.DISPATCH); handlers.get("READY").handle(responseTotal, raw); break; case "RESUMED": if (!processingReady) { initiating = false; ready(); } if (!content.isNull("_trace")) updateTraces(content.getJSONArray("_trace"), "RESUMED", WebSocketCode.DISPATCH); break; default: SocketHandler handler = handlers.get(type); if (handler != null) handler.handle(responseTotal, raw); else LOG.debug("Unrecognized event:\n" + raw); } } catch (JSONException ex) { LOG.warn("Got an unexpected Json-parse error. Please redirect following message to the devs:\n\t" + ex.getMessage() + "\n\t" + type + " -> " + content); LOG.log(ex); } catch (Exception ex) { LOG.log(ex); } }
From source file:net.dv8tion.jda.core.handle.GuildRoleUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; JSONObject rolejson = content.getJSONObject("role"); GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a Role Update for a Guild that is not yet cached: " + content); return null; }//from w w w .ja va 2 s .com final long roleId = rolejson.getLong("id"); RoleImpl role = (RoleImpl) guild.getRolesMap().get(roleId); if (role == null) { api.getEventCache().cache(EventCache.Type.ROLE, roleId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a Role Update for Role that is not yet cached: " + content); return null; } String name = rolejson.getString("name"); Color color = rolejson.getInt("color") != 0 ? new Color(rolejson.getInt("color")) : null; int position = rolejson.getInt("position"); long permissions = rolejson.getLong("permissions"); boolean hoisted = rolejson.getBoolean("hoist"); boolean mentionable = rolejson.getBoolean("mentionable"); if (!Objects.equals(name, role.getName())) { String oldName = role.getName(); role.setName(name); api.getEventManager().handle(new RoleUpdateNameEvent(api, responseNumber, role, oldName)); } if (!Objects.equals(color, role.getColor())) { Color oldColor = role.getColor(); role.setColor(color); api.getEventManager().handle(new RoleUpdateColorEvent(api, responseNumber, role, oldColor)); } if (!Objects.equals(position, role.getPositionRaw())) { int oldPosition = role.getPosition(); int oldPositionRaw = role.getPositionRaw(); role.setRawPosition(position); api.getEventManager() .handle(new RoleUpdatePositionEvent(api, responseNumber, role, oldPosition, oldPositionRaw)); } if (!Objects.equals(permissions, role.getPermissionsRaw())) { long oldPermissionsRaw = role.getPermissionsRaw(); role.setRawPermissions(permissions); api.getEventManager() .handle(new RoleUpdatePermissionsEvent(api, responseNumber, role, oldPermissionsRaw)); } if (hoisted != role.isHoisted()) { boolean wasHoisted = role.isHoisted(); role.setHoisted(hoisted); api.getEventManager().handle(new RoleUpdateHoistedEvent(api, responseNumber, role, wasHoisted)); } if (mentionable != role.isMentionable()) { boolean wasMentionable = role.isMentionable(); role.setMentionable(mentionable); api.getEventManager().handle(new RoleUpdateMentionableEvent(api, responseNumber, role, wasMentionable)); } return null; }
From source file:cc.redpen.server.api.RedPenService.java
/** * Create a new redpen for the JSON object. * @param requestJSON the JSON contains configurations * @return a configured redpen instance/*from w w w . ja va 2 s . c om*/ */ public RedPen getRedPenFromJSON(JSONObject requestJSON) { String lang = "en"; Map<String, Map<String, String>> properties = new HashMap<>(); JSONObject config = null; if (requestJSON.has("config")) { try { config = requestJSON.getJSONObject("config"); lang = getOrDefault(config, "lang", "en"); 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 = this.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); } } return redPen; }