List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.appdynamics.monitors.nginx.statsExtractor.ConnectionsStatsExtractor.java
private Map<String, String> getConnectionStats(JSONObject connections) { Map<String, String> connectionStats = new HashMap<String, String>(); long accepted = connections.getLong("accepted"); connectionStats.put("connections|accepted", String.valueOf(accepted)); long dropped = connections.getLong("dropped"); connectionStats.put("connections|dropped", String.valueOf(dropped)); long active = connections.getLong("active"); connectionStats.put("connections|active", String.valueOf(active)); long idle = connections.getLong("idle"); connectionStats.put("connections|idle", String.valueOf(idle)); return connectionStats; }
From source file:de.hackerspacebremen.format.JSONFormatter.java
@Override public T reformat(final String object, final Class<T> entityClass) throws FormatException { T result = null;/*from ww w . ja v a 2 s . c om*/ final Map<String, Field> fieldMap = new HashMap<String, Field>(); if (entityClass.isAnnotationPresent(Entity.class)) { final Field[] fields = entityClass.getDeclaredFields(); for (final Field field : fields) { if (field.isAnnotationPresent(FormatPart.class)) { fieldMap.put(field.getAnnotation(FormatPart.class).key(), field); } } try { final JSONObject json = new JSONObject(object); result = entityClass.newInstance(); for (final String key : fieldMap.keySet()) { if (json.has(key)) { final Field field = fieldMap.get(key); final Method method = entityClass.getMethod(this.getSetter(field.getName()), new Class<?>[] { field.getType() }); final String type = field.getType().toString(); if (type.equals("class com.google.appengine.api.datastore.Key")) { method.invoke(result, KeyFactory.stringToKey(json.getString(key))); } else if (type.equals("class com.google.appengine.api.datastore.Text")) { method.invoke(result, new Text(json.getString(key))); } else if (type.equals("boolean")) { method.invoke(result, json.getBoolean(key)); } else if (type.equals("long")) { method.invoke(result, json.getLong(key)); } else if (type.equals("int")) { method.invoke(result, json.getInt(key)); } else { method.invoke(result, json.get(key)); } } } } catch (JSONException e) { logger.warning("JSONException occured: " + e.getMessage()); throw new FormatException(); } catch (NoSuchMethodException e) { logger.warning("NoSuchMethodException occured: " + e.getMessage()); throw new FormatException(); } catch (SecurityException e) { logger.warning("SecurityException occured: " + e.getMessage()); throw new FormatException(); } catch (IllegalAccessException e) { logger.warning("IllegalAccessException occured: " + e.getMessage()); throw new FormatException(); } catch (IllegalArgumentException e) { logger.warning("IllegalArgumentException occured: " + e.getMessage()); throw new FormatException(); } catch (InvocationTargetException e) { logger.warning("InvocationTargetException occured: " + e.getMessage()); throw new FormatException(); } catch (InstantiationException e) { logger.warning("InstantiationException occured: " + e.getMessage()); throw new FormatException(); } } return result; }
From source file:org.openqa.selenium.logging.SessionLogs.java
public static SessionLogs fromJSON(JSONObject rawSessionLogs) throws JSONException { SessionLogs sessionLogs = new SessionLogs(); for (Iterator logTypeItr = rawSessionLogs.keys(); logTypeItr.hasNext();) { String logType = (String) logTypeItr.next(); JSONArray rawLogEntries = rawSessionLogs.getJSONArray(logType); List<LogEntry> logEntries = new ArrayList<LogEntry>(); for (int index = 0; index < rawLogEntries.length(); index++) { JSONObject rawEntry = rawLogEntries.getJSONObject(index); logEntries.add(new LogEntry(LogLevelMapping.toLevel(rawEntry.getString("level")), rawEntry.getLong("timestamp"), rawEntry.getString("message"))); }/*from www. ja v a 2 s. c om*/ sessionLogs.addLog(logType, new LogEntries(logEntries)); } return sessionLogs; }
From source file:com.bmwcarit.barefoot.roadmap.Road.java
/** * Creates a {@link Route} object from its JSON representation. * * @param json JSON representation of the {@link Route}. * @param map {@link RoadMap} object as the reference of {@link RoadPoint}s and {@link Road}s. * @return {@link Road} object./* w w w. j a va 2s . c om*/ * @throws JSONException thrown on JSON extraction or parsing error. */ public static Road fromJSON(JSONObject json, RoadMap map) throws JSONException { long baseid = json.getLong("road"); Road road = map .get(Heading.valueOf(json.getString("heading")) == Heading.forward ? baseid * 2 : baseid * 2 + 1); if (road == null) { throw new JSONException("road id " + json.getLong("road") + " not found"); } return road; }
From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java
private void deserializeKey(String key, Bundle bundle) throws JSONException { String jsonString = cache.getString(key, "{}"); JSONObject json = new JSONObject(jsonString); String valueType = json.getString(JSON_VALUE_TYPE); if (valueType.equals(TYPE_BOOLEAN)) { bundle.putBoolean(key, json.getBoolean(JSON_VALUE)); } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); boolean[] array = new boolean[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getBoolean(i); }/*from www. j a v a 2s. com*/ bundle.putBooleanArray(key, array); } else if (valueType.equals(TYPE_BYTE)) { bundle.putByte(key, (byte) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_BYTE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); byte[] array = new byte[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (byte) jsonArray.getInt(i); } bundle.putByteArray(key, array); } else if (valueType.equals(TYPE_SHORT)) { bundle.putShort(key, (short) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_SHORT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); short[] array = new short[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (short) jsonArray.getInt(i); } bundle.putShortArray(key, array); } else if (valueType.equals(TYPE_INTEGER)) { bundle.putInt(key, json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_INTEGER_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int[] array = new int[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getInt(i); } bundle.putIntArray(key, array); } else if (valueType.equals(TYPE_LONG)) { bundle.putLong(key, json.getLong(JSON_VALUE)); } else if (valueType.equals(TYPE_LONG_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); long[] array = new long[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getLong(i); } bundle.putLongArray(key, array); } else if (valueType.equals(TYPE_FLOAT)) { bundle.putFloat(key, (float) json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_FLOAT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); float[] array = new float[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (float) jsonArray.getDouble(i); } bundle.putFloatArray(key, array); } else if (valueType.equals(TYPE_DOUBLE)) { bundle.putDouble(key, json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); double[] array = new double[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getDouble(i); } bundle.putDoubleArray(key, array); } else if (valueType.equals(TYPE_CHAR)) { String charString = json.getString(JSON_VALUE); if (charString != null && charString.length() == 1) { bundle.putChar(key, charString.charAt(0)); } } else if (valueType.equals(TYPE_CHAR_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); char[] array = new char[jsonArray.length()]; for (int i = 0; i < array.length; i++) { String charString = jsonArray.getString(i); if (charString != null && charString.length() == 1) { array[i] = charString.charAt(0); } } bundle.putCharArray(key, array); } else if (valueType.equals(TYPE_STRING)) { bundle.putString(key, json.getString(JSON_VALUE)); } else if (valueType.equals(TYPE_STRING_LIST)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int numStrings = jsonArray.length(); ArrayList<String> stringList = new ArrayList<String>(numStrings); for (int i = 0; i < numStrings; i++) { Object jsonStringValue = jsonArray.get(i); stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue); } bundle.putStringArrayList(key, stringList); } else if (valueType.equals(TYPE_ENUM)) { try { String enumType = json.getString(JSON_VALUE_ENUM_TYPE); @SuppressWarnings({ "unchecked", "rawtypes" }) Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType); @SuppressWarnings("unchecked") Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE)); bundle.putSerializable(key, enumValue); } catch (ClassNotFoundException e) { } catch (IllegalArgumentException e) { } } }
From source file:com.atolcd.alfresco.AuditEntry.java
public AuditEntry(String json) throws JSONException { if (json != null && json.length() > 0) { JSONObject jsonObj = new JSONObject(json); this.id = jsonObj.getLong("id"); this.auditUserId = jsonObj.getString("auditUserId"); this.auditSite = jsonObj.getString("auditSite"); this.auditAppName = jsonObj.getString("auditAppName"); this.auditActionName = jsonObj.getString("auditActionName"); this.auditObject = jsonObj.getString("auditObject"); this.auditTime = jsonObj.getLong("auditTime"); }/*from ww w. j ava 2s . c om*/ }
From source file:pe.chalk.takoyaki.target.NaverCafe.java
public NaverCafe(JSONObject properties) { super(properties.getString("prefix"), properties.getLong("interval")); this.getFilters() .addAll(Utils.buildStream(String.class, properties.getJSONArray("filters")).map(filterName -> { switch (filterName) { case ArticleFilter.NAME: return new ArticleFilter(this); case CommentaryFilter.NAME: return new CommentaryFilter(this); case VisitationFilter.NAME: return new VisitationFilter(this); default: return null; }//from w w w.j a v a 2 s. c om }).filter(filter -> filter != null).collect(Collectors.toList())); this.staff = new Staff(this.getLogger(), properties.getInt("timeout"), properties.getJSONObject("naverAccount")); this.address = properties.getString("address"); this.contentUrl = String.format(STRING_CONTENT, this.getAddress()); try { Document contentDocument = Jsoup.parse(this.getStaff().parse(this.contentUrl)); this.setName(contentDocument.select("h1.d-none").text()); Matcher clubIdMatcher = NaverCafe.PATTERN_CLUB_ID .matcher(contentDocument.head().select("script:not([type]):not([src])").first().html()); if (!clubIdMatcher.find()) { throw new IllegalArgumentException(" ID ? : " + this.getName()); } this.clubId = Integer.parseInt(clubIdMatcher.group(1)); this.menus = contentDocument.select("a[id^=menuLink]").stream() .map(element -> new Menu(this, Integer.parseInt(element.id().substring(8)), element.text())) .collect(Collectors.toList()); this.articleUrl = String.format(STRING_ARTICLE, this.getClubId()); Files.write(Paths.get("Takoyaki-menus-" + this.getAddress() + ".log"), this.getMenus().stream().map(Menu::toString).collect(Collectors.toList()), StandardCharsets.UTF_8); } catch (IOException | JSONException e) { String errorMessage = "?? : " + e.getClass().getName() + ": " + e.getMessage(); this.getLogger().error(errorMessage); throw new IllegalStateException(errorMessage); } }
From source file:com.hichinaschool.flashcards.anki.CardEditor.java
@Override protected Dialog onCreateDialog(int id) { StyledDialog dialog = null;//from ww w.j a v a2s .com Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(this); switch (id) { case DIALOG_TAGS_SELECT: builder.setTitle(R.string.card_details_tags); builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mAddNote) { try { JSONArray ja = new JSONArray(); for (String t : selectedTags) { ja.put(t); } mCol.getModels().current().put("tags", ja); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } mEditorNote.setTags(selectedTags); } mCurrentTags = selectedTags; updateTags(); } }); builder.setNegativeButton(res.getString(R.string.cancel), null); mNewTagEditText = (EditText) new EditText(this); mNewTagEditText.setHint(R.string.add_new_tag); InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (source.charAt(i) == ' ' || source.charAt(i) == ',') { return ""; } } return null; } }; mNewTagEditText.setFilters(new InputFilter[] { filter }); ImageView mAddTextButton = new ImageView(this); mAddTextButton.setImageResource(R.drawable.ic_addtag); mAddTextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tag = mNewTagEditText.getText().toString(); if (tag.length() != 0) { if (mEditorNote.hasTag(tag)) { mNewTagEditText.setText(""); return; } selectedTags.add(tag); actualizeTagDialog(mTagsDialog); mNewTagEditText.setText(""); } } }); FrameLayout frame = new FrameLayout(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL); params.rightMargin = 10; mAddTextButton.setLayoutParams(params); frame.addView(mNewTagEditText); frame.addView(mAddTextButton); builder.setView(frame, false, true); dialog = builder.create(); mTagsDialog = dialog; break; case DIALOG_DECK_SELECT: ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogDeckIds = new ArrayList<Long>(); ArrayList<JSONObject> decks = mCol.getDecks().all(); Collections.sort(decks, new JSONNameComparator()); builder.setTitle(R.string.deck); for (JSONObject d : decks) { try { if (d.getInt("dyn") == 0) { dialogDeckItems.add(d.getString("name")); dialogDeckIds.add(d.getLong("id")); } } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items = new String[dialogDeckItems.size()]; dialogDeckItems.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long newId = dialogDeckIds.get(item); if (mCurrentDid != newId) { if (mAddNote) { try { // TODO: mEditorNote.setDid(newId); mEditorNote.model().put("did", newId); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } } mCurrentDid = newId; updateDeck(); } } }); dialog = builder.create(); mDeckSelectDialog = dialog; break; case DIALOG_MODEL_SELECT: ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogIds = new ArrayList<Long>(); ArrayList<JSONObject> models = mCol.getModels().all(); Collections.sort(models, new JSONNameComparator()); builder.setTitle(R.string.note_type); for (JSONObject m : models) { try { dialogItems.add(m.getString("name")); dialogIds.add(m.getLong("id")); } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items2 = new String[dialogItems.size()]; dialogItems.toArray(items2); builder.setItems(items2, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long oldModelId; try { oldModelId = mCol.getModels().current().getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } long newId = dialogIds.get(item); if (oldModelId != newId) { mCol.getModels().setCurrent(mCol.getModels().get(newId)); JSONObject cdeck = mCol.getDecks().current(); try { cdeck.put("mid", newId); } catch (JSONException e) { throw new RuntimeException(e); } mCol.getDecks().save(cdeck); int size = mEditFields.size(); String[] oldValues = new String[size]; for (int i = 0; i < size; i++) { oldValues[i] = mEditFields.get(i).getText().toString(); } setNote(); resetEditFields(oldValues); mTimerHandler.removeCallbacks(checkDuplicatesRunnable); duplicateCheck(false); } } }); dialog = builder.create(); break; case DIALOG_RESET_CARD: builder.setTitle(res.getString(R.string.reset_card_dialog_title)); builder.setMessage(res.getString(R.string.reset_card_dialog_message)); builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // for (long cardId : // mDeck.getCardsFromFactId(mEditorNote.getId())) { // mDeck.cardFromId(cardId).resetCard(); // } // mDeck.reset(); // setResult(Reviewer.RESULT_EDIT_CARD_RESET); // mCardReset = true; // Themes.showThemedToast(CardEditor.this, // getResources().getString( // R.string.reset_card_dialog_confirmation), true); } }); builder.setNegativeButton(res.getString(R.string.no), null); builder.setCancelable(true); dialog = builder.create(); break; case DIALOG_INTENT_INFORMATION: dialog = createDialogIntentInformation(builder, res); } return dialog; }
From source file:de.quadrillenschule.azocamsyncd.astromode_old.PhotoProjectProfile.java
public void fromJSONProfile(String jsonProfile, PhotoProject project) { photoSeries = new LinkedList<>(); try {/*from ww w. ja va2 s. c o m*/ JSONObject jsa = new JSONObject(jsonProfile); ReceivePhotoSerie[] psArray = new ReceivePhotoSerie[jsa.names().length()]; for (int i = 0; i < jsa.names().length(); i++) { JSONObject seriesArray = (JSONObject) jsa.get(jsa.names().getString(i)); ReceivePhotoSerie ps = new ReceivePhotoSerie(project); ps.setName(jsa.names().get(i).toString()); ps.setNumberOfPlannedPhotos(seriesArray.getInt(Columns.NUMBER_OF_PLANNED_PHOTOS.name())); ps.setExposureTimeInMs(seriesArray.getLong(Columns.EXPOSURE_TIME.name())); psArray[seriesArray.getInt("ORDER_NUMBER")] = ps; } for (ReceivePhotoSerie ps : psArray) { photoSeries.add(ps); } } catch (JSONException ex) { Logger.getLogger(PhotoProjectProfile.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.snappy.couchdb.CouchDBHelper.java
/** * Parse a single JSON object of Message type * /*from w w w .j av a2 s. co m*/ * @param json * @param image * @param voice * @return * @throws SpikaException * @throws JSONException * @throws IOException * @throws ClientProtocolException */ private static Message parseMessageObject(JSONObject json, boolean image, boolean voice, boolean video) throws ClientProtocolException, IOException, JSONException, SpikaException { Message message = new Message(); if (json == null) { return message; } if (json.has(Const.ERROR)) { appLogout(null, false, isInvalidToken(json)); return null; } try { message.setId(json.getString(Const._ID)); } catch (JSONException e) { message.setId(""); } try { message.setRev(json.getString(Const._REV)); } catch (JSONException e) { message.setRev(""); } try { message.setType(json.getString(Const.TYPE)); } catch (JSONException e) { message.setType(""); } try { message.setMessageType(json.getString(Const.MESSAGE_TYPE)); } catch (JSONException e) { message.setMessageType(""); } try { message.setMessageTargetType(json.getString(Const.MESSAGE_TARGET_TYPE)); } catch (JSONException e) { message.setMessageTargetType(""); } try { message.setBody(json.getString(Const.BODY)); } catch (JSONException e) { message.setBody(""); } try { message.setFromUserId(json.getString(Const.FROM_USER_ID)); } catch (JSONException e) { message.setFromUserId(""); } try { message.setFromUserName(json.getString(Const.FROM_USER_NAME)); } catch (JSONException e) { message.setFromUserName(""); } try { message.setToUserId(json.getString(Const.TO_USER_ID)); } catch (JSONException e) { message.setToUserId(""); } try { message.setToGroupName(json.getString(Const.TO_USER_NAME)); } catch (JSONException e) { message.setToGroupName(""); } try { message.setToGroupId(json.getString(Const.TO_GROUP_ID)); } catch (JSONException e) { message.setToGroupId(""); } try { message.setToGroupName(json.getString(Const.TO_GROUP_NAME)); } catch (JSONException e) { message.setToGroupName(""); } try { message.setCreated(json.getLong(Const.CREATED)); } catch (JSONException e) { return null; } try { message.setModified(json.getLong(Const.MODIFIED)); } catch (JSONException e) { return null; } try { message.setValid(json.getBoolean(Const.VALID)); } catch (JSONException e) { message.setValid(true); } try { message.setAttachments(json.getJSONObject(Const.ATTACHMENTS).toString()); } catch (JSONException e) { message.setAttachments(""); } try { message.setLatitude(json.getString(Const.LATITUDE)); } catch (JSONException e) { message.setLatitude(""); } try { message.setLongitude(json.getString(Const.LONGITUDE)); } catch (JSONException e) { message.setLongitude(""); } try { message.setImageFileId((json.getString(Const.PICTURE_FILE_ID))); } catch (JSONException e) { message.setImageFileId(""); } try { message.setImageThumbFileId((json.getString(Const.PICTURE_THUMB_FILE_ID))); } catch (JSONException e) { message.setImageThumbFileId(""); } try { message.setVideoFileId((json.getString(Const.VIDEO_FILE_ID))); } catch (JSONException e) { message.setVideoFileId(""); } try { message.setVoiceFileId((json.getString(Const.VOICE_FILE_ID))); } catch (JSONException e) { message.setVoiceFileId(""); } try { message.setEmoticonImageUrl(json.getString(Const.EMOTICON_IMAGE_URL)); } catch (JSONException e) { message.setEmoticonImageUrl(""); } try { message.setAvatarFileId(json.getString(Const.AVATAR_THUMB_FILE_ID)); } catch (JSONException e) { message.setAvatarFileId(""); } try { message.setDeleteType(json.getInt(Const.DELETE_TYPE)); } catch (JSONException e) { message.setDeleteType(0); } try { message.setDelete(json.getInt(Const.DELETE_AT)); } catch (JSONException e) { message.setDelete(0); } try { message.setReadAt(json.getInt(Const.READ_AT)); } catch (JSONException e) { message.setReadAt(0); } try { message.setCommentCount(json.getInt(Const.COMMENT_COUNT)); } catch (JSONException e) { message.setCommentCount(0); } // if (image || video || voice) { // message.setCommentCount(CouchDB.getCommentCount(message.getId())); // } return message; }