List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:de.liedtke.format.JSONFormatter.java
@Override public <T extends BasicEntity> T reformat(final String object, final Class<T> entityClass) throws FormatException { T result = null;/*from ww w. j a v a2 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() }); if (FindInterface.class.isAssignableFrom(field.getType())) { final Method find = field.getType().getMethod("find", new Class<?>[] { String.class }); if (find != null) { final Object enumObject = find.invoke(Enum.class, json.get(key)); method.invoke(result, enumObject); } } else { 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:fr.pasteque.client.sync.SyncUpdate.java
private void parseProducts(JSONObject resp) { try {/*from w w w . j a va 2 s .co m*/ JSONArray array = resp.getJSONArray("content"); try { ImagesData.clearProducts(this.ctx); } catch (IOException e) { Log.w(LOG_TAG, "Unable to clear product images", e); } for (int i = 0; i < array.length(); i++) { JSONObject o = array.getJSONObject(i); String taxCatId = o.getString("taxCatId"); String taxId = this.taxIds.get(taxCatId); double taxRate = this.taxRates.get(taxCatId); Product p = Product.fromJSON(o, taxId, taxRate); if (o.getBoolean("hasImage")) { // TODO: call for image /*String image64 = o.getString("image"); try { byte[] data = Base64.decode(image64); ImagesData.storeProductImage(this.ctx, p.getId(), data); } catch (IOException e) { Log.w(LOG_TAG, "Unable to read product image for " + p.getId(), e); }*/ } // Find its category and add it if (o.getBoolean("visible")) { String catId = o.getString("categoryId"); for (Category c : this.catalog.getAllCategories()) { if (c.getId().equals(catId)) { this.catalog.addProduct(c, p); break; } } } else { this.catalog.addProduct(p); } } } catch (JSONException e) { Log.e(LOG_TAG, "Unable to parse response: " + resp.toString(), e); SyncUtils.notifyListener(this.listener, CATALOG_SYNC_ERROR, e); this.compositionsDone = true; return; } SyncUtils.notifyListener(this.listener, CATALOG_SYNC_DONE, this.catalog); // Start synchronizing compositions URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), SyncUtils.initParams(this.ctx, "CompositionsAPI", "getAll"), new DataHandler(DataHandler.TYPE_COMPOSITION)); }
From source file:io.spring.initializr.web.support.SpringBootMetadataReader.java
/** * Return the boot versions parsed by this instance. *///from w w w.ja v a2 s. co m public List<DefaultMetadataElement> getBootVersions() { JSONArray array = content.getJSONArray("projectReleases"); List<DefaultMetadataElement> list = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject it = array.getJSONObject(i); DefaultMetadataElement version = new DefaultMetadataElement(); version.setId(it.getString("version")); String name = it.getString("versionDisplayName"); version.setName(it.getBoolean("snapshot") ? name + " (SNAPSHOT)" : name); version.setDefault(it.getBoolean("current")); list.add(version); } return list; }
From source file:com.codeskraps.lolo.misc.Utils.java
public static LOLO getLolo() throws UnsupportedEncodingException, ClientProtocolException, IOException, IllegalArgumentException, NullPointerException, JSONException { long startTime = System.currentTimeMillis(); if (BuildConfig.DEBUG) Log.d(TAG, "download begining"); if (BuildConfig.DEBUG) Log.d(TAG, "download url:" + Constants.LOLO_URL); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(Constants.LOLO_URL); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); Log.d(TAG, "json: " + json); reader.close();/* w ww . j a v a 2 s .c om*/ JSONTokener tokener = new JSONTokener(json); JSONObject finalResult = new JSONObject(tokener); LOLO lolo = finalResult.getBoolean("open") ? LOLO.ON : LOLO.OFF; if (BuildConfig.DEBUG) Log.d(TAG, "lolo: " + lolo); if (BuildConfig.DEBUG) Log.d(TAG, "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); return lolo; }
From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java
/** * return top festival results matching the search criteria. If the * number of found festival is lesser than the requested number of festivals all found * festivals are returned/*from w w w. j a va 2 s.com*/ * * @param num number of festivals to return * @param official official to filter the results by, <code>null</code> to ignore * @param name name to filter the results by, <code>null</code> to ignore * @param country country to filter the results by, <code>null</code> to ignore * @param city city to filter the results by, <code>null</code> to ignore * @param genre genre to filter the results by, <code>null</code> to ignore * @param minPrice minimum price to filter the results by, <code>null</code> to ignore * @param maxPrice maximum price to filter the results by, <code>null</code> to ignore * @param artist artist performing in a concert hosted by the festival * to filter the results by, <code>null</code> to ignore * @return resulting festivals */ public Festival[] readMultipleFestivals(int num, Boolean official, String name, String country, String city, String genre, String minPrice, String maxPrice, String artist) throws ClientDoesNotHavePermissionException { try { URL url = new URL(ExternalDatabaseHelper.getReadMultipleFestivals()); Map<String, String> parameters = new HashMap<>(); parameters.put(ExternalDatabaseDefinitions.PARAMETER_NUMBER, String.valueOf(num)); if (official != null) parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL, String.valueOf(official)); if (name != null) parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME, name); if (country != null) parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY, country); if (city != null) parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY, city); if (genre != null) parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE, genre); if (minPrice != null) parameters.put(ExternalDatabaseDefinitions.PARAMETER_MIN_PRICE, minPrice); if (maxPrice != null) parameters.put(ExternalDatabaseDefinitions.PARAMETER_MAX_PRICE, maxPrice); if (artist != null) parameters.put(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_ARTIST, artist); String response = getRemoteData(url, parameters); JSONArray json = new JSONArray(response); Festival[] result = new Festival[json.length()]; for (int i = 0; i < json.length(); i++) { JSONObject current = json.getJSONObject(i); result[i] = new Festival(-1L, current.getLong(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ID), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME), current.getString( ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_DESCRIPTION), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ADDRESS), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_PRICES), current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OWNER), current.getBoolean(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL), current.getInt(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_VOTES)); } return result; } catch (JSONException | MalformedURLException ignore) { return null; } }
From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java
/** * @param festivalID external id of the festival * @return festival object or null//from w w w . j a va 2 s. c o m * @throws ClientDoesNotHavePermissionException */ public Festival readFestivalInfo(long festivalID) throws ClientDoesNotHavePermissionException { if (festivalID < 0) return null; try { URL url = new URL(ExternalDatabaseHelper.getReadFestivalInfo()); Map<String, String> parameters = new HashMap<>(); parameters.put(ExternalDatabaseDefinitions.PARAMETER_ID, String.valueOf(festivalID)); String response = getRemoteData(url, parameters); if (response == null) return null; if (response.equals(ExternalDatabaseDefinitions.RESPONSE_INVALID_FESTIVAL_ID)) return null; JSONObject json = new JSONObject(response); return new Festival(-1L, json.getLong(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ID), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_DESCRIPTION), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ADDRESS), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_PRICES), json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OWNER), json.getBoolean(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL), json.getInt(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_VOTES) ); } catch (MalformedURLException | JSONException ignore) { return null; } }
From source file:controllers.core.TimesheetController.java
/** * Save the weekly timesheet.//w ww . j a v a 2s .co m */ @Restrict({ @Group(IMafConstants.TIMESHEET_ENTRY_PERMISSION) }) public Result weeklySave() { String[] dataString = request().body().asFormUrlEncoded().get("data"); try { JSONObject dataJson = new JSONObject(dataString[0]); // get the report Long reportId = dataJson.getLong("reportId"); TimesheetReport report = TimesheetDao.getTimesheetReportById(reportId); // create the date format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // get the actor Actor actor = getCurrentActor(); // check the report belongs to the sign-in user if (!report.actor.id.equals(actor.id)) { return forbidden(views.html.error.access_forbidden.render("")); } // check the report is editable if (!report.isEditable()) { Utilities.sendErrorFlashMessage(Msg.get("core.timesheet.fill.save.error.non_editable")); return redirect( controllers.core.routes.TimesheetController.weeklyFill(sdf.format(report.startDate))); } Ebean.beginTransaction(); try { // get the entries JSONArray entriesJson = dataJson.getJSONArray("entries"); for (int i = 0; i < entriesJson.length(); i++) { JSONObject entryJson; try { entryJson = entriesJson.getJSONObject(i); } catch (JSONException e) { entryJson = null; } if (entryJson != null) { // get the attributes boolean inDB = entryJson.getBoolean("inDB"); Boolean toRemove; try { toRemove = entryJson.getBoolean("toRemove"); } catch (JSONException e) { toRemove = null; } Long entryId; try { entryId = entryJson.getLong("entryId"); } catch (JSONException e) { entryId = null; } Long portfolioEntryId; try { portfolioEntryId = entryJson.getLong("portfolioEntryId"); } catch (JSONException e) { portfolioEntryId = null; } Long packageId; try { packageId = entryJson.getLong("packageId"); } catch (JSONException e) { packageId = null; } Long activityId; try { activityId = entryJson.getLong("activityId"); } catch (JSONException e) { activityId = null; } // get the logs JSONArray logsJson = entryJson.getJSONArray("logs"); if (logsJson.length() == 7) { TimesheetEntry entry = null; if (inDB) { entry = TimesheetDao.getTimesheetEntryById(entryId); } else { entry = new TimesheetEntry(); entry.timesheetReport = report; } if (inDB && toRemove) { entry.doDelete(); } else { entry.portfolioEntry = null; entry.portfolioEntryPlanningPackage = null; entry.timesheetActivity = null; if (portfolioEntryId != null) { // initiative entry.portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId); if (packageId != null) { entry.portfolioEntryPlanningPackage = PortfolioEntryPlanningPackageDao .getPEPlanningPackageById(packageId); } } else { // activity entry.timesheetActivity = TimesheetDao.getTimesheetActivityById(activityId); } entry.save(); for (int j = 0; j < logsJson.length(); j++) { JSONObject logJson = logsJson.getJSONObject(j); // get the attributes double hours = logJson.getDouble("hours"); Long logId; try { logId = logJson.getLong("logId"); } catch (JSONException e) { logId = null; } TimesheetLog log = null; if (inDB) { log = TimesheetDao.getTimesheetLogById(logId); } else { log = new TimesheetLog(); log.timesheetEntry = entry; Calendar cal = Calendar.getInstance(); cal.setTime(report.startDate); cal.add(Calendar.DAY_OF_YEAR, j); log.logDate = cal.getTime(); } log.hours = hours; log.save(); } } } } } Ebean.commitTransaction(); } catch (Exception e) { Ebean.rollbackTransaction(); return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getI18nMessagesPlugin()); } Utilities.sendSuccessFlashMessage(Msg.get("core.timesheet.fill.save.successful")); return redirect(controllers.core.routes.TimesheetController.weeklyFill(sdf.format(report.startDate))); } catch (Exception e) { return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getI18nMessagesPlugin()); } }
From source file:de.btobastian.javacord.utils.handler.ReadyHandler.java
@Override public void handle(JSONObject packet) { JSONArray guilds = packet.getJSONArray("guilds"); // guild = server for (int i = 0; i < guilds.length(); i++) { JSONObject guild = guilds.getJSONObject(i); if (guild.has("unavailable") && guild.getBoolean("unavailable")) { // add guild to the list of unavailable servers api.getUnavailableServers().add(guild.getString("id")); continue; }// www. java 2 s . co m new ImplServer(guild, api); } JSONArray privateChannels = packet.getJSONArray("private_channels"); for (int i = 0; i < privateChannels.length(); i++) { JSONObject privateChannel = privateChannels.getJSONObject(i); String id = privateChannel.getString("id"); User user = api.getOrCreateUser(privateChannel.getJSONObject("recipient")); if (user != null) { ((ImplUser) user).setUserChannelId(id); } } api.setYourself(api.getOrCreateUser(packet.getJSONObject("user"))); }
From source file:org.dasein.cloud.gogrid.network.ip.GoGridIPSupport.java
private @Nullable IpAddress toAddress(@Nullable JSONObject json, @Nullable JSONArray vmList, @Nullable JSONArray lbList) throws CloudException, InternalException { if (json == null) { return null; }/*from w w w . j a v a2s. c om*/ IpAddress address = new IpAddress(); address.setForVlan(false); address.setRegionId(getRegionId(getContext())); address.setVersion(IPVersion.IPV4); try { if (json.has("id") && json.has("ip")) { address.setIpAddressId(json.getString("id")); address.setAddress(json.getString("ip")); } else { return null; } if (json.has("public") && json.getBoolean("public")) { address.setAddressType(AddressType.PUBLIC); } else { address.setAddressType(AddressType.PRIVATE); } if (json.has("state")) { JSONObject state = json.getJSONObject("state"); if (state.has("id")) { int s = state.getInt("id"); if (s != 1 && (vmList == null || lbList == null)) { return null; } else if (s == 2) { for (int i = 0; i < vmList.length(); i++) { JSONObject vm = vmList.getJSONObject(i); if (!vm.has("id")) { continue; } if (vm.has("ip")) { JSONObject ip = vm.getJSONObject("ip"); if (ip.has("id") && ip.getString("id").equals(address.getProviderIpAddressId())) { address.setServerId(vm.getString("id")); } } } if (address.getServerId() == null) { for (int i = 0; i < lbList.length(); i++) { JSONObject lb = lbList.getJSONObject(i); if (!lb.has("id")) { continue; } if (lb.has("virtualip.ip")) { JSONObject ip = lb.getJSONObject("virtualip.ip"); if (ip.has("id") && ip.getString("id").equals(address.getProviderIpAddressId())) { address.setProviderLoadBalancerId(lb.getString("id")); } } } } } } } } catch (JSONException e) { logger.error("Failed to parse JSON from the cloud: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } return address; }
From source file:com.hotstar.player.adplayer.feeds.ReferencePlayerFeedItemAdapter.java
/** * Returns a TimeRangeCollection of TimeRanges representing marker ranges, delete ranges, * or replace ranges. Also sets the TIME_RANGES_METADATA_KEY in the metadata node * @param metadataTimeRangeObject to be parsed * @return TimeRangeCollection of type DELETE, MARK, or REPLACE *///from w w w.j a va2s .c om protected AdvertisingMetadata parseTimeRangeMetadata(MetadataNode metadataNode, JSONObject metadataTimeRangeObject, AdvertisingMetadata advertisingMetadata) { TimeRangeCollection timeRanges = null; try { String timeRangeType = metadataTimeRangeObject.getString(METADATA_TIME_RANGE_TYPE); JSONArray timeRangesArray = metadataTimeRangeObject.getJSONArray(METADATA_TIME_RANGE_LIST); Metadata options = null; if (timeRangeType.equals(VALUE_TIME_RANGE_TYPE_DELETE)) { metadataNode.setValue(DefaultMetadataKeys.TIME_RANGES_METADATA_KEY.getValue(), VALUE_TIME_RANGE_TYPE_DELETE); timeRanges = new TimeRangeCollection(TimeRangeCollection.Type.DELETE_RANGES); for (int i = 0; i < timeRangesArray.length(); i++) { JSONObject timeRangeObject = timeRangesArray.getJSONObject(i); Long begin = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_BEGIN)); Long end = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_END)); TimeRange timeRange = TimeRange.createRange(begin, end - begin); timeRanges.addTimeRange(timeRange); } } else if (timeRangeType.equals(VALUE_TIME_RANGE_TYPE_MARK)) { metadataNode.setValue(DefaultMetadataKeys.TIME_RANGES_METADATA_KEY.getValue(), VALUE_TIME_RANGE_TYPE_MARK); timeRanges = new TimeRangeCollection(TimeRangeCollection.Type.MARK_RANGES); for (int i = 0; i < timeRangesArray.length(); i++) { JSONObject timeRangeObject = timeRangesArray.getJSONObject(i); Long begin = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_BEGIN)); Long end = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_END)); TimeRange timeRange = TimeRange.createRange(begin, end - begin); timeRanges.addTimeRange(timeRange); } // set other time-range related key/values options = new MetadataNode(); boolean isAdjustSeekPositionEnabled = metadataTimeRangeObject .getBoolean(NODE_NAME_CUSTOM_AD_MARKERS_ADJUST_SEEK_POSITION); if (isAdjustSeekPositionEnabled) { options.setValue(DefaultMetadataKeys.METADATA_KEY_ADJUST_SEEK_ENABLED.getValue(), VALUE_TRUE); } else { options.setValue(DefaultMetadataKeys.METADATA_KEY_ADJUST_SEEK_ENABLED.getValue(), VALUE_FALSE); } } else if (timeRangeType.equals(VALUE_TIME_RANGE_TYPE_REPLACE)) { metadataNode.setValue(DefaultMetadataKeys.TIME_RANGES_METADATA_KEY.getValue(), VALUE_TIME_RANGE_TYPE_REPLACE); timeRanges = new TimeRangeCollection(TimeRangeCollection.Type.REPLACE_RANGES); for (int i = 0; i < timeRangesArray.length(); i++) { JSONObject timeRangeObject = timeRangesArray.getJSONObject(i); Long begin = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_BEGIN)); Long end = Long.parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_END)); Long replacementDuration; if (timeRangeObject.has(METADATA_TIME_RANGE_REPLACEMENT_DURATION)) { replacementDuration = Long .parseLong(timeRangeObject.getString(METADATA_TIME_RANGE_REPLACEMENT_DURATION)); } else { replacementDuration = -1L; } ReplacementTimeRange timeRange = ReplacementTimeRange.createRange(begin, end - begin, replacementDuration); timeRanges.addTimeRange(timeRange); } } if (advertisingMetadata == null) { advertisingMetadata = new AdvertisingMetadata(); } advertisingMetadata.setTimeRanges(timeRanges, options); } catch (JSONException e) { //PMPDemoApp.logger.e(LOG_TAG + "#parseTimeRangeMetadata", e.getMessage()); } return advertisingMetadata; }