List of usage examples for org.json JSONObject toString
public String toString()
From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java
public String userProfile() { Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {}); try {/*from ww w . j ava2 s .co m*/ c.moveToFirst(); JSONObject obj = new JSONObject(); try { obj.put("name", c.getString(c.getColumnIndexOrThrow(MyInfo.NAME))); } catch (JSONException e) { } return JSON.fastAddBase64(obj.toString(), "picture", c.getBlob(c.getColumnIndexOrThrow(MyInfo.PICTURE))); } finally { c.close(); } }
From source file:com.extremeboredom.wordattack.utils.JSONUtils.java
/** * get String from jsonObject//from w w w . j ava 2 s .c o m * * @param jsonObject * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static String getStringCascade(JSONObject jsonObject, String defaultValue, String... keyArray) { if (jsonObject == null || keyArray == null || keyArray.length == 0) { return defaultValue; } String data = jsonObject.toString(); for (String key : keyArray) { data = getStringCascade(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; }
From source file:com.sfalma.trace.Sfalma.java
public static String createJSON(String app_package, String version, String phoneModel, String android_version, String stackTrace, String wifi_status, String mob_net_status, String gps_status, Date occuredAt) throws Exception { JSONObject json = new JSONObject(); JSONObject request_json = new JSONObject(); JSONObject exception_json = new JSONObject(); JSONObject application_json = new JSONObject(); JSONObject client_json = new JSONObject(); request_json.put("remote_ip", ""); json.put("request", request_json); // stackTrace contains many info we need to extract BufferedReader reader = new BufferedReader(new StringReader(stackTrace)); if (occuredAt == null) exception_json.put("occured_at", reader.readLine()); else//from www . j a va 2s .c o m exception_json.put("occured_at", occuredAt); exception_json.put("message", reader.readLine()); //get message String exception_class = reader.readLine(); exception_json.put("where", exception_class.substring(exception_class.lastIndexOf("(") + 1, exception_class.lastIndexOf(")"))); exception_json.put("klass", getClass(stackTrace)); exception_json.put("backtrace", stackTrace); json.put("exception", exception_json); reader.close(); application_json.put("phone", phoneModel); application_json.put("appver", version); application_json.put("appname", app_package); application_json.put("osver", android_version); //os_ver application_json.put("wifi_on", wifi_status); application_json.put("mobile_net_on", mob_net_status); application_json.put("gps_on", gps_status); json.put("application_environment", application_json); client_json.put("version", "sfalma-version-0.6"); client_json.put("name", "sfalma-android"); json.put("client", client_json); return json.toString(); }
From source file:edu.asu.bscs.ihattend.jsonrpcapp.JsonRPCCalculator.java
public Double calculate(Double op1, Double op2, String operation) { try {//from www .j a v a2 s . c o m JSONObject jsonObject = new JSONObject(); jsonObject.put("jsonrpc", "2.0"); jsonObject.put("id", ++id); jsonObject.put("method", operation); String params = String.format(",\"params\":[%.2f,%.2f]", op1, op2); String almost = jsonObject.toString(); String begin = almost.substring(0, almost.length() - 1); String end = almost.substring(almost.length() - 1); String call = begin + params + end; Log.d(TAG, "call: " + call); String responseString = server.call(call); Log.d(TAG, "response: " + responseString); JSONObject response = new JSONObject(responseString); Double result = response.optDouble("result"); Log.d(TAG, "result: " + result); return result; } catch (Exception e) { e.printStackTrace(); } // should really throw an exception... return 0.0; }
From source file:actuatorapp.ActuatorApp.java
public ActuatorApp() throws IOException, JSONException { //Takes a sting with a relay name "RELAYLO1-10FAD.relay1" //Actuator a = new Actuator("RELAYLO1-12854.relay1"); //Starts the virtualhub that is needed to connect to the actuators Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start(); //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"} api = new Socket("10.42.72.25", 8082); OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8); InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8); //Sends JSON authentication to CommandAPI JSONObject secret = new JSONObject(); secret.put("type", "authenticate"); secret.put("secret", "testpass"); osw.write(secret.toString() + "\r\n"); osw.flush();//from w w w . j ava 2 s . c om System.out.println("sent"); //Waits and recieves JSON authentication response BufferedReader br = new BufferedReader(isr); JSONObject response = new JSONObject(br.readLine()); System.out.println(response.toString()); if (!response.getBoolean("success")) { System.err.println("Invalid API secret"); System.exit(1); } try { while (true) { //JSON object will contain message from the server JSONObject type = getCommand(br); //Forward the command to be processed (will find out which actuators to turn on/off) commandFromApi(type); } } catch (Exception e) { System.out.println("Error listening to api"); } }
From source file:ai.ilikeplaces.logic.sits9.SubscriberNotifications.java
@Timeout synchronized public void timeout(final Timer timer) throws IOException, SAXException, TransformerException, JSONException, SQLException { final HBaseCrudService<GeohashSubscriber> _geohashSubscriberHBaseCrudService = new HBaseCrudService<GeohashSubscriber>(); final HBaseCrudService<GeohashSubscriber>.Scanner _scanner = _geohashSubscriberHBaseCrudService .scan(new GeohashSubscriber(), 1).returnValueBadly(); while (_scanner.getNewValue() != null) { final String _newValue = _scanner.getNewValue(); Loggers.debug("Scanned value:" + _newValue); final RowResponse _rowResponse = new Gson().fromJson(_newValue, RowResponse.class); Loggers.debug("Scanned as GSON:" + _rowResponse.toString()); for (final Row _row : _rowResponse.Row) { final BASE64Decoder _base64DecoderRowKey = new BASE64Decoder(); final byte[] _bytes = _base64DecoderRowKey.decodeBuffer(_row.key); final String rowKey = new String(_bytes); Loggers.debug("Decoded row key:" + rowKey); for (final Cell _cell : _row.Cell) { final BASE64Decoder _base64DecoderValue = new BASE64Decoder(); final byte[] _valueBytes = _base64DecoderValue.decodeBuffer(_cell.$); final String _cellAsString = new String(_valueBytes); Loggers.debug("Cell as string:" + _cellAsString); final GeohashSubscriber _geohashSubscriber = new GeohashSubscriber(); final DatumReader<GeohashSubscriber> _geohashSubscriberSpecificDatumReader = new SpecificDatumReader<GeohashSubscriber>( _geohashSubscriber.getSchema()); final BinaryDecoder _binaryDecoder = DecoderFactory.get().binaryDecoder(_valueBytes, null); final GeohashSubscriber _read = _geohashSubscriberSpecificDatumReader.read(_geohashSubscriber, _binaryDecoder); Loggers.debug("Decoded value avro:" + _read.toString()); final Date now = new Date(); final Calendar _week = Calendar.getInstance(); _week.setTimeInMillis(now.getTime() + (7 * 24 * 60 * 60 * 1000)); final SimpleDateFormat _simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); _simpleDateFormat.format(_week.getTime()); final StringBuffer eventList = new StringBuffer(""); {//Eventful try { final SimpleDateFormat eventfulDate = new SimpleDateFormat("yyyyMMdd00"); _simpleDateFormat.format(_week.getTime()); final JSONObject jsonObject = Modules.getModules().getEventulFactory() .getInstance("http://api.eventful.com/json/events/search/") .get("", new HashMap<String, String>() { {//Don't worry, this is a static initializer of this map :) put("location", "" + _read.getLatitude() + "," + _read.getLongitude()); put("within", "" + 100); put("date", eventfulDate.format(Calendar.getInstance().getTime()) + "-" + eventfulDate.format(_week.getTime())); }//from ww w .j av a 2 s . com } ); Loggers.debug("Eventful Reply:" + jsonObject.toString()); final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event"); final Document eventTemplateDocument = HTMLDocParser .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_EVENT); final String eventTemplate = HTMLDocParser .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument)); for (int i = 0; i < events.length(); i++) { final JSONObject eventJSONObject = new JSONObject(events.get(i).toString()); Double.parseDouble(eventJSONObject.getString(LATITUDE)); Double.parseDouble(eventJSONObject.getString(LONGITUDE)); final String eventName = eventJSONObject.getString("title"); final String eventUrl = eventJSONObject.getString("url"); final String eventDate = eventJSONObject.getString("start_time"); final String eventVenue = eventJSONObject.getString("venue_name"); Loggers.debug("Event name:" + eventName); eventList .append(eventTemplate .replace("_name_link_", !(("" + eventUrl).isEmpty()) ? eventUrl : ("https://www.google.com/search?q=" + eventName .replaceAll(" ", "+").replaceAll("-", "+"))) .replace("_place_link_", "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C" + _read.getLatitude().toString() + "," + _read.getLongitude().toString()) .replace("_name_", eventName).replace("_place_", eventVenue) .replace("_date_", eventDate)); } } catch (final Throwable t) { Loggers.error("Error appending Eventful data to Geohash Subscriber", t); } } {//Foursquare try { _simpleDateFormat.format(_week.getTime()); final JSONObject jsonObject = Modules.getModules().getEventulFactory() .getInstance("https://api.foursquare.com/v2/venues/explore") .get("", new HashMap<String, String>() { {//Don't worry, this is a static initializer of this map :) put("ll", "" + _read.getLatitude() + "," + _read.getLongitude()); put("radius", "" + 50000);//meters put("intent", "browse"); put("section", "topPicks"); put("client_secret", "PODRX5YWBSLAKAYRQ5CLPEPS3WHCXWFIJ3LXF3AKH4U1BDNI"); put("client_id", "25JZAK3TQPLIPUUXPIJWXQ5NSKSPTP4SYZLUZSCTZF3UJ4YX"); } } ); Loggers.debug("Foursquare Reply:" + jsonObject.toString()); final JSONArray referralArray = jsonObject.getJSONObject("response") .getJSONArray("groups").getJSONObject(0).getJSONArray("items"); final Document eventTemplateDocument = HTMLDocParser .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_PLACE); final String eventTemplate = HTMLDocParser .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument)); for (int i = 0; i < referralArray.length(); i++) { final JSONObject referral = referralArray.getJSONObject(i); referral.getJSONObject("venue").getJSONObject("location").getDouble("lng"); referral.getJSONObject("venue").getJSONObject("location").getDouble("lat"); final String eventName = referral.getJSONObject("venue").getString("name"); final String eventUrl = referral.getJSONObject("venue").optString("url"); final String eventVenue = referral.getJSONObject("venue").getJSONObject("location") .getString("address"); Loggers.debug("Event name:" + eventName); eventList .append(eventTemplate .replace("_name_link_", !(("" + eventUrl).isEmpty()) ? eventUrl : ("https://www.google.com/search?q=" + eventName .replaceAll(" ", "+").replaceAll("-", "+"))) .replace("_place_link_", "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C" + _read.getLatitude().toString() + "," + _read.getLongitude().toString()) .replace("_name_", eventName).replace("_place_", eventVenue) .replace("_date_", eventName)); } } catch (final Throwable t) { Loggers.error("Error appending Foursquare data to Geohash Subscriber", t); } } final String template = HTMLDocParser .getDocumentAsString(RBGet.getGlobalConfigKey("PAGEFILES") + EMAIL_FRAME); final Document email = HTMLDocParser .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL); final String _content = HTMLDocParser.convertNodeToHtml(HTMLDocParser.$("content", email)); final Parameter _unsubscribeLink = new Parameter("http://www.ilikeplaces.com/unsubscribe/") .append(Unsubscribe.TYPE, Unsubscribe.Type.GeohashSubscribe.name(), true) .append(Unsubscribe.VALUE, rowKey); final String finalEmail = template.replace("_FrameContent_", _content.replace(" ___||_", eventList.toString()).replace("_unsubscribe_link_", _unsubscribeLink.get())); Loggers.debug("Final email:" + finalEmail); sendMailLocal.sendAsHTML(_read.getEmailId().toString(), "Thank God it's Friday!", finalEmail); } } _geohashSubscriberHBaseCrudService.scan(new GeohashSubscriber(), _scanner); } Loggers.debug("Completed scanner"); }
From source file:com.amossys.hooker.common.InterceptEvent.java
/** * @return/* w w w . j a v a 2 s . com*/ */ public String toJson() { JSONObject object = new JSONObject(); try { // object.put("IdEvent", this.getIdEvent().toString()); object.put("Timestamp", this.getTimestamp()); object.put("RelativeTimestamp", this.getRelativeTimestamp()); object.put("HookerName", this.getHookerName()); object.put("IntrusiveLevel", this.getIntrusiveLevel()); object.put("InstanceID", this.getInstanceID()); object.put("PackageName", this.getPackageName()); object.put("ClassName", this.getClassName()); object.put("MethodName", this.getMethodName()); JSONArray parameters = new JSONArray(); if (this.getParameters() != null) { for (Entry<String, String> parameter : this.getParameters()) { JSONObject jsonParameter = new JSONObject(); jsonParameter.put("ParameterType", parameter.getKey()); jsonParameter.put("ParameterValue", parameter.getValue()); parameters.put(jsonParameter); } } object.put("Parameters", parameters); JSONObject returns = new JSONObject(); if (this.getReturns() != null) { returns.put("ReturnType", this.getReturns().getKey()); returns.put("ReturnValue", this.getReturns().getValue()); } object.put("Return", returns); JSONArray data = new JSONArray(); if (this.getData() != null) { for (String dataName : this.getData().keySet()) { if (dataName != null && this.getData().get(dataName) != null) { JSONObject dataP = new JSONObject(); dataP.put("DataName", dataName); dataP.put("DataValue", this.getData().get(dataName)); } } } object.put("Data", data); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return object.toString(); }
From source file:io.fabric8.kubernetes.api.Controller.java
private String convertYamlToJson(String yamlString) throws FileNotFoundException { Yaml yaml = new Yaml(); Map<String, Object> map = (Map<String, Object>) yaml.load(yamlString); JSONObject jsonObject = new JSONObject(map); return jsonObject.toString(); }
From source file:io.fabric8.kubernetes.api.Controller.java
private String convertYamlToJson(File yamlFile) throws FileNotFoundException { Yaml yaml = new Yaml(); FileInputStream fstream = new FileInputStream(yamlFile); Map<String, Object> map = (Map<String, Object>) yaml.load(fstream); JSONObject jsonObject = new JSONObject(map); return jsonObject.toString(); }
From source file:net.dv8tion.jda.core.handle.GuildCreateHandler.java
@Override protected Long handleInternally(JSONObject content) { Guild g = api.getGuildById(content.getLong("id")); Boolean wasAvail = (g == null || g.getName() == null) ? null : g.isAvailable(); api.getEntityBuilder().createGuildFirstPass(content, guild -> { if (guild.isAvailable()) { if (!api.getClient().isReady()) { api.getClient().<ReadyHandler>getHandler("READY").guildSetupComplete(guild); } else { if (wasAvail == null) //didn't exist {//from w w w .j ava 2s. co m api.getEventManager().handle(new GuildJoinEvent(api, responseNumber, guild)); api.getEventCache().playbackCache(EventCache.Type.GUILD, guild.getIdLong()); } else if (!wasAvail) //was previously unavailable { api.getEventManager().handle(new GuildAvailableEvent(api, responseNumber, guild)); } else { throw new RuntimeException("Got a GuildCreateEvent for a guild that already existed! Json: " + content.toString()); } } } else { if (!api.getClient().isReady()) { api.getClient().<ReadyHandler>getHandler("READY").acknowledgeGuild(guild, false, false, false); } else { //Proper GuildJoinedEvent is fired when guild was populated api.getEventManager() .handle(new UnavailableGuildJoinedEvent(api, responseNumber, guild.getIdLong())); } } }); return null; }