Java Code Examples for org.json.simple.JSONValue#parseWithException()

The following examples show how to use org.json.simple.JSONValue#parseWithException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScriptExecutorImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(String script) {
    StringBuilder sb = new StringBuilder();
    // Callback for scripts that want to send some message back to page-inspection.
    // We utilize custom alert handling of WebEngine for this purpose.
    sb.append("postMessageToNetBeans=function(e) {alert('"); // NOI18N
    sb.append(WebBrowserImpl.PAGE_INSPECTION_PREFIX);
    sb.append("'+JSON.stringify(e));};\n"); // NOI18N
    String quoted = '\"'+JSONValue.escape(script)+'\"';
    // We don't want to depend on what is the type of WebBrowser.executeJavaScript()
    // for various types of script results => we stringify the result
    // (i.e. pass strings only through executeJavaScript()). We decode
    // the strigified result then.
    sb.append("JSON.stringify({result : eval(").append(quoted).append(")});"); // NOI18N
    String wrappedScript = sb.toString();
    Object result = browserTab.executeJavaScript(wrappedScript);
    String txtResult = result.toString();
    try {
        JSONObject jsonResult = (JSONObject)JSONValue.parseWithException(txtResult);
        return jsonResult.get("result"); // NOI18N
    } catch (ParseException ex) {
        Logger.getLogger(ScriptExecutorImpl.class.getName()).log(Level.INFO, null, ex);
        return ScriptExecutor.ERROR_RESULT;
    }
}
 
Example 2
Source File: ResponseUtil.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
public static Object getMessagesFromResponse(String responseStr, String node) {
    Object msgObject = null;
    if (responseStr == null || responseStr.equalsIgnoreCase(""))
        return msgObject;
    try {
        JSONObject responseObj = (JSONObject) JSONValue
                .parseWithException(responseStr);
        if (responseObj != null) {
            JSONObject dataObj = (JSONObject) responseObj
                    .get(ConstantsForTest.DATA);
            if (dataObj != null) {
                msgObject = dataObj.get(node);
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msgObject;
}
 
Example 3
Source File: JsUtils.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void parseNdJsonIntoValue( BufferedReader reader, Value value, boolean strictEncoding )
	throws IOException {
	List< String > stringItemVector = reader.lines().collect( Collectors.toList() );

	for( String stringItem : stringItemVector ) {
		StringReader itemReader = new StringReader( stringItem );
		try {
			Value itemValue = Value.create();
			Object obj = JSONValue.parseWithException( itemReader );
			if( obj instanceof JSONArray ) {
				itemValue.children().put( JSONARRAY_KEY,
					jsonArrayToValueVector( (JSONArray) obj, strictEncoding ) );
			} else if( obj instanceof JSONObject ) {
				jsonObjectToValue( (JSONObject) obj, itemValue, strictEncoding );
			} else {
				objectToBasicValue( obj, itemValue );
			}
			value.getChildren( "item" ).add( itemValue );
		} catch( ParseException | ClassCastException e ) {
			throw new IOException( e );
		}

	}

}
 
Example 4
Source File: ResourcesJsonTest.java    From FEMultiPlayer-V2 with GNU General Public License v3.0 6 votes vote down vote up
private void forEachResource(Function<JSONObject, Optional<String>> func) throws IOException, ParseException {
	final ArrayList<String> results = new ArrayList<>();
	
	final java.io.Reader reader = new java.io.InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("res/resources.json"));
	final JSONObject root = (JSONObject) JSONValue.parseWithException(reader);
	reader.close();
	
	final JSONArray textures = (JSONArray) root.get("textures");
	for (Object textureAny : textures) {
		try {
			JSONObject texture = (JSONObject) textureAny;
			Optional<String> result = func.apply(texture);
			result.ifPresent(str -> results.add(str));
			
		} catch (ClassCastException ex) {
			results.add("Subelement of `textures` is not a json object: " + textureAny);
		}
	}
	
	if (! results.isEmpty()) {
		fail(mkString(results, "Problems detected: \n\t", "\n\t", "\n"));
	}
}
 
Example 5
Source File: IOSDebugTransport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private JSONObject extractResponse(NSObject r) throws Exception {
    if (r == null) {
        return null;
    }
    if (!(r instanceof NSDictionary)) {
        return null;
    }
    NSDictionary root = (NSDictionary) r;
    NSDictionary argument = (NSDictionary) root.objectForKey("__argument"); // NOI18N
    if (argument == null) {
        return null;
    }
    NSData data = (NSData) argument.objectForKey("WIRMessageDataKey"); // NOI18N
    if (data == null) {
        return null;
    }
    byte[] bytes = data.bytes();
    String s = new String(bytes);
    JSONObject o = (JSONObject) JSONValue.parseWithException(s);
    return o;
}
 
Example 6
Source File: BundlesGenerator.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This function performs: 1. Parse the remote's responding result, the result would be like:
 * {"locales":"en, ja, zh_CN","components":"default","bundles":"[{ \"en\":
 * {\"cancel\":\"Abbrechen\"}, \"ja\": {\"cancel\":\"Abbrechen\"}, \"zh_CN\":
 * {\"cancel\":\"Abbrechen\"}, \"component\":\"default\"
 * }]","version":"1.0.0","productName":"devCenter"} 2. Convert the packaged JSON content with
 * multiple component messages to multiple JSO resource files 3. Write the translation to path
 * src-generated/main/resources/l10n/bundles/";
 * 
 * @param remoteRusult the remote's string
 */
public void handleRemoteRusult(String remoteRusult) {
    MultiComponentsDTO baseTranslationDTO = TranslationUtil.getBaseTranslationDTO(remoteRusult);
    List bundles = baseTranslationDTO.getBundles();
    Iterator<?> it = bundles.iterator();
    String jsonFilePathDir = this.getJsonPath(baseTranslationDTO);
    while (it.hasNext()) {
        try {
            JSONObject bundleObj = (JSONObject) JSONValue.parseWithException(it.next()
                    .toString());
            String component = (String) bundleObj.get(ConstantsKeys.COMPONENT);
            List<String> locales = baseTranslationDTO.getLocales();
            String componentPath = jsonFilePathDir + ConstantsChar.BACKSLASH + component;
            new File(componentPath).mkdir();
            for (String locale : locales) {
                String tLocale = StringUtils.trim(locale);
                this.writeToBundle(
                        componentPath + ConstantsChar.BACKSLASH
                                + TranslationUtil.genernateJsonLocalizedFileName(tLocale),
                        component, tLocale, (JSONObject) bundleObj.get(tLocale));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
 
Example 7
Source File: Updater.java    From Modern-LWC with MIT License 6 votes vote down vote up
public static Object[] getLastUpdate() {
    try {
        JSONArray versionsArray = (JSONArray) JSONValue
                .parseWithException((new URL(String.valueOf(VERSION_URL))).toString());
        Double lastVersion = Double
                .parseDouble(((JSONObject) versionsArray.get(versionsArray.size() - 1)).get("name").toString());

        if (lastVersion > Double.parseDouble(LWC.getInstance().getPlugin().getDescription().getVersion())) {
            JSONArray updatesArray = (JSONArray) JSONValue
                    .parseWithException((new URL(String.valueOf(DESCRIPTION_URL))).toString());
            String updateName = ((JSONObject) updatesArray.get(updatesArray.size() - 1)).get("title").toString();

            Object[] update = {lastVersion, updateName};
            return update;
        }
    } catch (Exception e) {
        return new String[0];
    }

    return new String[0];
}
 
Example 8
Source File: RestJSONResponseParser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Parse JSON response.
 * <p/>
 * @param in {@link InputStream} to read.
 * @return Response returned by REST administration service.
 */
@Override
public RestActionReport parse(InputStream in) {
    RestActionReport report = new RestActionReport();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        copy(in, out);
        String respMsg = out.toString("UTF-8");
        JSONObject json = (JSONObject)JSONValue.parseWithException(respMsg);
        parseReport(report, json);
    } catch (IOException ex) {
        throw new GlassFishIdeException("Unable to copy JSON response.", ex);
    } catch (ParseException e) {
        throw new GlassFishIdeException("Unable to parse JSON response.", e);
    }
    return report;
}
 
Example 9
Source File: PageInspectorImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Processes incoming message for the inspected page.
 * 
 * @param messageTxt message to process.
 */
private void processMessage(final String messageTxt) {
    if (messageTxt == null) {
        synchronized (LOCK) {
            uninitSelectionMode(pageContext.lookup(JToolBar.class));
            if (pageModel == getPage()) {
                inspectPage(Lookup.EMPTY);
            }
        }
    } else {
        try {
            JSONObject message = (JSONObject)JSONValue.parseWithException(messageTxt);
            Object type = message.get(MESSAGE_TYPE);
            // Message about selection mode modification
            if (MESSAGE_SELECTION_MODE.equals(type)) {
                boolean selectionMode = (Boolean)message.get(MESSAGE_SELECTION_MODE_ATTR);
                pageModel.setSelectionMode(selectionMode);
            }
        } catch (ParseException ex) {
            Logger.getLogger(PageInspectorImpl.class.getName())
                    .log(Level.INFO, "Ignoring message that is not in JSON format: {0}", messageTxt); // NOI18N
        }
    }
}
 
Example 10
Source File: Message.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Message parse( String message ){
    try {
        JSONObject json = (JSONObject)JSONValue.parseWithException(message);
        return new Message(MessageType.forString((String)json.get("message")), json);
    } catch (ParseException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    }
}
 
Example 11
Source File: RegistrarSettingsActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static Map<String, Object> readJsonFromFile(String filename, String lastUpdateTime) {
  String contents =
      loadFile(
          RegistrarSettingsActionTestCase.class,
          filename,
          ImmutableMap.of("LAST_UPDATE_TIME", lastUpdateTime));
  try {
    @SuppressWarnings("unchecked")
    Map<String, Object> json = (Map<String, Object>) JSONValue.parseWithException(contents);
    return json;
  } catch (ParseException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 12
Source File: SourceMap.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given {@code text} and returns the corresponding JSON object.
 * 
 * @param text text to parse.
 * @return JSON object that corresponds to the given text.
 * @throws IllegalArgumentException when the given text is not a valid
 * representation of a JSON object.
 */
private static JSONObject toJSONObject(String text) throws IllegalArgumentException {
    try {
        JSONObject json = (JSONObject)JSONValue.parseWithException(text);
        return json;
    } catch (ParseException ex) {
        throw new IllegalArgumentException(text);
    }
}
 
Example 13
Source File: RemoteScriptExecutor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a message for this executor is received.
 * 
 * @param messageTxt message for this executor.
 */
void messageReceived(String messageTxt) {
    try {
        JSONObject message = (JSONObject)JSONValue.parseWithException(messageTxt);
        Object type = message.get(MESSAGE_TYPE);
        if (MESSAGE_EVAL.equals(type)) {
            int id = ((Number)message.get(MESSAGE_ID)).intValue();
            synchronized (LOCK) {
                for (int i=lastIDReceived+1; i<id; i++) {
                    LOG.log(Level.INFO, "Haven''t received result of execution of script with ID {0}.", i); // NOI18N
                    results.put(i, ERROR_RESULT);
                }
                Object status = message.get(MESSAGE_STATUS);
                Object result = message.get(MESSAGE_RESULT);
                if (MESSAGE_STATUS_OK.equals(status)) {
                    results.put(id, result);
                } else {
                    LOG.log(Level.INFO, "Message with id {0} wasn''t executed successfuly: {1}", // NOI18N
                            new Object[]{id, result});
                    results.put(id, ERROR_RESULT);
                }
                lastIDReceived = id;
                LOCK.notifyAll();
            }
        }
    } catch (ParseException ex) {
        LOG.log(Level.INFO, "Ignoring message that is not in JSON format: {0}", messageTxt); // NOI18N
    }        
}
 
Example 14
Source File: JsUtils.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void parseJsonIntoValue( Reader reader, Value value, boolean strictEncoding )
	throws IOException {
	try {
		Object obj = JSONValue.parseWithException( reader );
		if( obj instanceof JSONArray ) {
			value.children().put( JSONARRAY_KEY, jsonArrayToValueVector( (JSONArray) obj, strictEncoding ) );
		} else if( obj instanceof JSONObject ) {
			jsonObjectToValue( (JSONObject) obj, value, strictEncoding );
		} else {
			objectToBasicValue( obj, value );
		}
	} catch( ParseException | ClassCastException e ) {
		throw new IOException( e );
	}
}
 
Example 15
Source File: SSTableExportTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/**
 * Tests CASSANDRA-6892 (key aliases being used improperly for validation)
 */
@Test
public void testColumnNameEqualToDefaultKeyAlias() throws IOException, ParseException
{
    File tempSS = tempSSTableFile("Keyspace1", "UUIDKeys");
    ColumnFamily cfamily = ArrayBackedSortedColumns.factory.create("Keyspace1", "UUIDKeys");
    SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2, ActiveRepairService.UNREPAIRED_SSTABLE);

    // Add a row
    cfamily.addColumn(column(CFMetaData.DEFAULT_KEY_ALIAS, "not a uuid", 1L));
    writer.append(Util.dk(ByteBufferUtil.bytes(UUIDGen.getTimeUUID())), cfamily);

    SSTableReader reader = writer.closeAndOpenReader();
    // Export to JSON and verify
    File tempJson = File.createTempFile("CFWithColumnNameEqualToDefaultKeyAlias", ".json");
    SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[0],
            CFMetaData.sparseCFMetaData("Keyspace1", "UUIDKeys", BytesType.instance));

    JSONArray json = (JSONArray)JSONValue.parseWithException(new FileReader(tempJson));
    assertEquals(1, json.size());

    JSONObject row = (JSONObject)json.get(0);
    JSONArray cols = (JSONArray) row.get("cells");
    assertEquals(1, cols.size());

    // check column name and value
    JSONArray col = (JSONArray) cols.get(0);
    assertEquals(CFMetaData.DEFAULT_KEY_ALIAS, ByteBufferUtil.string(hexToBytes((String) col.get(0))));
    assertEquals("not a uuid", ByteBufferUtil.string(hexToBytes((String) col.get(1))));
}
 
Example 16
Source File: EppControllerTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<String, Object> parseJsonMap(String json) throws Exception {
  return (Map<String, Object>) JSONValue.parseWithException(json);
}
 
Example 17
Source File: GenerateDnsReportCommandTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private Object getOutputAsJson() throws IOException, ParseException {
  try (Reader reader = Files.newBufferedReader(output, UTF_8)) {
    return JSONValue.parseWithException(reader);
  }
}
 
Example 18
Source File: ResourceFileWritter.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This function will perform: 1. Parse the remote's responding result, the
 * result would be like:
 * {"locales":"en, ja, zh_CN","components":"default","bundles":"[{ \"en\":
 * {\"cancel\":\"Abbrechen\"}, \"ja\": {\"cancel\":\"Abbrechen\"},
 * \"zh_CN\": {\"cancel\":\"Abbrechen\"}, \"component\":\"default\"
 * }]","version":"1.0.0","productName":"devCenter"} 2. Convert the packaged
 * JSON content with multiple component messages to multiple JSO resource
 * files 3. Write the translation to path
 * src-generated/main/resources/l10n/bundles/";
 *
 * @param remoteRusult
 *            the string to parse and write
 * @throws VIPResourceOperationException
 *             if file opertion gets problem
 */
public static void writeStrToMultiJSONFiles(String remoteRusult)
		throws VIPResourceOperationException {
	MultiComponentsDTO baseTranslationDTO = new MultiComponentsDTO();
	try {
		baseTranslationDTO = MultiComponentsDTO
				.getMultiComponentsDTO(remoteRusult);
	} catch (VIPAPIException e1) {
		e1.printStackTrace();
	}
	List bundles = baseTranslationDTO.getBundles();
	Iterator<?> it = bundles.iterator();
	SingleComponentDTO singleComponentDTO = new SingleComponentDTO();
	singleComponentDTO.setProductName(baseTranslationDTO.getProductName());
	singleComponentDTO.setVersion(baseTranslationDTO.getVersion());
	while (it.hasNext()) {
		try {
			JSONObject bundleObj = (JSONObject) JSONValue
					.parseWithException(it.next().toString());
			String component = (String) bundleObj
					.get(ConstantsKeys.COMPONENT);
			singleComponentDTO.setComponent(component);
			List<String> locales = baseTranslationDTO.getLocales();
			for (String locale : locales) {
				String tLocale = StringUtils.trim(locale);
				singleComponentDTO.setLocale(tLocale);
				singleComponentDTO.setMessages((JSONObject) bundleObj
						.get(tLocale));
				String jsonFilePathDir = ResourceFilePathGetter
						.getLocalizedJSONFilesDir(singleComponentDTO);
				ResourceFileWritter.writeJSONObjectToJSONFile(
						jsonFilePathDir
								+ ConstantsChar.BACKSLASH
								+ ResourceFilePathGetter
										.getLocalizedJSONFileName(tLocale),
						singleComponentDTO);
			}
		} catch (ParseException e) {
			throw new VIPResourceOperationException("Parse '"
					+ it.next().toString() + "' failed.");
		}
	}
}
 
Example 19
Source File: I18nUtilTest.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testLocalesExtract() {
	
	String languages="zh,en,zh-Hant,zh-Hans-HK";
	
	try {
		String[] languageArray=languages.split(",");
		for(int i=0;i<languageArray.length;i++) {
			String regions = PatternUtil.getRegionFromLib(languageArray[i]);
			Map<String, Object> genreJsonObject = null;
			genreJsonObject = (Map<String, Object>) JSONValue.parseWithException(regions);
			Map<String, Object> territoriesObject = (Map<String, Object>) JSONValue.parseWithException(genreJsonObject.get("territories").toString());
			if (languageArray[i].equals("zh")) {
				Assert.assertEquals("zh", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("台湾", territoriesObject.get("TW"));

				Assert.assertEquals("阿森松岛", territoriesObject.get("AC"));
				Assert.assertEquals("南极洲", territoriesObject.get("AQ"));
				Assert.assertEquals("布韦岛", territoriesObject.get("BV"));
				Assert.assertEquals("克利珀顿岛", territoriesObject.get("CP"));

				Assert.assertEquals("南乔治亚和南桑威奇群岛", territoriesObject.get("GS"));
				Assert.assertEquals("赫德岛和麦克唐纳群岛", territoriesObject.get("HM"));
				Assert.assertEquals("马尔代夫", territoriesObject.get("MV"));
				Assert.assertEquals("特里斯坦-达库尼亚群岛", territoriesObject.get("TA"));

				Assert.assertEquals("法属南部领地", territoriesObject.get("TF"));
				Assert.assertEquals("未知地区", territoriesObject.get("ZZ"));
				Assert.assertEquals("", genreJsonObject.get("defaultRegionCode"));
			}
			if (languageArray[i].equals("zh-Hant")) {
				Assert.assertEquals("zh", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("台灣", territoriesObject.get("TW"));
				Assert.assertEquals("義大利", territoriesObject.get("IT"));
				Assert.assertEquals("TW", genreJsonObject.get("defaultRegionCode"));

			}
			if (languageArray[i].equals("en")) {
				Assert.assertEquals("en", genreJsonObject.get("language"));
				Assert.assertNotNull(territoriesObject.get("TW"));
				Assert.assertEquals("Taiwan", territoriesObject.get("TW"));
				Assert.assertEquals("North Korea", territoriesObject.get("KP"));
				Assert.assertEquals("US", genreJsonObject.get("defaultRegionCode"));
			}
			if (languageArray[i].equals("zh-Hans-HK")) {
				Assert.assertEquals("HK", genreJsonObject.get("defaultRegionCode"));
			}

		}	
	} catch (ParseException e) {
		e.printStackTrace();
	}
}
 
Example 20
Source File: JSONUtils.java    From sqoop-on-spark with Apache License 2.0 3 votes vote down vote up
/**
 * Parse given string as JSON and return corresponding JSONObject.
 *
 * This method will throw SqoopException on any parsing error.
 *
 * @param input JSON encoded String
 * @return
 */
public static JSONObject parse(String input) {
  try {
    return (JSONObject) JSONValue.parseWithException(input);
  } catch (ParseException e) {
    throw new SqoopException(SerializationError.SERIALIZATION_002, e);
  }
}