List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:net.zionsoft.obadiah.model.utils.AppUpdateChecker.java
@Override protected void onHandleIntent(Intent intent) { try {//from w w w. j a v a 2 s .c o m // we only check if at least 24 hours is passed final SharedPreferences preferences = getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE); final long now = System.currentTimeMillis(); final long lastCheckedTimestamp = preferences .getLong(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION_TIMESTAMP, 0); if (now - lastCheckedTimestamp < DateUtils.DAY_IN_MILLIS) { return; } // we only check if the user has active WiFi or WiMAX final NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)) .getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { return; } final int networkType = networkInfo.getType(); if (networkType != ConnectivityManager.TYPE_WIFI && networkType != ConnectivityManager.TYPE_WIMAX) { return; } final String response = new String(NetworkHelper.get(NetworkHelper.CLIENT_VERSION_URL), "UTF-8"); final JSONObject versionObject = new JSONObject(response); final int latestVersion = versionObject.getInt("versionCode"); final SharedPreferences.Editor editor = preferences.edit(); if (latestVersion < preferences.getInt(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION, 0)) { editor.putInt(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION, latestVersion) .putBoolean(Constants.PREF_KEY_ASKED_APPLICATION_UPDATE, false); } editor.putLong(Constants.PREF_KEY_CHECKED_APPLICATION_VERSION_TIMESTAMP, now).apply(); } catch (Exception e) { Crashlytics.logException(e); } }
From source file:com.trellmor.berrytube.ChatMessage.java
/** * Constructs a <code>ChatMessage</code> from an <code>JSONObject</code> * //w ww.j a v a 2s .c om * @param message * <code>JSONObject<code> containing all the required fields to form a chat message * @throws JSONException */ public ChatMessage(JSONObject message) throws JSONException { mNick = message.getString("nick"); mMsg = message.getString("msg"); mMulti = message.getInt("multi"); mType = message.getInt("type"); // check emote if (message.has("emote") && message.get("emote") instanceof String) { String emote = message.getString("emote"); if (emote.compareTo("rcv") == 0) this.mEmote = EMOTE_RCV; else if (emote.compareTo("sweetiebot") == 0) this.mEmote = EMOTE_SWEETIEBOT; else if (emote.compareTo("spoiler") == 0) this.mEmote = EMOTE_SPOILER; else if (emote.compareTo("act") == 0) this.mEmote = EMOTE_ACT; else if (emote.compareTo("request") == 0) this.mEmote = EMOTE_REQUEST; else if (emote.compareTo("poll") == 0) this.mEmote = EMOTE_POLL; else if (emote.compareTo("drink") == 0) this.mEmote = EMOTE_DRINK; } else mEmote = 0; JSONObject metadata = message.getJSONObject("metadata"); mFlair = metadata.optInt("flair"); mFlaunt = metadata.optBoolean("nameflaunt"); try { this.mTimeStamp = TIMESTAMP_FORMAT.parse(message.getString("timestamp")).getTime(); } catch (ParseException pe) { Log.w(TAG, "Error parsing timestamp string"); this.mTimeStamp = System.currentTimeMillis(); } this.mHidden = (this.mEmote == EMOTE_SPOILER); }
From source file:de.jaetzold.philips.hue.HueLightBulb.java
void parseLight(JSONObject lightJson) { name = lightJson.getString("name"); if (lightJson.has("state")) { final JSONObject state = lightJson.getJSONObject("state"); on = state.getBoolean("on"); brightness = state.getInt("bri"); hue = state.getInt("hue"); saturation = state.getInt("sat"); ciex = state.getJSONArray("xy").getDouble(0); ciey = state.getJSONArray("xy").getDouble(1); colorTemperature = state.getInt("ct"); colorMode = new ColorMode[] { HS, XY, CT }[Arrays.asList("hs", "xy", "ct") .indexOf(state.getString("colormode").toLowerCase())]; final Effect effect = Effect.fromName(state.getString("effect")); if (effect == null) { throw new HueCommException("Can not find effect named \"" + state.getString("effect") + "\""); }/*w ww. j a v a 2s . com*/ this.effect = effect; lastSyncTime = System.currentTimeMillis(); } else { sync(); } }
From source file:com.github.khandroid.rest.RestResponseParser.java
public RestResponse parse(String response) throws MalformedResponseException { try {/*w w w . j a v a2 s. co m*/ JSONObject respJson = new JSONObject(response); int status = respJson.getInt("status"); if (status == RestResponse.RESPONSE_STATUS_OK || status == RestResponse.RESPONSE_STATUS_ERR) { int tmpResponseCode = respJson.getInt("response_code"); int responseCode = tmpResponseCode; String payload = respJson.getString("payload"); return new RestResponse(status, responseCode, payload); } else { throw new MalformedResponseException("Invalid status returned from server ;" + status); } } catch (JSONException e) { throw new MalformedResponseException("Unable to interpret the string as JSON data strcuture.", e); } }
From source file:com.atolcd.alfresco.ProxyAuditFilter.java
@Override public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain) throws IOException, ServletException { // Get the HTTP request/response/session HttpServletRequest request = (HttpServletRequest) sReq; // HttpServletResponse response = (HttpServletResponse) sRes; RequestWrapper requestWrapper = new RequestWrapper(request); // Initialize a new request context RequestContext context = ThreadLocalRequestContext.getRequestContext(); String referer = request.getHeader("referer"); if (context == null) { try {/* w w w. ja v a 2 s . c om*/ // Perform a "silent" init - i.e. no user creation or remote // connections context = RequestContextUtil.initRequestContext(getApplicationContext(), request, true); try { RequestContextUtil.populateRequestContext(context, request); } catch (ResourceLoaderException e) { // e.printStackTrace(); } catch (UserFactoryException e) { // e.printStackTrace(); } } catch (RequestContextException ex) { throw new ServletException(ex); } } User user = context.getUser(); String requestURI = request.getRequestURI(); String method = request.getMethod().toUpperCase(); if (user != null) { try { JSONObject auditSample = new JSONObject(); auditSample.put(AUDIT_ID, "0"); auditSample.put(AUDIT_USER_ID, user.getId()); auditSample.put(AUDIT_SITE, ""); auditSample.put(AUDIT_APP_NAME, ""); auditSample.put(AUDIT_ACTION_NAME, ""); auditSample.put(AUDIT_OBJECT, ""); auditSample.put(AUDIT_TIME, Long.toString(System.currentTimeMillis())); // For documents only (only in sites!) if (requestURI.endsWith("/doclib/activity") && request.getMethod().equals(POST)) { String type = request.getContentType().split(";")[0]; if (type.equals("application/json")) { // Get JSON Object JSONObject activityFeed = new JSONObject(requestWrapper.getStringContent()); String activityType = activityFeed.getString("type"); if (activityType != null) { if ("file-added".equals(activityType) || ("file-updated".equals(activityType) && (referer != null && !referer.contains("document-details"))) // Done in JavaScript on "document-details" page || "file-deleted".equals(activityType)) { if (activityFeed.has("nodeRef")) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_SITE, activityFeed.getString("site")); auditSample.put(AUDIT_ACTION_NAME, activityType); auditSample.put(AUDIT_OBJECT, activityFeed.getString("nodeRef")); auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); remoteCall(request, auditSample); } } else if ("files-added".equals(activityType) || "files-deleted".equals(activityType)) { // multiple file uploads/deletions (5 or more) Integer fileCount = activityFeed.getInt("fileCount"); if (fileCount != null && fileCount > 0) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_SITE, activityFeed.getString("site")); auditSample.put(AUDIT_ACTION_NAME, "file-" + activityType.split("-")[1]); auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); // auditSample.put(AUDIT_OBJECT, ""); for (int i = 0; i < fileCount; i++) { remoteCall(request, auditSample); } } } } } } else if (requestURI.startsWith(URI_NODE_UPDATE) && requestURI.endsWith(FORMPROCESSOR)) { JSONObject updatedData = new JSONObject(requestWrapper.getStringContent()); // Online edit used the same form (plus the cm_content // metadata) if (!updatedData.has("prop_cm_content")) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1)); auditSample.put(AUDIT_ACTION_NAME, "update"); auditSample.put(AUDIT_SITE, TEMP_SITE); remoteCall(request, auditSample); } } else if (requestURI.endsWith("/activity/create")) { String jsonPost = requestWrapper.getStringContent(); if (jsonPost != null && !jsonPost.isEmpty()) { JSONObject json = new JSONObject(jsonPost); String mod = AuditHelper.extractModFromActivity(json); if (mod != null) { auditSample.put(AUDIT_APP_NAME, mod); auditSample.put(AUDIT_SITE, json.getString("site")); auditSample.put(AUDIT_ACTION_NAME, AuditHelper.extractActionFromActivity(json)); auditSample.put(AUDIT_OBJECT, json.getString("nodeRef")); remoteCall(request, auditSample); } } } else if (requestURI.equals(URI_UPLOAD)) { // XXX: issue with big files // Nothing to do - Insert request is done in JavaScript } else if (requestURI.endsWith("/comments") || requestURI.endsWith("/replies")) { // Comments & replies String[] urlTokens = request.getHeader("referer").toString().split("/"); HashMap<String, String> auditData = this.getUrlData(urlTokens); auditSample.put(AUDIT_SITE, auditData.get(KEY_SITE)); auditSample.put(AUDIT_APP_NAME, auditData.get(KEY_MODULE)); auditSample.put(AUDIT_ACTION_NAME, "comments"); auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1)); // Remote call for DB remoteCall(request, auditSample); } else if (requestURI.startsWith(URI_WIKI)) { String[] urlTokens = requestURI.split("/"); String wikiPageId = urlTokens[urlTokens.length - 1]; String siteId = urlTokens[urlTokens.length - 2]; if (method.equals(Method.PUT.toString().toString())) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_SITE, siteId); auditSample.put(AUDIT_APP_NAME, MOD_WIKI); if (params.has("currentVersion")) { auditSample.put(AUDIT_ACTION_NAME, "update-post"); } else { auditSample.put(AUDIT_ACTION_NAME, "create-post"); } String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_WIKI, wikiPageId); auditSample.put(AUDIT_OBJECT, auditObject); // Remote call remoteCall(request, auditSample); } else if (method.equals(DELETE)) { auditSample.put(AUDIT_SITE, siteId); auditSample.put(AUDIT_APP_NAME, MOD_WIKI); auditSample.put(AUDIT_ACTION_NAME, "delete-post"); auditSample.put(AUDIT_OBJECT, wikiPageId); // Remote call remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_BLOG)) { auditSample.put(AUDIT_APP_NAME, MOD_BLOG); if (method.equals(POST)) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_SITE, params.get("site")); auditSample.put(AUDIT_ACTION_NAME, "blog-create"); auditSample.put(AUDIT_OBJECT, params.get("title")); remoteCall(request, auditSample); } else if (method.equals(PUT)) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_SITE, params.get("site")); auditSample.put(AUDIT_ACTION_NAME, "blog-update"); auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0)); remoteCall(request, auditSample); } else if (method.equals(DELETE)) { String[] urlTokens = requestURI.split("/"); auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]); auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]); auditSample.put(AUDIT_ACTION_NAME, "blog-delete"); remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_DISCUSSIONS)) { auditSample.put(AUDIT_APP_NAME, "discussions"); if (method.equals(POST)) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_SITE, params.get("site")); auditSample.put(AUDIT_ACTION_NAME, "discussions-create"); auditSample.put(AUDIT_OBJECT, params.get("title")); remoteCall(request, auditSample); } else if (method.equals(PUT)) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); String siteId = (String) params.get("site"); auditSample.put(AUDIT_SITE, siteId); auditSample.put(AUDIT_ACTION_NAME, "discussions-update"); String[] urlTokens = requestURI.split("/"); String discussionId = urlTokens[urlTokens.length - 1]; String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, "discussions", discussionId); auditSample.put(AUDIT_OBJECT, auditObject); remoteCall(request, auditSample); } else if (method.equals(DELETE)) { String[] urlTokens = requestURI.split("/"); auditSample.put(AUDIT_ACTION_NAME, "discussions-deleted"); auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]); auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]); remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_LINKS) && !method.equals(GET)) { String[] urlTokens = requestURI.split("/"); JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_APP_NAME, MOD_LINKS); if (method.equals(POST)) { if (requestURI.startsWith(URI_LINKS + "delete/")) { auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]); auditSample.put(AUDIT_OBJECT, params.getJSONArray("items").get(0)); auditSample.put(AUDIT_ACTION_NAME, "links-delete"); } else { auditSample.put(AUDIT_OBJECT, params.get("title")); auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]); auditSample.put(AUDIT_ACTION_NAME, "links-create"); } remoteCall(request, auditSample); } else if (method.equals(PUT)) { String siteId = urlTokens[urlTokens.length - 3]; auditSample.put(AUDIT_SITE, siteId); auditSample.put(AUDIT_ACTION_NAME, "links-update"); String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_LINKS, urlTokens[urlTokens.length - 1]); auditSample.put(AUDIT_OBJECT, auditObject); remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_DOWNLOAD)) { String a = request.getParameter("a"); if (a != null && !a.isEmpty()) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1)); auditSample.put(AUDIT_ACTION_NAME, "true".equalsIgnoreCase(a) ? "download" : "stream"); auditSample.put(AUDIT_SITE, TEMP_SITE); remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_ACTION)) { // XXX: done in JavaScript } else if (requestURI.endsWith("memberships") && method.equals(GET)) { String type = request.getParameter("authorityType"); String nf = request.getParameter("nf"); String[] urlTokens = requestURI.split("/"); auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]); auditSample.put(AUDIT_APP_NAME, MOD_MEMBERS); auditSample.put(AUDIT_ACTION_NAME, type.toLowerCase()); auditSample.put(AUDIT_OBJECT, nf); remoteCall(request, auditSample); } else if (requestURI.endsWith(URI_CALENDAR)) { JSONObject params = new JSONObject(requestWrapper.getStringContent()); auditSample.put(AUDIT_APP_NAME, MOD_CALENDAR); auditSample.put(AUDIT_ACTION_NAME, "create"); auditSample.put(AUDIT_SITE, params.get("site")); auditSample.put(AUDIT_OBJECT, params.get("what")); remoteCall(request, auditSample); } else if ((requestURI.startsWith(URI_DATALIST) || requestURI.startsWith(URI_DATALIST_DELETE)) && method.equals(POST)) { boolean isDeleteRequest = request.getParameter("alf_method") != null; auditSample.put(AUDIT_APP_NAME, MOD_DATA); auditSample.put(AUDIT_SITE, TEMP_SITE); if (isDeleteRequest) { auditSample.put(AUDIT_ACTION_NAME, "datalist-delete"); JSONObject params = new JSONObject(requestWrapper.getStringContent()); JSONArray items = params.getJSONArray("nodeRefs"); for (int i = 0; i < items.length(); i++) { auditSample.put(AUDIT_OBJECT, items.getString(i)); remoteCall(request, auditSample); } } else { auditSample.put(AUDIT_ACTION_NAME, "datalist-post"); auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0)); remoteCall(request, auditSample); } } else if (requestURI.startsWith(URI_SOCIAL_PUBLISHING) && method.equals(POST)) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_SITE, TEMP_SITE); auditSample.put(AUDIT_ACTION_NAME, "publish"); JSONObject params = new JSONObject(requestWrapper.getStringContent()); JSONArray items = params.getJSONArray("publishNodes"); for (int i = 0; i < items.length(); i++) { auditSample.put(AUDIT_OBJECT, items.getString(i)); remoteCall(request, auditSample); } } else if (requestURI.indexOf("/ratings") != -1) { auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT); auditSample.put(AUDIT_SITE, TEMP_SITE); int offset = 1; if (POST.equals(method)) { auditSample.put(AUDIT_ACTION_NAME, "rate"); } else if (DELETE.equals(method)) { auditSample.put(AUDIT_ACTION_NAME, "unrate"); offset = 2; } auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, offset)); remoteCall(request, auditSample); } } catch (JSONException e) { logger.error("JSON Error during a remote call ..."); if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } } } chain.doFilter(requestWrapper, sRes); }
From source file:com.norman0406.slimgress.API.Common.Location.java
public Location(JSONObject json) throws JSONException { latitude = json.getInt("latE6"); longitude = json.getInt("lngE6"); }
From source file:drusy.ui.panels.InternetStatePanel.java
private void updateConnectionInformation(final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_CONNECTION, output, "Fetching connection state", false); task.addListener(new HttpUtils.DownloadListener() { @Override/*from w ww . j ava 2 s .c om*/ public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); if (success == true) { JSONObject result = obj.getJSONObject("result"); int rateDown = result.getInt("rate_down"); int rateUp = result.getInt("rate_up"); String ipv4 = result.getString("ipv4"); String ipv6 = result.getString("ipv6"); String state = result.getString("state"); int bandwidth_up = result.getInt("bandwidth_up"); int bandwidth_down = result.getInt("bandwidth_down"); checkNotifs(rateDown, rateUp, bandwidth_down, bandwidth_up); downloadChartPanel.addDataValue(rateDown / 1000.0, bandwidth_down / 8000.0); uploadChartPanel.addDataValue(rateUp / 1000.0, bandwidth_up / 8000.0); ipv4ContentLabel.setText(ipv4); ipv6ContentLabel.setText(ipv6); connectionStateContentLabel.setText(state); downloadContentLabel.setText(String.valueOf(rateDown / 1000.0) + " ko/s"); maxDownloadContentLabel.setText(String.valueOf(bandwidth_down / 8000.0) + " ko/s"); uploadContentLabel.setText(String.valueOf(rateUp / 1000.0) + " ko/s"); maxUploadContentLabel.setText(String.valueOf(bandwidth_up / 8000.0) + " ko/s"); } else { String msg = obj.getString("msg"); Log.Debug("Freebox Connection State", msg); } if (updater != null) { updater.updated(); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Connection State", ex.getMessage()); if (updater != null) { updater.updated(); } } }); }
From source file:org.stockchart.StockChartView.java
public void load(String s) throws JSONException { reset();//from ww w .j a v a 2 s.co m JSONObject j = new JSONObject(s); if (j.has("areas")) { JSONArray areas = j.getJSONArray("areas"); for (int i = 0; i < areas.length(); i++) { JSONObject area = areas.getJSONObject(i); Area a = new Area(); a.fromJSONObject(area); fAreas.add(a); } } if (j.has("globalAxisRanges")) { JSONArray ranges = j.getJSONArray("globalAxisRanges"); for (int i = 0; i < ranges.length(); i++) { JSONObject range = ranges.getJSONObject(i); AxisRange ar = new AxisRange(); Axis.Side side = Axis.Side.valueOf(range.getString("side")); ar.fromJSONObject(range.getJSONObject("axisRange")); fGlobalRanges.put(side, ar); } } if (j.has("indicators")) { JSONArray indicators = j.getJSONArray("indicators"); fIndicatorManager.fromJSONArray(indicators); } fCrosshair.fromJSONObject(j.getJSONObject("crosshair")); fClearColor = j.getInt("clearColor"); }
From source file:at.alladin.rmbt.android.views.ResultGraphView.java
private void redraw(JSONArray result) { try {/*from w ww. java 2 s . c om*/ JSONObject curve = result.getJSONObject(0).getJSONObject("speed_curve"); if (curve != null) { uploadArray = curve.getJSONArray("upload"); downloadArray = curve.getJSONArray("download"); signalArray = curve.getJSONArray("signal"); } //System.out.println(signalArray); long maxTimeUpload = result.getJSONObject(0).optLong("time_ul_ms") + result.getJSONObject(0).optLong("duration_upload_ms"); long timeElapsed = Math.round((double) maxTimeUpload / 1000); if (signalGraph != null && signalArray != null && signalArray.length() > 0 && signalGraph.getGraphs().size() < 1) { Log.d("ResultGraphView", "DRAWING SIGNAL GRAPH\n" + signalArray); final long maxTimeSignal = signalArray.optJSONObject(signalArray.length() - 1) .optLong("time_elapsed"); final long timeElapsedMs = Math.max(maxTimeSignal, maxTimeUpload); timeElapsed = Math.round((double) timeElapsedMs / 1000); signalGraph.getLabelHMaxList().clear(); signalGraph.addLabelHMax(String.valueOf(timeElapsed < 7 ? 7 : timeElapsed)); signalGraph.updateGrid((int) timeElapsed, 4); /* [{"network_type":"WLAN","time_elapsed":0,"signal_strength":-56}, * {"network_type":"WLAN","time_elapsed":10121,"signal_strength":-55}, * {"network_type":"WLAN","time_elapsed":37478,"signal_strength":-57}] */ MinMax<Integer> signalBoundsRsrp = NetworkUtil .getSignalStrengthBounds(InformationCollector.SINGAL_TYPE_RSRP); MinMax<Integer> signalBoundsWlan = NetworkUtil .getSignalStrengthBounds(InformationCollector.SINGAL_TYPE_WLAN); MinMax<Integer> signalBoundsMobile = NetworkUtil .getSignalStrengthBounds(InformationCollector.SINGAL_TYPE_MOBILE); List<GraphService> signalList = new ArrayList<GraphService>(); boolean has4G = false; boolean has3G = false; boolean hasWlan = false; String lastNetworkType = ""; String lastCatTechnology = ""; GraphService curGraph = null; double prevValue = 0d; boolean hasSignalCategoryChanged = false; double lastLabelYPosition = -1d; double time = 0d; double signalChangeStartTime = 0d; double value = 0d; double oldValidValue = 0d; System.out.println("MAXTIME: " + timeElapsedMs); for (int i = 0; i < signalArray.length(); i++) { JSONObject signalObject = signalArray.getJSONObject(i); String networkType = signalObject.optString("network_type"); String catTechnology = signalObject.optString("cat_technology"); //set proper signal strength attribute String signalAttribute = "signal_strength"; String signalColor = "#ffffff"; time = i > 0 ? ((double) signalObject.getInt("time_elapsed") / (double) timeElapsedMs) : 0d; oldValidValue = value > 0d ? value : oldValidValue; if ("LTE".equals(networkType)) { if (!lastNetworkType.equals(networkType) && !lastCatTechnology.equals(catTechnology)) { if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } GraphService newGraph = StaticGraph.addGraph(signalGraph, Color.parseColor(COLOR_SIGNAL_4G), signalArray.length() == 1 ? true : false); signalList.add(newGraph); if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } signalChangeStartTime = time; hasSignalCategoryChanged = true; curGraph = newGraph; } has4G = true; signalAttribute = "lte_rsrp"; signalColor = COLOR_SIGNAL_4G; value = getRelativeSignal(signalBoundsRsrp, signalAttribute, signalObject); } else if ("WLAN".equals(networkType)) { if (!lastNetworkType.equals(networkType) && !lastCatTechnology.equals(catTechnology)) { if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } GraphService newGraph = StaticGraph.addGraph(signalGraph, Color.parseColor(COLOR_SIGNAL_WLAN), signalArray.length() == 1 ? true : false); signalList.add(newGraph); if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } signalChangeStartTime = time; hasSignalCategoryChanged = true; curGraph = newGraph; } hasWlan = true; signalAttribute = "signal_strength"; signalColor = COLOR_SIGNAL_WLAN; value = getRelativeSignal(signalBoundsWlan, signalAttribute, signalObject); } else { if (!lastNetworkType.equals(networkType)) { signalChangeStartTime = time; hasSignalCategoryChanged = true; if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } if ((!lastCatTechnology.equals(catTechnology)) && ("4G".equals(lastCatTechnology) || "WLAN".equals(lastCatTechnology) || "".equals(lastCatTechnology))) { GraphService newGraph = StaticGraph.addGraph(signalGraph, Color.parseColor(COLOR_SIGNAL_3G), signalArray.length() == 1 ? true : false); signalList.add(newGraph); if (curGraph != null) { curGraph.addValue((1 - prevValue), time); } curGraph = newGraph; } } has3G = true; signalAttribute = "signal_strength"; signalColor = COLOR_SIGNAL_3G; value = getRelativeSignal(signalBoundsMobile, signalAttribute, signalObject); } if (value > 0d) { System.out.println("SIGNAL: " + value + "@" + time + " = " + signalObject); if (value >= 0d && curGraph != null) { if (hasSignalCategoryChanged) { curGraph.addValue((1 - value), signalChangeStartTime); hasSignalCategoryChanged = false; if (lastLabelYPosition == -1d) { lastLabelYPosition = (float) (1 - (value > 0d ? value : prevValue)); } else { if (Math.abs(signalChangeStartTime - time) < .125d) { float curPosition = (float) (1 - (value > 0d ? value : prevValue)); if (Math.abs(curPosition - lastLabelYPosition) <= .11d) { lastLabelYPosition = curPosition + (curPosition > lastLabelYPosition ? +.1d : -.1d); } else { lastLabelYPosition = curPosition; } } else { lastLabelYPosition = (float) (1 - (value > 0d ? value : prevValue)); } } //lastLabelXPosition = (float) time; double labelDiff = lastLabelYPosition - (1 - value); System.out.println("i" + i + " -> " + lastLabelYPosition + " : " + (1 - value) + " diff: " + Math.abs(labelDiff) + " istoolow (<.09d)? " + (Math.abs(labelDiff) < .09d)); if (Math.abs(labelDiff) < .09d && i == 0) { if (labelDiff < 0d) { lastLabelYPosition = lastLabelYPosition < .50d ? lastLabelYPosition - .075d : lastLabelYPosition + .075d; } else { lastLabelYPosition = lastLabelYPosition < .50d ? lastLabelYPosition + .075d : lastLabelYPosition - .075d; } } signalGraph.addLabel((float) signalChangeStartTime, (float) lastLabelYPosition, networkType, signalColor); } //System.out.println("ADDING VALUE TO GRAPH " + (1 - value) + " on: " + time); curGraph.addValue((1 - value), time); prevValue = value; } } lastNetworkType = networkType; lastCatTechnology = catTechnology; } //draw signal graph to the end if (prevValue > 0 && curGraph != null) { curGraph.addValue((1 - prevValue), 1f); } signalGraph.clearLabels(CustomizableGraphView.LABELLIST_VERTICAL_MAX); signalGraph.clearLabels(CustomizableGraphView.LABELLIST_VERTICAL_MIN); if (has3G) { signalGraph.addLabelVMax(String.valueOf(signalBoundsMobile.max), COLOR_SIGNAL_3G); signalGraph.addLabelVMin(String.valueOf(signalBoundsMobile.min), COLOR_SIGNAL_3G); } if (has4G) { signalGraph.addLabelVMax(String.valueOf(signalBoundsRsrp.max), COLOR_SIGNAL_4G); signalGraph.addLabelVMin(String.valueOf(signalBoundsRsrp.min), COLOR_SIGNAL_4G); } if (hasWlan) { signalGraph.addLabelVMax(String.valueOf(signalBoundsWlan.max), COLOR_SIGNAL_WLAN); signalGraph.addLabelVMin(String.valueOf(signalBoundsWlan.min), COLOR_SIGNAL_WLAN); } //signalGraph.repaint(getContext()); } else if (signalGraph != null && signalGraph.getGraphs().size() > 0) { Log.d("ResultGraphView", "REDRAWING SIGNAL GRAPH"); //signalGraph.repaint(getContext()); signalGraph.invalidate(); } signalProgress.setVisibility(View.GONE); if (uploadArray != null && uploadArray != null && uploadArray.length() > 0 && ulGraph.getGraphs().size() < 1) { Log.d("ResultGraphView", "DRAWING UL GRAPH"); drawCurve(uploadArray, ulGraph, COLOR_UL_GRAPH, String .valueOf(Math.round(result.getJSONObject(0).optDouble("duration_upload_ms") / 1000d))); addStaticMarker(signalArray, signalGraph, COLOR_UL_GRAPH, 70, result.getJSONObject(0).optDouble("time_ul_ms"), result.getJSONObject(0).optDouble("time_ul_ms") + result.getJSONObject(0).optDouble("duration_upload_ms"), timeElapsed * 1000); double timeUl = result.getJSONObject(0).optDouble("duration_upload_ms"); long timeElapsedUl = Math.round(timeUl / 1000); ulGraph.setRowLinesLabelList(SPEED_LABELS); ulGraph.updateGrid((int) timeElapsedUl, 4.5f); } else if (uploadArray.length() > 0 && ulGraph != null && ulGraph.getGraphs().size() > 0) { Log.d("ResultGraphView", "REDRAWING UL GRAPH"); //ulGraph.repaint(getContext()); ulGraph.invalidate(); } ulProgress.setVisibility(View.GONE); if (downloadArray != null && downloadArray != null && downloadArray.length() > 0 && dlGraph.getGraphs().size() < 1) { Log.d("ResultGraphView", "DRAWING DL GRAPH"); drawCurve(downloadArray, dlGraph, COLOR_DL_GRAPH, String .valueOf(Math.round(result.getJSONObject(0).optDouble("duration_download_ms") / 1000d))); addStaticMarker(signalArray, signalGraph, COLOR_DL_GRAPH, 70, result.getJSONObject(0).optDouble("time_dl_ms"), result.getJSONObject(0).optDouble("time_dl_ms") + result.getJSONObject(0).optDouble("duration_download_ms"), timeElapsed * 1000); double timeDl = result.getJSONObject(0).optDouble("duration_download_ms"); long timeElapsedDl = Math.round(timeDl / 1000); dlGraph.setRowLinesLabelList(SPEED_LABELS); dlGraph.updateGrid((int) timeElapsedDl, 4.5f); } else if (downloadArray.length() > 0 && dlGraph != null && dlGraph.getGraphs().size() > 0) { Log.d("ResultGraphView", "REDRAWING DL GRAPH"); //dlGraph.repaint(getContext()); dlGraph.invalidate(); } dlProgress.setVisibility(View.GONE); } catch (Exception e) { if (signalGraph != null) { signalGraph.invalidate(); } if (ulGraph != null) { ulGraph.invalidate(); } if (dlGraph != null) { dlGraph.invalidate(); } e.printStackTrace(); //TODO show no data available view } }
From source file:at.alladin.rmbt.android.views.ResultGraphView.java
public double getRelativeSignal(final MinMax<Integer> signalBounds, final String signalAttribute, final JSONObject signalObject) throws JSONException { final int signal = signalObject.getInt(signalAttribute); final double value = signal < 0 ? ((double) (signal - signalBounds.max) / (double) (signalBounds.min - signalBounds.max)) : signal;// w ww . ja v a 2 s . c o m System.out.println("signalAttrib: " + signalAttribute + ", signal: " + signal + " value: " + value); return value; }