Java Code Examples for net.sf.json.JSONSerializer#toJSON()
The following examples show how to use
net.sf.json.JSONSerializer#toJSON() .
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: Google.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
public String newAccessToken() { try { Map<String, String> params = new HashMap<String, String>(); params.put("refresh_token", this.refreshToken); params.put("client_id", CLIENTID); params.put("client_secret", CLIENTSECRET); //params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"); params.put("grant_type", "refresh_token"); String json = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params); JSON root = (JSON)JSONSerializer.toJSON(json); if (!(root instanceof JSONObject)) { return null; } return ((JSONObject)root).getString("access_token"); } catch (Exception exception) { log(exception); return null; } }
Example 2
Source File: ParallelsDesktopConnectorSlaveComputer.java From jenkins-parallels with MIT License | 6 votes |
public boolean checkVmExists(String vmId) { try { RunVmCallable command = new RunVmCallable("list", "-i", "--json"); String callResult = forceGetChannel().call(command); JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult); for (int i = 0; i < vms.size(); i++) { JSONObject vmInfo = vms.getJSONObject(i); if (vmId.equals(vmInfo.getString("ID")) || vmId.equals(vmInfo.getString("Name"))) return true; } return true; } catch (Exception ex) { LOGGER.log(Level.SEVERE, ex.toString()); } return false; }
Example 3
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * Return the JSON data object from the URL. */ public Vertex requestJSON(String url, String attribute, Map<String, String> headers, Network network) { log("GET JSON", Level.INFO, url, attribute); try { String json = Utils.httpGET(url, headers); log("JSON", Level.FINE, json); JSON root = (JSON)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Object value = root; if (attribute != null) { value = ((JSONObject)root).get(attribute); if (value == null) { return null; } } Vertex object = convertElement(value, network); return object; } catch (Exception exception) { log(exception); return null; } }
Example 4
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * Return the count of the JSON result array. */ public int countJSON(String url, String attribute, Network network) { log("COUNT JSON", Level.INFO, url, attribute); try { String json = Utils.httpGET(url); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return 0; } Object value = root.get(attribute); if (value == null) { return 0; } if (value instanceof JSONArray) { return ((JSONArray)value).size(); } return 1; } catch (Exception exception) { log(exception); return 0; } }
Example 5
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * POST the JSON object and return the JSON data from the URL. */ public Vertex postJSON(String url, Vertex jsonObject, Map<String, String> headers, Network network) { log("POST JSON", Level.INFO, url); try { String data = convertToJSON(jsonObject); log("POST JSON", Level.FINE, data); String json = Utils.httpPOST(url, "application/json", data, headers); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
Example 6
Source File: GogsConfigHandler.java From gogs-webhook-plugin with MIT License | 6 votes |
/** * Creates a web hook in Gogs with the passed json configuration string * * @param jsonCommand A json buffer with the creation command of the web hook * @param projectName the project (owned by the user) where the webHook should be created * @throws IOException something went wrong */ int createWebHook(String jsonCommand, String projectName) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks"; Executor executor = getExecutor(); Request request = Request.Post(gogsHooksConfigUrl); if (gogsAccessToken != null) { request.addHeader("Authorization", "token " + gogsAccessToken); } String result = executor .execute(request.bodyString(jsonCommand, ContentType.APPLICATION_JSON)) .returnContent().asString(); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result ); return jsonObject.getInt("id"); }
Example 7
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
/** * GET the JSON data from the URL. */ public Vertex requestJSONAuth(String url, String user, String password, String agent, Network network) { log("GET JSON Auth", Level.INFO, url); try { String json = Utils.httpAuthGET(url, user, password, agent); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
Example 8
Source File: JSONToXMLConverter.java From jmeter-plugins with Apache License 2.0 | 5 votes |
@Deprecated private String ConvertToXML(String jsonData) { XMLSerializer serializer = new XMLSerializer(); JSON json = JSONSerializer.toJSON(jsonData); serializer.setRootName("xmlOutput"); serializer.setTypeHintsEnabled(false); return serializer.write(json); }
Example 9
Source File: WeChat.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Retrieves access token for bot. * Access token must be obtained before calling APIs */ protected void getAccessToken() throws Exception { String url = "https://"; url = url.concat( this.international ? INTERNATIONAL_API : CHINA_API ); url = url.concat("/cgi-bin/token"); String data = "?grant_type=client_credential&appid=" + appId + "&secret=" + appPassword; url = url.concat(data); String json = Utils.httpGET(url); JSONObject root = (JSONObject)JSONSerializer.toJSON(json); if(root.optString("access_token") != null) { int tokenExpiresIn = root.optInt("expires_in"); String accessToken = root.optString("access_token"); setToken(accessToken); this.tokenExpiry = new Date(System.currentTimeMillis() + (tokenExpiresIn * 1000)); log("WeChat access token retrieved - token: " + accessToken + ", expires in " + tokenExpiresIn, Level.INFO); } else if (root.optString("errmsg") != null) { String errMsg = root.optString("errmsg"); int errCode = root.optInt("errcode"); log("WeChat get access token failed - Error code:" + errCode + ", Error Msg: " + errMsg, Level.INFO); } else { log("WeChat get access token failed.", Level.INFO); } saveProperties(); }
Example 10
Source File: GlobalConfigurationServiceTest.java From sonar-quality-gates-plugin with MIT License | 5 votes |
@Test public void testGetGlobalConfigsArrayWhenArray() { String arrayString = "[{\"name\":\"Sonar1\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"},{\"name\":\"Sonar2\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}]"; globalDataConfigs = JSONSerializer.toJSON(arrayString); jsonArray = JSONArray.class.cast(globalDataConfigs); assertEquals(jsonArray, globalConfigurationService.getGlobalConfigsArray(globalDataConfigs)); }
Example 11
Source File: GlobalConfigurationServiceTest.java From sonar-quality-gates-plugin with MIT License | 5 votes |
@Test public void testGetGlobalConfigsArrayWhenObject() { jsonArray = new JSONArray(); doReturn(jsonArray).when(spyGlobalConfigurationService).createJsonArrayFromObject(JSONObject.fromObject(globalDataConfigs)); String objectString = "{\"name\":\"Sonar\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}"; globalDataConfigs = JSONSerializer.toJSON(objectString); jsonArray.add(globalDataConfigs); assertEquals(jsonArray, spyGlobalConfigurationService.getGlobalConfigsArray(globalDataConfigs)); }
Example 12
Source File: DatadogHttpClient.java From jenkins-datadog-plugin with MIT License | 5 votes |
@Override public boolean validate() throws IOException, ServletException { String urlParameters = "?api_key=" + apiKey; HttpURLConnection conn = null; boolean status = true; try { // Make request conn = getHttpURLConnection(new URL(url + VALIDATE + urlParameters)); conn.setRequestMethod("GET"); // Get response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); // Validate JSONObject json = (JSONObject) JSONSerializer.toJSON(result.toString()); if (!json.getBoolean("valid")) { status = false; } } catch (Exception e) { if (conn != null && conn.getResponseCode() == HTTP_FORBIDDEN) { logger.severe("Hmmm, your API key may be invalid. We received a 403 error."); } else { logger.severe(String.format("Client error: %s", e.toString())); } status = false; } finally { if (conn != null) { conn.disconnect(); } } return status; }
Example 13
Source File: BlazemeterAPIClientTest.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
@org.junit.Test public void testUserFlow() throws Exception { URL url = BlazemeterAPIClientTest.class.getResource("/responses.json"); JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(FileUtils.readFileToString(new File(url.getPath())), new JsonConfig()); StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl(); BlazeMeterReport report = new BlazeMeterReport(); report.setShareTest(true); report.setProject("New project"); report.setTitle("New test"); report.setToken("123456"); BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "https://a.blazemeter.com/", "data_address", new BlazeMeterReport()); for (Object resp : jsonArray) { emul.addEmul((JSON) resp); } BlazeMeterAPIClient apiClient = new BlazeMeterAPIClient(emul, notifier, report); apiClient.prepare(); // if share user test String linkPublic = apiClient.startOnline(); System.out.println(linkPublic); assertFalse(linkPublic.isEmpty()); assertEquals("https://a.blazemeter.com//app/?public-token=public_test_token#/masters/master_id/summary", linkPublic); // if private user test report.setShareTest(false); String linkPrivate = apiClient.startOnline(); System.out.println(linkPrivate); assertFalse(linkPrivate.isEmpty()); assertEquals("https://a.blazemeter.com//app/#/masters/master_id", linkPrivate); List<SampleResult> sampleResults = generateResults(); apiClient.sendOnlineData(JSONConverter.convertToJSON(sampleResults, sampleResults)); apiClient.endOnline(); }
Example 14
Source File: FreebaseUtil.java From xcurator with Apache License 2.0 | 5 votes |
public static JSONArray fetch(String query_template_file, Map<String, String> params) { try { properties.load(new FileInputStream(FREEBASE_PROPERTIES_LOC)); HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); String query = IOUtils.toString(new FileInputStream(query_template_file)); query = manipulateQuery(query, params); GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread"); url.put("query", query); url.put("key", properties.get("API_KEY")); System.out.println("URL:" + url); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse httpResponse = request.execute(); JSON obj = JSONSerializer.toJSON(httpResponse.parseAsString()); if (obj.isEmpty()) { return null; } JSONObject jsonObject = (JSONObject) obj; JSONArray results = jsonObject.getJSONArray("result"); System.out.println(results.toString()); return results; } catch (IOException ex) { ex.printStackTrace(); } return null; }
Example 15
Source File: BasicSense.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Create an input based on the sentence. */ protected Vertex createInputCommand(String json, Network network) { JSONObject root = (JSONObject)JSONSerializer.toJSON(json); if (root == null) { return null; } Vertex object = getBot().awareness().getSense(Http.class).convertElement(root, network); Vertex input = network.createInstance(Primitive.INPUT); input.setName(json); input.addRelationship(Primitive.SENSE, getPrimitive()); input.addRelationship(Primitive.INPUT, object); return input; }
Example 16
Source File: Facebook.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Check the command JSON for a Facebook attachment object to append to a Facebook Messeneger message. */ public String createJSONAttachment(String command, String id, String text) { JSONObject root = (JSONObject)JSONSerializer.toJSON(command); if (!root.has("type") || !root.getString("type").equals("facebook")) { return ""; } JSONObject json = root.getJSONObject("attachment"); if (json == null) { return ""; } return json.toString(); }
Example 17
Source File: OnlineDbMVStoreUtils.java From ipst with Mozilla Public License 2.0 | 4 votes |
public static Map<String, Boolean> jsonToIndexesData(String json) { JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(json); return (Map<String, Boolean>) JSONObject.toBean(jsonObj, Map.class); }
Example 18
Source File: QQSpeech.java From BotLibre with Eclipse Public License 1.0 | 4 votes |
public static synchronized boolean speak(String voice, String text, String file, String apiKey, String appId) { if ((text == null) || text.isEmpty()) { return false; } if (text.length() > MAX_SIZE) { text = text.substring(0, MAX_SIZE); } try { TreeMap<String, String> params = new TreeMap<String, String>(); params.put("app_id", appId); params.put("speaker", voice); params.put("format", "3"); params.put("volume", "0"); params.put("speed", "100"); params.put("text", text); params.put("aht", "0"); params.put("apc", "58"); params.put("time_stamp", String.valueOf(new Date().getTime() / 1000)); params.put("nonce_str", UUID.randomUUID().toString().replace("-", "")); params.put("sign", getQQRequestSignature(apiKey, appId, params)); String paramString = ""; try { for (Map.Entry<String, String> entry : params.entrySet()) { paramString = paramString.concat(entry.getKey()).concat("=").concat(URLEncoder.encode(entry.getValue(), "UTF-8")).concat("&"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String response = Utils.httpPOST(QQ_SPEECH_URL, "application/x-www-form-urlencoded", paramString); JSONObject root = (JSONObject)JSONSerializer.toJSON(response); JSONObject data = root.getJSONObject("data"); if(data!=null) { String speech = data.getString("speech"); if(speech != null && !speech.isEmpty()) { File path = new File(file + ".mp3"); new File(path.getParent()).mkdirs(); byte[] audioData = Base64.decode(speech); FileOutputStream fos = new FileOutputStream(path); fos.write(audioData); fos.close(); } else { throw new Exception(response); } } else { throw new Exception(response); } } catch (Exception exception) { AdminDatabase.instance().log(exception); return false; } return true; }
Example 19
Source File: JsonUtils.java From pipeline-aws-plugin with Apache License 2.0 | 4 votes |
public static Object fromString(String string) { return JSONSerializer.toJSON(string); }
Example 20
Source File: Twilio.java From BotLibre with Eclipse Public License 1.0 | 4 votes |
/** * Generate the voice Twilio TwiML XML string from the reply and command JSON. */ public String generateVoiceTwiML(String command, String reply) { JSONObject json = null; if (command != null && !command.isEmpty()) { JSONObject root = (JSONObject)JSONSerializer.toJSON(command); json = root.optJSONObject("twiml"); } StringWriter writer = new StringWriter(); writer.write("<Response>"); if (json == null) { writer.write("<Gather timeout='3' input='speech dtmf'>"); writer.write("<Say>" + reply + "</Say>"); writer.write("</Gather>"); writer.write("</Response>"); return writer.toString(); } // If there is a command, then only write the command elements. // Append the reply to the gather. boolean hasSay = false; for (Object key : json.keySet()) { boolean isGather = "Gather".equals(String.valueOf(key)); boolean isSay = "Say".equals(String.valueOf(key)); writer.write("<"); writer.write(String.valueOf(key)); Object element = json.opt((String)key); if (element instanceof String) { writer.write(">"); writer.write(String.valueOf(element)); } else if (element instanceof JSONObject) { boolean hasInput = false; boolean hasTimeout = false; for (Object attribute : ((JSONObject)element).keySet()) { if ("input".equals(String.valueOf(attribute))) { hasInput = true; } if ("timeout".equals(String.valueOf(attribute))) { hasTimeout = true; } writer.write(" "); writer.write(String.valueOf(attribute)); writer.write("='"); Object value = ((JSONObject)element).opt((String)attribute); writer.write(String.valueOf(value)); writer.write("'"); } if (!hasInput && isGather) { writer.write(" input='speech dtmf'"); } if (!hasTimeout && isGather) { writer.write(" timeout='3'"); } writer.write(">"); if (isSay) { writer.write(reply); hasSay = true; } } if (isGather && !hasSay) { writer.write("<Say>" + reply + "</Say>"); } writer.write("</"); writer.write(String.valueOf(key)); writer.write(">"); } writer.write("</Response>"); return writer.toString(); }