Java Code Examples for org.json.JSONObject#getNames()

The following examples show how to use org.json.JSONObject#getNames() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: micro-integrator   File: QueryFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static void addJSONMappingResultRecord(JSONObject obj,
        OMElement parentEl) throws DataServiceFault {
    Object item;
    for (String name : JSONObject.getNames(obj)) {
        try {
            item = obj.get(name);
        } catch (JSONException e) {
            throw new DataServiceFault(e, "Unexpected JSON parsing error: " + e.getMessage());
        }
        if (name.startsWith("@")) {
            processJSONMappingCallQuery(name.substring(1), item, parentEl);
        } else {
            processJSONMappingResultColumn(name, item, parentEl);
        }
    }
}
 
Example 2
Source Project: Hi-WAY   File: GalaxyTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A function that maps the values of a given JSON object (e.g. an invocation's tool state) according to the mappings defined in this Galaxy Tool
 * 
 * @param jo
 *            the JSON object whose values are to be mapped
 * @throws JSONException
 *             JSONException
 */
public void mapParams(JSONObject jo) throws JSONException {
	if (jo.length() == 0)
		return;
	for (String name : JSONObject.getNames(jo)) {
		Object value = jo.get(name);
		if (value instanceof JSONObject) {
			mapParams((JSONObject) value);
		} else {
			GalaxyParamValue paramValue = getFirstMatchingParamByName(name);
			if (paramValue != null && paramValue.hasMapping(value)) {
				jo.put(name, paramValue.getMapping(value));
			} else if (value.equals(JSONObject.NULL)) {
				jo.remove(name);
			}
		}
	}
}
 
Example 3
/**
 * Transform a jsonarray into a unique map with ALL json object properties
 *
 * @param object
 * @return
 * @throws JSONException
 */
public static List<Map<String, Object>> toMap(JSONArray object) throws JSONException {
	List<Map<String, Object>> toReturn = new ArrayList<Map<String, Object>>();

	if (object != null) {
		for (int o=0; o < object.length(); o++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			JSONObject obj = (JSONObject)object.get(o);
			String[] names = JSONObject.getNames(obj);
			for (int i = 0; i < names.length; i++) {
				map.put(names[i], obj.get(names[i]));
			}
			toReturn.add(map);
		}
	}

	return toReturn;

}
 
Example 4
Source Project: concierge   File: PojoReflector.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public B beanFromJSONObject(final JSONObject obj) throws Exception {
	final String[] names = JSONObject.getNames(obj);
	final B instance = clazz.newInstance();
	for (int i = 0; i < names.length; i++) {
		final String key = names[i];
		final Method setter = setterMethodTable.get(key);
		if (setter == null) {
			// silently ignore, it's JSON after all
			continue;
		}
		final Object o = obj.get(key);
		// check for empty object from JS...
		if (!(o instanceof JSONObject)) {
			setter.invoke(instance, o);
		}
	}

	return instance;
}
 
Example 5
/**
 * Instruments application properties by copying values from the instrumentation JSON.
 * Note, that this method will perform a shallow instrumentation of single string properties.
 * @param manifest
 * @param instrumentation
 * @throws JSONException
 * @throws InvalidAccessException 
 */
public static void instrumentManifest(ManifestParseTree manifest, JSONObject instrumentation) throws JSONException, InvalidAccessException {

	if (instrumentation == null || !manifest.has(ManifestConstants.APPLICATIONS))
		return;

	List<ManifestParseTree> applications = manifest.get(ManifestConstants.APPLICATIONS).getChildren();

	if (instrumentation == null || instrumentation.length() == 0)
		return;

	for (String key : JSONObject.getNames(instrumentation)) {
		Object value = instrumentation.get(key);
		for (ManifestParseTree application : applications) {

			if (ManifestConstants.MEMORY.equals(key) && !updateMemory(application, (String) value))
				continue;

			if (value instanceof String) {
				application.put(key, (String) value);
			} else if (value instanceof JSONObject) {
				application.put(key, (JSONObject) value);
			}
		}
	}
}
 
Example 6
protected String httpGet(String url, String encoding,
                         Map<String, String> headers) throws IOException, CredentialInvalidException {
    if (url.startsWith("local://")) {
        Path file = localSource.resolve(url.substring("local://".length()));
        byte[] bytes = Files.readAllBytes(file);
        encoding = getEncoding(encoding, bytes);
        return new String(bytes, encoding);
    } else {
        Request request = Request.Get(url).connectTimeout(getTimeout())
                .socketTimeout(getTimeout());
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        JSONObject jsonHeaders = scheduleData.getData().optJSONObject(PARAM_HEADERS);
        if (jsonHeaders != null) {
            for (String key : JSONObject.getNames(jsonHeaders)) {
                request.addHeader(key, jsonHeaders.optString(key));
            }
        }
        return executeRequest(encoding, request);
    }
}
 
Example 7
private Map<String,?> toJavaMap(JSONObject jsonMap) throws JSONException {
    Map<String,Object> map = new HashMap<String,Object>();
    for (String key : JSONObject.getNames(jsonMap)) {
        Object value = jsonMap.get(key);
        if (value instanceof JSONObject) {
            map.put(key, toJavaMap((JSONObject) value));
        } else {
            map.put(key, value);
        }
    }
    return map;
}
 
Example 8
Source Project: aion   File: ApiWeb3Aion.java    License: MIT License 5 votes vote down vote up
public ChainHeadView(ChainHeadView cv) {
    hashQueue = new LinkedList<>(cv.hashQueue);
    blkList = new HashMap<>(cv.blkList);
    blkObjList = new HashMap<>(cv.blkObjList);
    txnList = new HashMap<>(cv.txnList);
    response = new JSONObject(cv.response, JSONObject.getNames(cv.response));
    qSize = cv.qSize;
}
 
Example 9
public static Map<String, String> getAttributes(Node component, String selector, long frameId) {
    JSObject player = ((JSValue) component.getProperties().get("player" + frameId)).asObject();
    JSValue attributes = player.getProperty("attributes").asFunction().invoke(player, selector);
    String r = (String) attributes.getStringValue();
    JSONObject o = new JSONObject(r);
    String[] names = JSONObject.getNames(o);
    HashMap<String, String> rm = new HashMap<>();
    for (String name : names) {
        rm.put(name, o.getString(name));
    }
    return rm;
}
 
Example 10
Source Project: marathonv5   File: AbstractPreferences.java    License: Apache License 2.0 5 votes vote down vote up
public void resetInstance(AbstractPreferences oldInstance) {
    listeners = oldInstance.listeners;
    String[] names = JSONObject.getNames(prefs);
    if (names != null) {
        for (String section : names) {
            firePreferenceChange(section);
        }
    }
}
 
Example 11
Source Project: mdw   File: Solution.java    License: Apache License 2.0 5 votes vote down vote up
public Solution(JSONObject json) throws JSONException {
    id = json.getString("id");
    name = json.getString("name");
    if (json.has("ownerType"))
        ownerType = json.getString("ownerType");
    if (json.has("ownerId"))
        ownerId = json.getString("ownerId");
    if (json.has("description"))
        description = json.getString("description");
    if (json.has("members")) {
        JSONObject mems = json.getJSONObject("members");
        members = new HashMap<MemberType,List<Jsonable>>();
        String[] memberTypeListNames = JSONObject.getNames(mems);
        if (memberTypeListNames != null) {
            for (int i = 0; i < memberTypeListNames.length; i++) {
                String memberTypeListName = memberTypeListNames[i];
                MemberType memberType = getMemberType(memberTypeListName);
                JSONArray memsArray = (JSONArray)mems.get(memberTypeListName);
                List<Jsonable> membersList = getMembersList(memberType, memsArray);
                members.put(memberType, membersList);
            }
        }
    }
    if (json.has("values")) {
        JSONObject vals = json.getJSONObject("values");
        values = new HashMap<String,String>();
        String[] valNames = JSONObject.getNames(vals);
        if (valNames != null) {
            for (int i = 0; i < valNames.length; i++)
                values.put(valNames[i], vals.getString(valNames[i]));
        }
    }
}
 
Example 12
Source Project: mdw   File: Pagelet.java    License: Apache License 2.0 5 votes vote down vote up
public static final Map<String,String> getMap(JSONObject jsonObj) throws JSONException {
    Map<String,String> map = new HashMap<String,String>();
    String[] names =  JSONObject.getNames(jsonObj);
    if (names != null) {
        for (String name : names)
            map.put(name, jsonObj.getString(name));
    }
    return map;
}
 
Example 13
Source Project: marathonv5   File: PropertyHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static String toCSS(JSONObject urp) {
    Properties props = new Properties();
    String[] names = JSONObject.getNames(urp);
    for (String prop : names) {
        props.setProperty(prop, urp.get(prop).toString());
    }
    return toCSS(props);
}
 
Example 14
Source Project: marathonv5   File: PropertyHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Properties asProperties(JSONObject jsonObject) {
    Properties r = new Properties();
    String[] names = JSONObject.getNames(jsonObject);
    if (names != null) {
        for (String name : names) {
            r.setProperty(name, jsonObject.get(name).toString());
        }
    }
    return r;
}
 
Example 15
Source Project: marathonv5   File: PropertyHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Properties asProperties(JSONObject jsonObject) {
    Properties r = new Properties();
    String[] names = JSONObject.getNames(jsonObject);
    if (names != null) {
        for (String name : names) {
            r.setProperty(name, jsonObject.get(name).toString());
        }
    }
    return r;
}
 
Example 16
/**
 * Replace the desired JSON key with the given value
 *
 * @param json
 * @param key
 * @param value
 * @return true if operation succeeded
 */
public static boolean replaceKey(JSONObject json, final String key, final Object value) {
    String[] keys;
    boolean res = false;

    if (org.apache.commons.lang.StringUtils.isBlank(key)
            || null == json) {
        return false;
    }
    // first search from
    if (json.has(key)) {
        json.put(key, value);
        return true;
    }
    keys = JSONObject.getNames(json);
    if (null == keys
            || keys.length == 0) {
        return false;
    }
    for (String id : keys) {
        Object obj = json.get(id);

        if (obj instanceof JSONObject) {
            if (replaceKey((JSONObject) obj, key, value)) {
                return true;
            }
        } else if (obj instanceof JSONArray) {
            for (int i = 0; i < ((JSONArray) obj).length(); i++) {
                Object elem = ((JSONArray) obj).get(i);

                if (elem instanceof JSONObject) {
                    res = replaceKey((JSONObject) elem, key, value);
                }
            }
        } else {
            // do nothing
        }
    }
    return res;
}
 
Example 17
Source Project: mdw   File: JsonExport.java    License: Apache License 2.0 4 votes vote down vote up
private int printFilters(Sheet sheet, JSONObject filters, int begin) {
    int rownum = begin;
    Font bold = sheet.getWorkbook().createFont();
    bold.setBold(true);
    CellStyle labelRowStyle = sheet.getWorkbook().createCellStyle();
    labelRowStyle.setFont(bold);
    labelRowStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    labelRowStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    Row labelRow = sheet.createRow(rownum);
    Cell cell = labelRow.createCell(0);
    cell.setCellValue("Filters:");
    cell.setCellStyle(labelRowStyle);
    labelRow.setRowStyle(labelRowStyle);

    CellStyle nameStyle = sheet.getWorkbook().createCellStyle();
    nameStyle.setFont(bold);

    rownum++;
    for (String name : JSONObject.getNames((filters))){
        Row row = sheet.createRow(rownum);
        Cell nameCell = row.createCell(0);
        nameCell.setCellValue(name);
        nameCell.setCellStyle(nameStyle);
        Object jsonValue = filters.get(name);
        if (jsonValue != null) {
            Cell valueCell = row.createCell(1);
            setCellValue(valueCell, jsonValue);
        }
        rownum++;
    }
    rownum++;

    labelRow = sheet.createRow(rownum);
    cell = labelRow.createCell(0);
    cell.setCellValue("Data:");
    cell.setCellStyle(labelRowStyle);
    labelRow.setRowStyle(labelRowStyle);
    rownum++;
    return rownum;
}
 
Example 18
Source Project: ict   File: ConfigurableIxiContext.java    License: Apache License 2.0 4 votes vote down vote up
private JSONObject cloneJSONObject(JSONObject jsonObject) {
    return new JSONObject(jsonObject, JSONObject.getNames(jsonObject));
}
 
Example 19
/**
 * Called when AVL data is read from URL. Processes the JSON data and calls
 * processAvlReport() for each AVL report.
 */
@Override
protected Collection<AvlReport> processData(InputStream in) throws Exception {
	// Get the JSON string containing the AVL data
	String jsonStr = getJsonString(in);
	try {
		// Convert JSON string to a JSON object
		JSONObject jsonObj = new JSONObject(jsonStr);

		// The JSON feed is really odd. Instead of having an
		// array of vehicles there is a separate JSON object
		// for each vehicle, and the name of the object is the
		// trip ID. Therefore need to get names of all the objects
		// so that each one can be accessed by name.
		String tripNames[] = JSONObject.getNames(jsonObj);
		
		// The return value for the method
		Collection<AvlReport> avlReportsReadIn = new ArrayList<AvlReport>();

		// For each vehicle...
		for (String tripName : tripNames) {
			JSONObject v = jsonObj.getJSONObject(tripName);
			
			// Create the AvlReport from the JSON data
			String vehicleId = Integer.toString(v.getInt("vehicle_id"));
			Double lat = v.getDouble("vehicle_lat");
			Double lon = v.getDouble("vehicle_lon");
			// Guessing that the speed is in mph since getting values up to 58.
			// Therefore need to convert to m/s.
			float speed = (float) v.getDouble("vehicle_speed") * Geo.MPH_TO_MPS;
			// Not sure if bearing is the same as heading.
			float heading = (float) v.getDouble("vehicle_bearing");
			// The time is really strange. It is off by 4-5 hours for some
			// strange reason. It appears to be 4 hours off during daylight
			// savings time but 5 hours during normal winter hours. Yikes!
			// Therefore using the parameter keolisFeedAvlTimeOffset to
			// specify the offset.
			long gpsTime =
					v.getLong("vehicle_timestamp") * Time.MS_PER_SEC
							+ keolisFeedAvlTimeOffset.getValue()
							* Time.HOUR_IN_MSECS;

			// Create the AvlReport
			AvlReport avlReport =
					new AvlReport(vehicleId, gpsTime, lat, lon, speed,
							heading, "Keolis");

			// Need to set assignment info separately. Unfortunately the 
			// trip ID in the Keolis feed doesn't correspond exactly to the
			// trip IDs in the GTFS data. In Keolis feed it will be 
			// something like "CR-FRAMINGHAM-Weekday-515" but in GTFS it will
			// be "CR-Worcester-CR-Weekday-Worcester-Jun15-515". Therefore 
			// it is best to just use the trip short name, such as "515".
			String tripShortName =
					tripName.substring(tripName.lastIndexOf('-') + 1);
			
			// Actually set the assignment
			avlReport.setAssignment(tripShortName,
					AssignmentType.TRIP_SHORT_NAME);

			logger.debug("From KeolisAvlModule {}", avlReport);
			
			if (shouldProcessAvl) {
				avlReportsReadIn.add(avlReport);
			}
		}	
		
		// Return all the AVL reports read in
		return avlReportsReadIn;
	} catch (JSONException e) {
		logger.error("Error parsing JSON. {}. {}", e.getMessage(), jsonStr,
				e);
		return new ArrayList<AvlReport>();
	}

}
 
Example 20
Source Project: mdw   File: Attributes.java    License: Apache License 2.0 4 votes vote down vote up
public Attributes(JSONObject json) {
    for (String name : JSONObject.getNames(json)) {
        put(name, json.optString(name));
    }
}