List of usage examples for org.json JSONArray getString
public String getString(int index) throws JSONException
From source file:es.stork.ws.StorkSamlEngineWS.java
/** * Generates SAML Token// w ww . j a v a 2 s. co m * @destination destination URL * @serviceProvider Service Provider's name * @qaal qaa level requested * @personalAttributeList attribute list requestesd in JSON format * @return SAML token in XML format */ public byte[] generateSTORKAuthnRequest(@WebParam(name = "destination") String destination, @WebParam(name = "serviceProvider") String serviceProvider, @WebParam(name = "qaal") int qaal, @WebParam(name = "urlAssertionConsumerService") String urlAssertionConsumerService, @WebParam(name = "spId") String spId, @WebParam(name = "spApplication") String spApplication, @WebParam(name = "personalAttributeList") String personalAttributeList) { //Load properties file configs = new Properties(); try { configs.load(this.getClass().getClassLoader().getResourceAsStream(Constants.WS_PROPERTIES)); } catch (IOException e) { LOG.error("Reading properties file: " + e.getMessage()); e.printStackTrace(); throw new STORKSAMLEngineWSException(e.getMessage()); } //Unmarshall JSON chain JSONObject json; try { json = new JSONObject(personalAttributeList); } catch (ParseException e) { LOG.error("Generating STORKAuthnRequest: " + e.getMessage()); e.printStackTrace(); throw new STORKSAMLEngineWSException(e.getMessage()); } Iterator<?> itr = json.keys(); PersonalAttributeList pAttList = new PersonalAttributeList(); while (itr.hasNext()) { String attributeName = (String) itr.next(); PersonalAttribute pAttribute = new PersonalAttribute(); pAttribute.setName(attributeName); if (json.get(attributeName).getClass().getName().equals("org.json.JSONArray")) { ArrayList<String> attributeValues = new ArrayList<String>(); JSONArray jarray = (JSONArray) json.get(attributeName); for (int i = 0; i < jarray.length(); i++) { if (i == 0) { if (jarray.getString(i).equals("true")) pAttribute.setIsRequired(true); else pAttribute.setIsRequired(false); } else { attributeValues.add(jarray.getString(i)); } pAttribute.setValue(attributeValues); } } else if (json.get(attributeName).equals("true")) pAttribute.setIsRequired(true); else pAttribute.setIsRequired(false); pAttList.add(pAttribute); } STORKAuthnRequest authnRequest = new STORKAuthnRequest(); authnRequest.setDestination(destination); authnRequest.setProviderName(serviceProvider); authnRequest.setQaa(qaal); authnRequest.setPersonalAttributeList(pAttList); authnRequest.setAssertionConsumerServiceURL(urlAssertionConsumerService); //new parameters authnRequest.setSpSector(configs.getProperty(Constants.SP_SECTOR)); authnRequest.setSpInstitution(serviceProvider); authnRequest.setSpApplication(spApplication); authnRequest.setSpCountry(configs.getProperty(Constants.SP_COUNTRY)); //V-IDP parameters authnRequest.setSPID(spId); //Generates Stork Request try { engine = STORKSAMLEngine.getInstance("WS"); authnRequest = engine.generateSTORKAuthnRequest(authnRequest); engine.validateSTORKAuthnRequest(authnRequest.getTokenSaml()); LOG.info("Generated STORKAuthnRequest(id: {})", authnRequest.getSamlId()); } catch (STORKSAMLEngineException e) { LOG.error("Generating STORKAuthnRequest: " + e.getMessage()); e.printStackTrace(); throw new STORKSAMLEngineWSException(e.getMessage()); } return authnRequest.getTokenSaml(); }
From source file:org.dasein.cloud.joyent.compute.Machine.java
private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException { if (ob == null) { return null; }/* ww w . ja va 2 s . c o m*/ try { VirtualMachine vm = new VirtualMachine(); vm.setClonable(false); vm.setImagable(false); vm.setLastPauseTimestamp(-1L); vm.setPersistent(true); vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a"); vm.setProviderOwnerId(provider.getContext().getAccountNumber()); vm.setProviderRegionId(provider.getContext().getRegionId()); vm.setTerminationTimestamp(-1L); if (ob.has("id")) { vm.setProviderVirtualMachineId(ob.getString("id")); } if (ob.has("name")) { vm.setName(ob.getString("name")); } if (ob.has("ips")) { JSONArray ips = ob.getJSONArray("ips"); ArrayList<String> pubIp = new ArrayList<String>(); ArrayList<String> privIp = new ArrayList<String>(); for (int i = 0; i < ips.length(); i++) { String addr = ips.getString(i); boolean pub = false; if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) { if (addr.startsWith("172.")) { String[] nums = addr.split("\\."); if (nums.length != 4) { pub = true; } else { try { int x = Integer.parseInt(nums[1]); if (x < 16 || x > 31) { pub = true; } } catch (NumberFormatException ignore) { // ignore } } } else { pub = true; } } if (pub) { pubIp.add(addr); } else { privIp.add(addr); } } if (!pubIp.isEmpty()) { vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()])); } if (!privIp.isEmpty()) { vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()])); } } if (ob.has("metadata")) { JSONObject md = ob.getJSONObject("metadata"); JSONArray names = md.names(); if (names != null) { for (int i = 0; i < names.length(); i++) { String name = names.getString(i); if (name.equals("dsnDescription")) { vm.setDescription(md.getString(name)); } else if (name.equals("dsnTrueImage")) { vm.setProviderMachineImageId(md.getString(name)); } else if (name.equals("dsnTrueProduct")) { vm.setProductId(md.getString(name)); } else { vm.addTag(name, md.getString(name)); } } } } if (vm.getProviderMachineImageId() == null && ob.has("dataset")) { vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset"))); } if (ob.has("created")) { vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created"))); } vm.setPausable(false); // can't ever pause/resume joyent vms vm.setRebootable(false); if (ob.has("state")) { vm.setCurrentState(toState(ob.getString("state"))); if (VmState.RUNNING.equals(vm.getCurrentState())) { vm.setRebootable(true); } else if (VmState.STOPPED.equals(vm.getCurrentState())) { vm.setImagable(true); } } vm.setLastBootTimestamp(vm.getCreationTimestamp()); if (vm.getName() == null) { vm.setName(vm.getProviderVirtualMachineId()); } if (vm.getDescription() == null) { vm.setDescription(vm.getName()); } discover(vm); boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS)); if (vm.getProductId() == null) { VirtualMachineProduct d = null; int disk, ram; disk = ob.getInt("disk"); ram = ob.getInt("memory"); for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) { d = prd; boolean isProductSmartOs = prd.getName().contains("smartos"); if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk && prd.getRamSize().intValue() == ram) { if (isVMSmartOs && !isProductSmartOs) { continue; } if (!isVMSmartOs && isProductSmartOs) { continue; } vm.setProductId(prd.getProviderProductId()); break; } } if (vm.getProductId() == null) { vm.setProductId(d.getProviderProductId()); } } return vm; } catch (JSONException e) { throw new CloudException(e); } }
From source file:org.schedulesdirect.grabber.ScheduleTask.java
protected void fetchStations(Map<String, Collection<String>> ids) { if (ids == null || ids.size() == 0) { LOG.info("No stale schedules identified; skipping schedule download!"); return;/*from w w w .j ava2s . c o m*/ } DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULES, clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl()); JSONArray data = new JSONArray(); Iterator<String> idItr = ids.keySet().iterator(); while (idItr.hasNext()) { String id = idItr.next(); JSONObject o = new JSONObject(); o.put("stationID", id); Collection<String> dates = new ArrayList<>(); for (String date : ids.get(id)) dates.add(date); o.put("date", dates); data.put(o); } try { JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONArray.class); for (int i = 0; i < resp.length(); ++i) { JSONObject o = resp.getJSONObject(i); if (!JsonResponseUtils.isErrorResponse(o)) { JSONArray sched = o.getJSONArray("programs"); String schedId = o.getString("stationID"); Date expiry = new Date(System.currentTimeMillis() - Grabber.MAX_AIRING_AGE); for (int j = 0; j < sched.length(); ++j) { try { JSONObject airing = sched.getJSONObject(j); Date end = AiringUtils.getEndDate(airing); String progId = airing.getString("programID"); if (!end.before(expiry)) { String md5 = airing.getString("md5"); cache.markIfDirty(progId, md5); } else LOG.debug(String.format("Expired airing discovered and ignored! [%s; %s; %s]", progId, o.getString("stationID"), end)); synchronized (ScheduleTask.class) { List<JSONObject> objs = FULL_SCHEDS.get(schedId); if (objs == null) { objs = new ArrayList<JSONObject>(); FULL_SCHEDS.put(schedId, objs); } objs.add(airing); } } catch (JSONException e) { LOG.warn(String.format("JSONException [%s]", o.optString("stationID", "unknown")), e); } } } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.SCHEDULE_QUEUED) LOG.warn(String.format( "StationID %s is queued server side and will be downloaded on next EPG update!", o.getString("stationID"))); else throw new InvalidJsonObjectException("Error received for schedule", o.toString(3)); } } catch (JSONException | JsonParseException e) { Grabber.failedTask = true; LOG.fatal("Fatal JSON error!", e); throw new RuntimeException(e); } catch (IOException e) { Grabber.failedTask = true; LOG.error("IOError receiving schedule data! Filling cache with empty schedules!", e); try { JSONArray schedIds = this.req; for (int i = 0; i < schedIds.length(); ++i) { String id = schedIds.getString(i); Path p = vfs.getPath("schedules", String.format("%s.txt", id)); if (!Files.exists(p)) { JSONObject emptySched = new JSONObject(); emptySched.put("stationID", id); emptySched.put("programs", new JSONArray()); Files.write(p, emptySched.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); } } } catch (Exception x) { LOG.error("Unexpected error!", x); throw new RuntimeException(x); } } }
From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java
private String[] getJavaStringArray(JSONArray array) throws JSONException { int len = array.length(); String[] result = new String[len]; for (int i = 0; i < len; i++) { result[i] = array.isNull(i) ? null : array.getString(i); }/*from w w w. j ava 2 s .c om*/ return result; }
From source file:org.chromium.ChromeIdentity.java
private String getScopesString(CordovaArgs args) throws IOException, JSONException { JSONArray scopes = args.getJSONObject(1).getJSONArray("scopes"); StringBuilder ret = new StringBuilder("oauth2:"); for (int i = 0; i < scopes.length(); i++) { if (i != 0) { ret.append(" "); }//from w w w . ja v a 2 s. c o m ret.append(scopes.getString(i)); } return ret.toString(); }
From source file:com.example.android.geofence.DGGeofencing.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equalsIgnoreCase("initCallbackForRegionMonitoring")) { cbContext = callbackContext;/* w ww.j av a 2 s .c o m*/ } else if (action.equalsIgnoreCase("startMonitoringRegion")) { // Create an intent filter for the broadcast receiver mIntentFilter = new IntentFilter(); // Action for broadcast Intents that report successful addition of geofences mIntentFilter.addAction(GeofenceUtils.ACTION_GEOFENCES_ADDED); // Action for broadcast Intents that report successful removal of geofences mIntentFilter.addAction(GeofenceUtils.ACTION_GEOFENCES_REMOVED); // Action for broadcast Intents containing various types of geofencing errors mIntentFilter.addAction(GeofenceUtils.ACTION_GEOFENCE_ERROR); // All Location Services sample apps use this category mIntentFilter.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES); // Instantiate the current List of geofences mCurrentGeofences = new ArrayList<Geofence>(); // Instantiate a Geofence requester mGeofenceRequester = new GeofenceRequester(this.cordova.getActivity()); // Instantiate a Geofence remover mGeofenceRemover = new GeofenceRemover(this.cordova.getActivity()); // Attach to the main UI //setContentView(R.layout.activity_main); /* * Record the request as an ADD. If a connection error occurs, * the app can automatically restart the add request if Google Play services * can fix the error */ mRequestType = GeofenceUtils.REQUEST_TYPE.ADD; /* * Check for Google Play services. Do this after * setting the request type. If connecting to Google Play services * fails, onActivityResult is eventually called, and it needs to * know what type of request was in progress. */ if (!servicesConnected()) { return false; } /* * Create a version of geofence 1 that is "flattened" into individual fields. This * allows it to be stored in SharedPreferences. */ double lat = Double.valueOf(args.getString(1)); double lng = Double.valueOf(args.getString(2)); float radius = Float.valueOf(args.getString(3)); mUIGeofence1 = new SimpleGeofence("1", // Get latitude, longitude, and radius from the UI lat, lng, radius, // Set the expiration time GEOFENCE_EXPIRATION_IN_MILLISECONDS, // Only detect entry transitions Geofence.GEOFENCE_TRANSITION_ENTER); /* * Add Geofence objects to a List. toGeofence() * creates a Location Services Geofence object from a * flat object */ mCurrentGeofences.add(mUIGeofence1.toGeofence()); // Start the request. Fail if there's already a request in progress try { // Try to add geofences mGeofenceRequester.addGeofences(mCurrentGeofences); } catch (UnsupportedOperationException e) { // Notify user that previous request hasn't finished. } } return true; }
From source file:com.intel.xdk.multitouch.MultiTouch.java
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback context used when calling back into JavaScript. * @return True when the action was valid, false otherwise. *///from www.java 2s. c om public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("enableMultitouch")) { enableMultitouch(); } else if (action.equals("disableMultitouch")) { disableMultitouch(); } else if (action.equals("queueMultitouchData")) { queueMultitouchData(args.getString(0), args.getInt(1), args.getInt(2)); } else if (action.equals("getMultitouchData")) { String js = getMultitouchData(); JSONArray r = new JSONArray(js); callbackContext.success(r); } else if (action.equals("messagePump")) { JSONObject r = new JSONObject(); r.put("message", new JSONObject(messagePump())); callbackContext.success(r); } else if (action.equals("addMessage")) { addMessage(args.getString(0)); } else if (action.equals("")) { this.enableMultitouch(); } else { return false; } return true; }
From source file:com.cmackay.plugins.googleanalytics.GoogleAnalyticsPlugin.java
private void set(String rawArgs, CallbackContext callbackContext) { if (hasTracker(callbackContext)) { try {//from w w w . j a v a 2 s. c om JSONArray args = new JSONArray(rawArgs); String key = args.getString(0); String value = args.isNull(1) ? null : args.getString(1); tracker.set(key, value); callbackContext.success(); } catch (JSONException e) { callbackContext.error(e.toString()); } } }
From source file:com.pimp.companionforband.utils.jsontocsv.parser.JsonFlattener.java
private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) { int length = obj.length(); for (int i = 0; i < length; i++) { try {/* ww w. ja va 2s . c o m*/ if (obj.get(i).getClass() == JSONArray.class) { JSONArray jsonArray = (JSONArray) obj.get(i); if (jsonArray.length() < 1) continue; flatten(jsonArray, flatJson, prefix + i); } else if (obj.get(i).getClass() == JSONObject.class) { JSONObject jsonObject = (JSONObject) obj.get(i); flatten(jsonObject, flatJson, prefix + (i + 1)); } else { String value = obj.getString(i); if (value != null) flatJson.put(prefix + (i + 1), value); } } catch (Exception e) { Log.e("flattenJsonArray", e.toString()); } } }
From source file:org.entrystore.ldcache.util.JsonUtil.java
public static Set<Value> jsonArrayToValueSet(JSONArray array) { Set<Value> result = new HashSet<Value>(); for (int i = 0; i < array.length(); i++) { String uri = null;// w ww . j a v a 2 s. c o m try { uri = array.getString(i); } catch (JSONException e) { log.warn(e.getMessage()); continue; } if (uri != null) { result.add(new URIImpl(NS.expandNS(uri))); } } return result; }