Java Code Examples for org.json.JSONArray#put()

The following examples show how to use org.json.JSONArray#put() . 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 File: ApiMetadata.java    From magnet-client with Mozilla Public License 2.0 6 votes vote down vote up
private JSONObject toJson(List<String> urls) {
    JSONObject result = new JSONObject();
    JSONArray objects = new JSONArray();

    try {
        for (String url : urls) {
            objects.put(new JSONObject().put("url", url));
        }

        result.put("objects", objects);
    } catch(JSONException error) {
        Log.e(TAG, error.getMessage());
    }

    return result;
}
 
Example 2
Source File: AssetServicesImpl.java    From mdw with Apache License 2.0 6 votes vote down vote up
public JSONObject discoverGitAssets(String repoUrl, String branch) throws ServiceException {
    JSONObject packages = new JSONObject();
    packages.put("gitBranch", branch);
    packages.put("assetRoot", ApplicationContext.getAssetRoot());
    packages.put("packages", new JSONArray());
    try {
        GitDiscoverer discoverer = getDiscoverer(repoUrl);
        discoverer.setRef(branch);
        Map<String,PackageMeta> packageInfo = discoverer.getPackageInfo();
        for (PackageMeta pkgMeta : packageInfo.values()) {
            JSONArray array = packages.getJSONArray("packages");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("format", "json");
            jsonObj.put("name", pkgMeta.getName());
            jsonObj.put("version", pkgMeta.getVersion());
            array.put(jsonObj);
        }
    }
    catch (IOException ex) {
        throw new ServiceException(ex.getMessage(), ex);
    }
    return packages;
}
 
Example 3
Source File: SchedulerUtilitiesV2.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void getSaveAsSnapshotOptions(JSONObject request, DispatchContext dispatchContext, JSONArray jerr) throws JSONException {
	Boolean saveassnap = request.optBoolean("saveassnapshot");
	if (saveassnap) {
		dispatchContext.setSnapshootDispatchChannelEnabled(true);

		String snapshotName = request.optString("snapshotname");
		dispatchContext.setSnapshotName(snapshotName);
		if (snapshotName.trim().equals("")) {
			jerr.put("Empty snapshotName");
		}

		String snapshotDescription = request.optString("snapshotdescription");
		dispatchContext.setSnapshotDescription(snapshotDescription);

		String snapshotHistoryLength = request.optString("snapshothistorylength");
		dispatchContext.setSnapshotHistoryLength(snapshotHistoryLength);
	}
}
 
Example 4
Source File: TracerouteDataBean.java    From netanalysis-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
public JSONObject toJson() {
    JSONObject json = super.toJson();
    JSONArray jarr = new JSONArray();
    if (routeInfoList != null && !routeInfoList.isEmpty()) {
        for (RouteInfoBean bean : routeInfoList) {
            if (bean == null || bean.toJson().length() == 0)
                continue;
            
            jarr.put(bean.toJson());
        }
    }
    try {
        json.put("route_info", jarr);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    return json;
}
 
Example 5
Source File: Util.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@CheckResult
private static JSONArray getJsonArrayWithoutEntryByIndex(JSONArray jsonArray, int pos) throws JSONException {
    JSONArray result = new JSONArray();

    for (int i = 0; i < jsonArray.length(); i++) {
        if (i != pos) {
            result.put(jsonArray.get(i));
        }
    }

    return result;
}
 
Example 6
Source File: UnSavedHistoryStage.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void onSave() {
    MarathonInputStage testNameStage = new MarathonInputStage("Test name", "Save the current test run",
            FXUIUtils.getIcon("testrunner")) {

        @Override
        protected String validateInput(String name) {
            String errorMessage = null;
            if (name.length() == 0 || name.trim().isEmpty()) {
                errorMessage = "Enter a valid name";
            }
            return errorMessage;
        }

        @Override
        protected String getInputFiledLabelText() {
            return "Enter a test name: ";
        }

        @Override
        protected void setDefaultButton() {
            okButton.setDefaultButton(true);
        }
    };
    TestNameHandler testNameHandler = new TestNameHandler();
    testNameStage.setInputHandler(testNameHandler);
    testNameStage.getStage().showAndWait();
    if (testNameHandler.getTestName() == null)
        return;
    JSONObject jsonObject = removeAndGetTest("unsaved");
    if (jsonObject != null) {
        JSONArray history = TestRunnerHistory.getInstance().getHistory("favourites");
        String testName = testNameHandler.getTestName();
        jsonObject.put("name", testName);
        history.put(jsonObject);
        TestRunnerHistory.getInstance().save();
    }
}
 
Example 7
Source File: Activities.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Path("/definitions")
public JSONObject getDefinitions(Query query) throws ServiceException {
    ActivityList activityVOs = ServiceLocator.getDesignServices().getActivityDefinitions(query);
    JSONArray jsonActivities = new JSONArray();
    for (ActivityInstance activityInstance : activityVOs.getActivities()) {
        jsonActivities.put(activityInstance.getJson());
    }
    return activityVOs.getJson();
}
 
Example 8
Source File: FacebookDialog.java    From android-skeleton-project with MIT License 5 votes vote down vote up
private Object flattenObject(Object object) throws JSONException {
    if (object == null) {
        return null;
    }

    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        // Don't flatten objects that are marked as create_object.
        if (jsonObject.optBoolean(NativeProtocol.OPEN_GRAPH_CREATE_OBJECT_KEY)) {
            return object;
        }
        if (jsonObject.has("id")) {
            return jsonObject.getString("id");
        } else if (jsonObject.has("url")) {
            return jsonObject.getString("url");
        }
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        JSONArray newArray = new JSONArray();
        int length = jsonArray.length();

        for (int i = 0; i < length; ++i) {
            newArray.put(flattenObject(jsonArray.get(i)));
        }

        return newArray;
    }

    return object;
}
 
Example 9
Source File: IoHelper.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
public static void collectionToFile (final Collection<String> data, final File f) throws IOException {
	try {
		final JSONArray arr = new JSONArray();
		for (final String d : data) {
			arr.put(d);
		}
		stringToFile(arr.toString(2), f);
	}
	catch (final JSONException e) {
		throw new IOException(e.toString(), e);
	}
}
 
Example 10
Source File: EnumTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * To serialize by assigned value, use the put() methods. The value
 * will be stored as a enum type. 
 */
@Test
public void enumPut() {
    JSONObject jsonObject = new JSONObject();
    MyEnum myEnum = MyEnum.VAL2;
    jsonObject.put("myEnum", myEnum);
    MyEnumField myEnumField = MyEnumField.VAL1;
    jsonObject.putOnce("myEnumField", myEnumField);

    // validate JSON content
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 2 top level objects", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/myEnum")));
    assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/myEnumField")));
    
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(myEnum);
    jsonArray.put(1, myEnumField);

    // validate JSON content
    doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
    assertTrue("expected 2 top level objects", ((List<?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonArray.query("/0")));
    assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonArray.query("/1")));

    /**
     * Leaving these tests because they exercise get, opt, and remove
     */
    assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0)));
    assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1)));
    assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1)));
}
 
Example 11
Source File: Tasks.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Path("/templates")
public JsonArray getTemplates(Query query) throws ServiceException {
    List<TaskTemplate> taskVOs = getTaskServices().getTaskTemplates(query);
    JSONArray jsonTasks = new JSONArray();
    for (TaskTemplate taskVO : taskVOs) {
        JSONObject jsonTask = new JsonObject();
        jsonTask.put("packageName", taskVO.getPackageName());
        jsonTask.put("taskId", taskVO.getId());
        jsonTask.put("name", taskVO.getTaskName());
        jsonTask.put("version", taskVO.getVersionString());
        jsonTask.put("logicalId", taskVO.getLogicalId());
        jsonTasks.put(jsonTask);
    }
    return new JsonArray(jsonTasks);
}
 
Example 12
Source File: PathSet.java    From jingtum-lib-java with MIT License 5 votes vote down vote up
public JSONArray toJSONArray() {
    JSONArray array = new JSONArray();
    for (Hop hop : this) {
        array.put(hop.toJSONObject());
    }
    return array;
}
 
Example 13
Source File: Tasks.java    From mdw with Apache License 2.0 5 votes vote down vote up
@Path("/tops")
public JsonArray getTops(Query query) throws ServiceException {
    // dashboard top throughput query
    List<TaskAggregate> taskAggregates = getTaskServices().getTopTasks(query);
    JSONArray taskArr = new JSONArray();
    int ct = 0;
    TaskAggregate other = null;
    long otherTot = 0;
    for (TaskAggregate taskAggregate : taskAggregates) {
        if (ct >= query.getMax()) {
            if (other == null) {
                other = new TaskAggregate(0);
                other.setName("Other");
            }
            otherTot += taskAggregate.getCount();
        }
        else {
            taskArr.put(taskAggregate.getJson());
        }
        ct++;
    }
    if (other != null) {
        other.setCount(otherTot);
        taskArr.put(other.getJson());
    }
    return new JsonArray(taskArr);
}
 
Example 14
Source File: LayoutServiceDemo.java    From java-example with MIT License 5 votes vote down vote up
void launchOpenfin() throws DesktopException, DesktopIOException, IOException, InterruptedException {
		RuntimeConfiguration config = new RuntimeConfiguration();
		String rvm = System.getProperty("com.openfin.demo.layout.rvm");
		if (rvm != null) {
			config.setLaunchRVMPath(rvm);
		}
		config.setRuntimeVersion("alpha");
		config.setAdditionalRuntimeArguments("--v=1 ");
		serviceConfig = new JSONArray();
		JSONObject layout = new JSONObject();
		layout.put("name", "layouts");
//		layout.put("manifestUrl", "http://localhost:8081/app3.json");
		JSONObject scfg = new JSONObject();
		JSONObject sfeatures = new JSONObject();
		sfeatures.put("dock", true);
		sfeatures.put("tab", true);
		scfg.put("features", sfeatures);
		layout.put("config", scfg);
		serviceConfig.put(0, layout);
		config.addConfigurationItem("services", serviceConfig);

		JSONObject startupApp = new JSONObject();
		startupApp.put("uuid", appUuid);
		startupApp.put("name", appUuid);
		startupApp.put("url", "about:blank");
		startupApp.put("autoShow", false);
		config.setStartupApp(startupApp);

		this.desktopConnection = new DesktopConnection(javaConnectUuid);
		this.desktopConnection.connect(config, this, 60);
		latch.await();
	}
 
Example 15
Source File: JsonConvert.java    From react-native-cordova with MIT License 5 votes vote down vote up
public static JSONArray reactToJSON(ReadableArray readableArray) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    for(int i=0; i < readableArray.size(); i++) {
        ReadableType valueType = readableArray.getType(i);
        switch (valueType){
            case Null:
                jsonArray.put(JSONObject.NULL);
                break;
            case Boolean:
                jsonArray.put(readableArray.getBoolean(i));
                break;
            case Number:
                try {
                    jsonArray.put(readableArray.getInt(i));
                } catch(Exception e) {
                    jsonArray.put(readableArray.getDouble(i));
                }
                break;
            case String:
                jsonArray.put(readableArray.getString(i));
                break;
            case Map:
                jsonArray.put(reactToJSON(readableArray.getMap(i)));
                break;
            case Array:
                jsonArray.put(reactToJSON(readableArray.getArray(i)));
                break;
        }
    }
    return jsonArray;
}
 
Example 16
Source File: SlotList.java    From Aegis with GNU General Public License v3.0 5 votes vote down vote up
public JSONArray toJson() {
    JSONArray array = new JSONArray();
    for (Slot slot : this) {
        array.put(slot.toJson());
    }

    return array;
}
 
Example 17
Source File: AuthorizationsService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
@UserConstraint(functionalities = { SpagoBIConstants.PROFILE_MANAGEMENT })
public String getAuthorizations(@Context HttpServletRequest req) {
	JSONObject documentJSON = new JSONObject();

	try {
		IEngUserProfile profile = (IEngUserProfile) req.getSession().getAttribute(IEngUserProfile.ENG_USER_PROFILE);
		if (profile instanceof UserProfile) {
			UserProfile spagoBIUserProfile = (UserProfile) profile;
			String organization = spagoBIUserProfile.getOrganization();

			ITenantsDAO tenantsDAO = DAOFactory.getTenantsDAO();
			List<Integer> productTypeIds = tenantsDAO.loadSelectedProductTypesIds(organization);
			IRoleDAO roleDAO = DAOFactory.getRoleDAO();
			List<String> authorizationsWithDuplicates = roleDAO.loadAllAuthorizationsNamesByProductTypes(productTypeIds);
			Set<String> authorizations = new HashSet<String>(authorizationsWithDuplicates);
			JSONArray authorizationsJSONArray = new JSONArray();

			for (String authorization : authorizations) {
				JSONObject authorizationJSONObject = new JSONObject();
				authorizationJSONObject.put("name", authorization);
				authorizationsJSONArray.put(authorizationJSONObject);
			}

			documentJSON.put("root", authorizationsJSONArray);
		}
		return documentJSON.toString();
	} catch (Throwable t) {
		logger.error("An unexpected error occured while retriving authorizations");
		throw new SpagoBIServiceException("An unexpected error occured while authorizations", t);
	}

}
 
Example 18
Source File: ReadBuildRevisionParameters.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
private AnswerItem<JSONObject> findBuildRevisionParametersList(String system, String build, String revision, String application, ApplicationContext appContext, boolean userHasPermissions, HttpServletRequest request) throws JSONException {

        AnswerItem<JSONObject> item = new AnswerItem<>();
        JSONObject object = new JSONObject();
        brpService = appContext.getBean(BuildRevisionParametersService.class);

        int startPosition = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0"));
        int length = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0"));
        /*int sEcho  = Integer.valueOf(request.getParameter("sEcho"));*/

        String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
        int columnToSortParameter = Integer.parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_0"), "1"));
        String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "ID,Build,Revision,Release,Application,Project,TicketIDFixed,BugIDFixed,Link,ReleaseOwner,Subject,datecre,jenkinsbuildid,mavengroupid,mavenartifactid,mavenversion");
        String columnToSort[] = sColumns.split(",");
        String columnName = columnToSort[columnToSortParameter];
        String sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_0"), "asc");
        List<String> individualLike = new ArrayList<>(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
        
        Map<String, List<String>> individualSearch = new HashMap<>();
        for (int a = 0; a < columnToSort.length; a++) {
            if (null!=request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
                List<String> search = new ArrayList<>(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
                if(individualLike.contains(columnToSort[a])) {
                	individualSearch.put(columnToSort[a]+":like", search);
                }else {
                	individualSearch.put(columnToSort[a], search);
                }            
            }
        }
        
        AnswerList<BuildRevisionParameters> resp = brpService.readByVarious1ByCriteria(system, application, build, revision, startPosition, length, columnName, sort, searchParameter, individualSearch);

        JSONArray jsonArray = new JSONArray();
        if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
            for (BuildRevisionParameters brp : (List<BuildRevisionParameters>) resp.getDataList()) {
                jsonArray.put(convertBuildRevisionParametersToJSONObject(brp));
            }
        }

        object.put("hasPermissions", userHasPermissions);
        object.put("contentTable", jsonArray);
        object.put("iTotalRecords", resp.getTotalRows());
        object.put("iTotalDisplayRecords", resp.getTotalRows());

        item.setItem(object);
        item.setResultMessage(resp.getResultMessage());
        return item;
    }
 
Example 19
Source File: HttpOneM2MOperation.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public JSONObject createContainer(ArrayList<String> labels, FoundDeviceInfo.ResourceInfo resourceInfo) {
    String parentId = "OIC-" + this.deviceId;
    String resourceUri = resourceInfo.resourceUri;
    JSONObject jsonResponse = new JSONObject();
    String resourceName = resourceInfo.resourceUri.substring(1);

    try {
        JSONObject body = new JSONObject();
        JSONObject body_wrap = new JSONObject();
        String strOrigin = parentId + resourceUri;
        JSONArray lblArray = new JSONArray();

        for(String label : labels) {
            lblArray.put(label);
        }

        Date endtime = new Date(today.getTime() + (1000 * 60 * 60 * 24 * 365)); // after one year
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddTHHmmss");

        client.openConnection();
        client.setRequestHeader(this.host, this.deviceId, strOrigin, resourceName, MemberType.CONTENT_INSTANCE);

        body.put("con", 100);
        body.put("cnf", "text/plain:0");
        body.put("lbl", lblArray);
        body.put("et", sf.format(endtime));
        body_wrap.put("cin",body);

        client.sendRequest(body_wrap);

        jsonResponse = client.getResponse();

    }catch(IOException ioe) {
        ioe.printStackTrace();

    }catch(JSONException jsone) {
        jsone.printStackTrace();
    }catch(Exception e) {
        e.printStackTrace();

    }

    return jsonResponse;


}
 
Example 20
Source File: TestUtils.java    From ambry with Apache License 2.0 3 votes vote down vote up
/**
 * Generates an array of JSON data node objects.
 * Increments basePort and sslPort for each node to ensure unique DataNode given same hostname.
 *
 * @param dataNodeCount how many data nodes to generate
 * @param hostname the hostname for each node in the array
 * @param basePort the starting standard port number for nodes generated
 * @param sslPort the starting SSL port number for nodes generated
 * @param http2Port the starting HTTP2 port number for nodes generated
 * @param hardwareState a {@link HardwareLayout} value for each node
 * @param disks a {@link JSONArray} of disks for each node
 * @return a {@link JSONArray} of nodes
 */
static JSONArray getJsonArrayDataNodes(int dataNodeCount, String hostname, int basePort, int sslPort, int http2Port,
    HardwareState hardwareState, JSONArray disks) throws JSONException {
  JSONArray jsonArray = new JSONArray();
  for (int i = 0; i < dataNodeCount; ++i) {
    jsonArray.put(getJsonDataNode(hostname, basePort + i, sslPort + i, http2Port + i, hardwareState, disks));
  }
  return jsonArray;
}