net.sf.json.JSONArray Java Examples

The following examples show how to use net.sf.json.JSONArray. 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: geowave   Author: locationtech   File: GeoServerRestClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a list of geoserver styles
 */
public Response getStyles() {
  final Response resp = getWebTarget().path("rest/styles.json").request().get();

  if (resp.getStatus() == Status.OK.getStatusCode()) {

    resp.bufferEntity();

    // get the style names
    final JSONArray styleArray =
        getArrayEntryNames(
            JSONObject.fromObject(resp.readEntity(String.class)),
            "styles",
            "style");

    final JSONObject stylesObj = new JSONObject();
    stylesObj.put("styles", styleArray);

    return Response.ok(stylesObj.toString(defaultIndentation)).build();
  }

  return resp;
}
 
Example #2
Source Project: mobi   Author: inovexcorp   File: SparqlRestTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getPagedResultsWithLinksTest() {
    Response response = target().path("sparql/page").queryParam("query", ALL_QUERY)
            .queryParam("limit", 1).queryParam("offset", 1).request().get();
    assertEquals(response.getStatus(), 200);
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + testModel.size());
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 2);
    links.forEach(link -> {
        assertTrue(link.getUri().getRawPath().contains("sparql/page"));
        assertTrue(link.getRel().equals("prev") || link.getRel().equals("next"));
    });
    JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
    assertTrue(result.containsKey("bindings"));
    assertTrue(result.containsKey("data"));
    JSONArray data = result.getJSONArray("data");
    assertEquals(data.size(), 1);
}
 
Example #3
Source Project: gerrit-events   Author: sonyxperiadev   File: VoteDeleted.java    License: MIT License 6 votes vote down vote up
@Override
public void fromJson(JSONObject json) {
    super.fromJson(json);
    comment = getString(json, COMMENT);
    if (json.containsKey(REVIEWER)) {
        this.reviewer = new Account(json.getJSONObject(REVIEWER));
    }
    if (json.containsKey(REMOVER)) {
        this.remover = new Account(json.getJSONObject(REMOVER));
    }
    if (json.containsKey(APPROVALS)) {
        JSONArray eventApprovals = json.getJSONArray(APPROVALS);
        for (int i = 0; i < eventApprovals.size(); i++) {
            approvals.add(new Approval(eventApprovals.getJSONObject(i)));
        }
    }
}
 
Example #4
Source Project: mobi   Author: inovexcorp   File: MergeRequestRest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves a list of all the {@link MergeRequest}s in Mobi sorted according to the provided parameters
 * and optionally filtered by whether or not they are accepted.
 *
 * @param sort The IRI of the predicate to sort by
 * @param asc Whether the results should be sorted ascending or descending. Default is false.
 * @param accepted Whether the results should only be accepted or open requests
 * @return The list of all {@link MergeRequest}s that match the criteria
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Retrieves all MergeRequests in the application")
public Response getMergeRequests(@QueryParam("sort") String sort,
                          @DefaultValue("false") @QueryParam("ascending") boolean asc,
                          @DefaultValue("false") @QueryParam("accepted") boolean accepted) {
    MergeRequestFilterParams.Builder builder = new MergeRequestFilterParams.Builder();
    if (!StringUtils.isEmpty(sort)) {
        builder.setSortBy(createIRI(sort, vf));
    }
    builder.setAscending(asc).setAccepted(accepted);
    try {
        JSONArray result = JSONArray.fromObject(manager.getMergeRequests(builder.build()).stream()
                .map(request -> modelToJsonld(request.getModel(), transformer))
                .map(RestUtils::getObjectFromJsonld)
                .collect(Collectors.toList()));
        return Response.ok(result).build();
    } catch (IllegalStateException | MobiException ex) {
        throw ErrorUtils.sendError(ex, ex.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #5
Source Project: jenkins-parallels   Author: Parallels   File: ParallelsDesktopConnectorSlaveComputer.java    License: MIT License 6 votes vote down vote up
public boolean checkVmExists(String vmId)
{
	try
	{
		RunVmCallable command = new RunVmCallable("list", "-i", "--json");
		String callResult = forceGetChannel().call(command);
		JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult);
		for (int i = 0; i < vms.size(); i++)
		{
			JSONObject vmInfo = vms.getJSONObject(i);
			if (vmId.equals(vmInfo.getString("ID")) || vmId.equals(vmInfo.getString("Name")))
				return true;
		}
		return true;
	}
	catch (Exception ex)
	{
		LOGGER.log(Level.SEVERE, ex.toString());
	}
	return false;
}
 
Example #6
Source Project: ipst   Author: itesla   File: HistoDbClientImpl.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public Collection<Collection<String>> getTopologyDescription(String id, String topoHash) {
    try (InputStream is = httpClient.getHttpRequest(new HistoDbUrl(config, "itesla/topos/" + id + "/" + topoHash + ".json", Collections.emptyMap()))) {
        byte[] bytes = ByteStreams.toByteArray(is);

        Collection<Collection<String>> result = new HashSet<>();

        JSONArray topology = JSONArray.fromObject(new String(bytes, Charset.forName("UTF-8")));
        for (int i = 0; i < topology.size(); i++) {
            JSONArray jsonConnectedSet = topology.getJSONArray(i);
            Collection<String> connectedSet = Arrays.asList((String[]) jsonConnectedSet.toArray(new String[]{}));

            result.add(connectedSet);
        }

        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source Project: openemm   Author: agnitas-org   File: WorkflowController.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@GetMapping("/list.action")
public String list(ComAdmin admin, @ModelAttribute("workflowForm") PaginationForm form, Model model) {
    FormUtils.syncNumberOfRows(webStorage, ComWebStorage.WORKFLOW_OVERVIEW, form);

    JSONArray workflows = workflowService.getWorkflowListJson(admin);
    model.addAttribute("workflowsJson", workflows);

    model.addAttribute("adminTimeZone", admin.getAdminTimezone());
    SimpleDateFormat dateTimeFormat = admin.getDateTimeFormat();
    model.addAttribute("adminDateTimeFormat", dateTimeFormat.toPattern());
    SimpleDateFormat dateFormat = admin.getDateFormat();
    model.addAttribute("adminDateFormat", dateFormat.toPattern());
    SimpleDateFormat timeFormat = admin.getTimeFormat();
    model.addAttribute("adminTimeFormat", timeFormat.toPattern());
    SimpleDateFormat dateTimeFormatWithSeconds = admin.getDateTimeFormatWithSeconds();
    model.addAttribute("adminDateTimeFormatWithSeconds", dateTimeFormatWithSeconds.toPattern());

    return "workflow_list";
}
 
Example #8
Source Project: mobi   Author: inovexcorp   File: DatasetRestTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getDatasetRecordsWithLinksTest() {
    // Setup:
    when(results.getPage()).thenReturn(Collections.singletonList(record2));
    when(results.getPageNumber()).thenReturn(2);
    when(results.getPageSize()).thenReturn(1);

    Response response = target().path("datasets").queryParam("offset", 1).queryParam("limit", 1).request().get();
    assertEquals(response.getStatus(), 200);
    verify(datasetManager).getDatasetRecords(any(DatasetPaginatedSearchParams.class));
    verify(service, atLeastOnce()).skolemize(any(Statement.class));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "3");
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 2);
    assertTrue(response.hasLink("prev"));
    assertTrue(response.hasLink("next"));
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example #9
Source Project: mobi   Author: inovexcorp   File: CatalogRestTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void mergeWithErrorTest() {
    // Setup:
    doThrow(new MobiException()).when(versioningManager).merge(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), eq(vf.createIRI(BRANCH_IRI)), eq(vf.createIRI(BRANCH_IRI)), any(User.class), any(Model.class), any(Model.class));
    JSONArray adds = new JSONArray();
    adds.add(new JSONObject().element("@id", "http://example.com/add").element("@type", new JSONArray().element("http://example.com/Add")));
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("additions", adds.toString());

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/branches/" + encode(BRANCH_IRI) + "/conflicts/resolution")
            .queryParam("targetId", BRANCH_IRI).request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);

    doThrow(new IllegalStateException()).when(versioningManager).merge(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), eq(vf.createIRI(BRANCH_IRI)), eq(vf.createIRI(BRANCH_IRI)), any(User.class), any(Model.class), any(Model.class));
    response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/branches/" + encode(BRANCH_IRI) + "/conflicts/resolution")
            .queryParam("targetId", BRANCH_IRI).request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 500);
}
 
Example #10
Source Project: primecloud-controller   Author: primecloud-controller-org   File: UsergroupClient.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ユーザグループ情報を更新します。
 * usrgrpidパラメータを必ず指定する必要があります。<br/>
 * @param param {@link UsergroupUpdateParam}
 * @return 更新されたユーザグループ情報のusrgrpidのリスト
 */
@SuppressWarnings("unchecked")
public List<String> update(UsergroupUpdateParam param) {
    if (param.getUsrgrpid() == null || param.getUsrgrpid().length() == 0) {
        throw new IllegalArgumentException("usrgrpid is required.");
    }

    JSONObject params = JSONObject.fromObject(param, defaultConfig);
    if (accessor.checkVersion("2.0") >= 0) {
        // api_accessは2.0以降で廃止されたパラメータ
        if (params.containsKey("api_access")) {
            params.remove("api_access");
        }
    }

    JSONObject result = (JSONObject) accessor.execute("usergroup.update", params);

    JSONArray usrgrpids = result.getJSONArray("usrgrpids");
    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(String.class);
    return (List<String>) JSONArray.toCollection(usrgrpids, config);
}
 
Example #11
Source Project: jeecg   Author: zhangdaiscott   File: JSONHelper.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>泛型T 代表主实体类型
 * @param <D1>泛型D1 代表从实体类型
 * @param <D2>泛型D2 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName1
 *            从实体类在主实体类中的属性
 * @param detailClass1
 *            从实体类型
 * @param detailName2
 *            从实体类在主实体类中的属性
 * @param detailClass2
 *            从实体类型
 * @param detailName3
 *            从实体类在主实体类中的属性
 * @param detailClass3
 *            从实体类型
 * @return
 */
public static <T, D1, D2, D3> T toBean(String jsonString,
		Class<T> mainClass, String detailName1, Class<D1> detailClass1,
		String detailName2, Class<D2> detailClass2, String detailName3,
		Class<D3> detailClass3) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
	JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
	JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);

	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1);
	List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2);
	List<D3> detailList3 = JSONHelper.toList(jsonArray3, detailClass3);

	try {
		BeanUtils.setProperty(mainEntity, detailName1, detailList1);
		BeanUtils.setProperty(mainEntity, detailName2, detailList2);
		BeanUtils.setProperty(mainEntity, detailName3, detailList3);
	} catch (Exception ex) {
		throw new RuntimeException("主从关系JSON反序列化实体失败!");
	}

	return mainEntity;
}
 
Example #12
Source Project: pdf-extract   Author: bitextor   File: Config.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<JoinWordInfo> getJoinWordsList(JSONArray jArray) {
	List<JoinWordInfo> list = new ArrayList<>();
	if (jArray != null) {
		for (int j = 0, jlen = jArray.size(); j < jlen; j++) {

			JSONArray jNormalize = (JSONArray) jArray.get(j);

			String front = jNormalize.getString(0);
			String back = jNormalize.getString(1);
			String replace = jNormalize.getString(2);

			JoinWordInfo joinw = new JoinWordInfo();
			joinw.front = front;
			joinw.back = back;
			joinw.joinText = replace;
			list.add(joinw);
		}
	}
	return list;
}
 
Example #13
Source Project: marathon-plugin   Author: jenkinsci   File: MarathonRecorderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that URIs are properly put through replace macro.
 *
 * @throws Exception
 */
@Test
public void testRecorderURIsMacro() throws Exception {
    final List<MarathonUri> uris             = new ArrayList<>(2);
    final MarathonRecorder  marathonRecorder = new MarathonRecorder(TestUtils.getHttpAddresss(httpServer));

    uris.add(new MarathonUri("http://example.com/${BUILD_NUMBER}"));
    uris.add(new MarathonUri("http://again.example.com/$BUILD_NUMBER"));
    marathonRecorder.setUris(uris);

    final FreeStyleProject project = basicSetup(marathonRecorder);
    final FreeStyleBuild   build   = basicRunWithSuccess(project);

    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    final JSONObject   jsonRequest = TestUtils.jsonFromRequest(httpServer);
    final JSONArray    urisList    = jsonRequest.getJSONArray("uris");
    final String       buildNumber = String.valueOf(build.getNumber());
    final List<String> buildUris   = new ArrayList<>(Arrays.asList("http://example.com/" + buildNumber, "http://again.example.com/" + buildNumber));

    for (Object uriObj : urisList) {
        String uri = (String) uriObj;
        assertTrue("Invalid URI", buildUris.contains(uri));
    }
}
 
Example #14
Source Project: BotLibre   Author: BotLibre   File: Http.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the count of the JSON result array.
 */
public int countJSON(String url, String attribute, Network network) {
	log("COUNT JSON", Level.INFO, url, attribute);
	try {
		String json = Utils.httpGET(url);
		log("JSON", Level.FINE, json);
		JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim());
		if (root == null) {
			return 0;
		}
		Object value = root.get(attribute);
		if (value == null) {
			return 0;
		}
		if (value instanceof JSONArray) {
			return ((JSONArray)value).size();
		}
		return 1;
	} catch (Exception exception) {
		log(exception);
		return 0;
	}
}
 
Example #15
Source Project: warnings-ng-plugin   Author: jenkinsci   File: RemoteApiITest.java    License: MIT License 6 votes vote down vote up
/** Verifies that the remote API for the tools aggregation correctly returns the summary. */
@Test
public void shouldReturnAggregation() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles("checkstyle1.xml", "checkstyle2.xml");
    enableWarnings(project, createCheckstyle("**/checkstyle1*"),
            configurePattern(new Pmd()), configurePattern(new SpotBugs()));
    Run<?, ?> build = buildWithResult(project, Result.SUCCESS);

    JSONWebResponse json = callJsonRemoteApi(build.getUrl() + "warnings-ng/api/json");
    JSONObject result = json.getJSONObject();

    assertThatJson(result).node("tools").isArray().hasSize(3);
    JSONArray tools = result.getJSONArray("tools");

    assertThatToolsContains(tools, "checkstyle", "CheckStyle Warnings", 3);
    assertThatToolsContains(tools, "pmd", "PMD Warnings", 0);
    assertThatToolsContains(tools, "spotbugs", "SpotBugs Warnings", 0);
}
 
Example #16
Source Project: xxshop   Author: StevenWash   File: GoodsAction.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * goodsIds用来接收来自前台的数据:包含了categoryId和num的json字符串
	 * result 则返回查询到的信息,也是封装成了一个json字符串
	 * @param goodsIds
	 * @param model
	 * @return
	 */
	@RequestMapping("/getGoodsesByIds")
	public String getGoodsesByIds(String goodsIds, Model model) {
//		System.out.println("goodsIds:" + goodsIds);
		String[] ids = goodsIds.split(",");
//		for (String s : ids) {
//			System.out.println("test:" + s);
//		}
//		System.out.println("test:" + ids.toString());
		List<Goods> goodses = goodsService.getGoodsByIds(ids);
		JsonConfig c = new JsonConfig();
		c.setExcludes(new String[] { "category", "goodsNo", "categoryId",
				"price1", "stock", "description", "role", "sellTime",
				"sellNum", "score" });
		JSONArray a = JSONArray.fromObject(goodses, c);
		String result = a.toString();
		model.addAttribute("result", result);
		System.out.println(result);
//		System.out.println("result:" + result);
		return "/TestJSP.jsp";
//		return "getgoodsesbyids";

	}
 
Example #17
Source Project: zap-extensions   Author: zaproxy   File: HiddenFilesScanRule.java    License: Apache License 2.0 6 votes vote down vote up
private static List<String> getOptionalList(JSONObject jsonObj, String key) {
    if (!jsonObj.has(key)) {
        return Collections.emptyList();
    }
    JSONArray jsonArray;
    try {
        jsonArray = jsonObj.getJSONArray(key);
    } catch (JSONException jEx) {
        LOG.warn("Unable to parse JSON (" + key + ").", jEx);
        return Collections.emptyList();
    }
    List<String> newList = new ArrayList<>();
    for (int x = 0; x < jsonArray.size(); x++) {
        newList.add(jsonArray.getString(x));
    }
    return newList;
}
 
Example #18
Source Project: office-365-connector-plugin   Author: jenkinsci   File: WebhookJobPropertyDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public WebhookJobProperty newInstance(StaplerRequest req, JSONObject formData) {

    List<Webhook> webhooks = new ArrayList<>();
    if (formData != null && !formData.isNullObject()) {
        JSON webhooksData = (JSON) formData.get("webhooks");
        if (webhooksData != null && !webhooksData.isEmpty()) {
            if (webhooksData.isArray()) {
                JSONArray webhooksArrayData = (JSONArray) webhooksData;
                webhooks.addAll(req.bindJSONToList(Webhook.class, webhooksArrayData));
            } else {
                JSONObject webhooksObjectData = (JSONObject) webhooksData;
                webhooks.add(req.bindJSON(Webhook.class, webhooksObjectData));
            }
        }
    }
    return new WebhookJobProperty(webhooks);
}
 
Example #19
Source Project: sso-oauth2   Author: kongbigliang   File: JsonTools.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 
* json转换map.
* <br>详细说明
* @param jsonStr json字符串
* @return
* @return Map<String,Object> 集合
* @throws
* @author slj
*/
public static Map<String, Object> parseJSON2Map(String jsonStr) {
	ListOrderedMap map = new ListOrderedMap();
	// System.out.println(jsonStr);
	// 最外层解析
	JSONObject json = JSONObject.fromObject(jsonStr);
	for (Object k : json.keySet()) {
		Object v = json.get(k);
		// 如果内层还是数组的话,继续解析
		if (v instanceof JSONArray) {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Iterator<JSONObject> it = ((JSONArray) v).iterator();
			while (it.hasNext()) {
				JSONObject json2 = it.next();
				list.add(parseJSON2Map(json2.toString()));
			}
			map.put(k.toString(), list);
		} else {
			map.put(k.toString(), v);
		}
	}
	return map;
}
 
Example #20
Source Project: primecloud-controller   Author: primecloud-controller-org   File: UsergroupClient.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ユーザグループ情報とユーザ情報、権限情報を紐付けます。
 * userids,usrgrpidsパラメータを必ず指定する必要があります。<br/>
 * @param param {@link UsergroupMassAddParam}
 * @return 更新されたユーザグループ情報のusrgrpidのリスト
 */
public List<String> massAdd(UsergroupMassAddParam param) {
    if (param.getUserids() == null || param.getUserids().isEmpty()) {
        throw new IllegalArgumentException("userids is required.");
    }
    if (param.getUsrgrpids() == null || param.getUsrgrpids().isEmpty()) {
        throw new IllegalArgumentException("usrgrpids is required.");
    }
    JSONObject params = JSONObject.fromObject(param, defaultConfig);
    JSONObject result = (JSONObject) accessor.execute("usergroup.massAdd", params);

    JSONArray usrgrpids = result.getJSONArray("usrgrpids");
    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(String.class);

    // Zabbix 2.2.9でusrgrpidsが数値のArrayとして返ってくることへの対応
    List<?> ids = (List<?>) JSONArray.toCollection(usrgrpids, config);
    List<String> resultIds = new ArrayList<String>();
    for (Object id : ids) {
        resultIds.add(id.toString());
    }
    return resultIds;
}
 
Example #21
Source Project: wangmarket   Author: xnx3   File: AgencyUserController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 资金变动日志
 * @throws LogException 
 */
@RequiresPermissions("agencySiteSizeLogList")
@RequestMapping("siteSizeLogList${url.suffix}")
public String siteSizeLogList(HttpServletRequest request, Model model) throws LogException{
	if(SiteSizeChangeLog.aliyunLogUtil == null){
		return error(model, "未开启日志服务");
	}
	//当前10位时间戳
	String query = "userid="+getUserId();
	AliyunLogPageUtil log = new AliyunLogPageUtil(SiteSizeChangeLog.aliyunLogUtil);
	
	//得到当前页面的列表数据
	JSONArray jsonArray = log.list(query, "", true, 15, request);
	
	//得到当前页面的分页相关数据(必须在执行了list方法获取列表数据之后,才能调用此处获取到分页)
	Page page = log.getPage();
	//设置分页,出现得上几页、下几页跳转按钮的个数
	page.setListNumber(2);
	
	model.addAttribute("list", jsonArray);
	model.addAttribute("page", page);
	
	return "agency/siteSizeLogList";
}
 
Example #22
Source Project: geowave   Author: locationtech   File: ValueConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert value into the specified type
 *
 * @param <X> Class to convert to
 * @param value Value to convert from
 * @param targetType Type to convert into
 * @return The converted value
 */
@SuppressWarnings("unchecked")
public static <X> X convert(final Object value, final Class<X> targetType) {
  // HP Fortify "Improper Output Neutralization" false positive
  // What Fortify considers "user input" comes only
  // from users with OS-level access anyway
  LOGGER.trace("Attempting to convert " + value + " to class type " + targetType);
  if (value != null) {
    // if object is already in intended target type, no need to convert
    // it, just return as it is
    if (value.getClass() == targetType) {
      return (X) value;
    }

    if ((value.getClass() == JSONObject.class) || (value.getClass() == JSONArray.class)) {
      return (X) value;
    }
  }

  final String strValue = String.valueOf(value);
  final Object retval = ConvertUtils.convert(strValue, targetType);
  return (X) retval;
}
 
Example #23
Source Project: jeewx-api   Author: zhangdaiscott   File: JwDataCubeAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取消息发送月数据
 * @param bDate 起始时间
 * @param eDate 结束时间
 * @return
 * @throws WexinReqException
 */
public static List<WxDataCubeStreamMsgMonthInfo> getWxDataCubeStreamMsgMonthInfo(String accesstoken,String bDate,String eDate) throws WexinReqException {
	if (accesstoken != null) {
		
		// 封装请求参数
		WxDataCubeStreamMsgMonthParam msgParam = new WxDataCubeStreamMsgMonthParam();
		msgParam.setAccess_token(accesstoken);
		msgParam.setBegin_date(bDate);
		msgParam.setEnd_date(eDate);
		
		// 调用接口
		String requestUrl = GETUPSTREAMMSGMONTH_URL.replace("ACCESS_TOKEN", accesstoken);
		JSONObject obj = JSONObject.fromObject(msgParam);
		JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
		Object error = result.get("errcode");

		// 无错误消息时 返回数据对象
		JSONArray arrayResult = result.getJSONArray("list");
		// 正常返回
		List<WxDataCubeStreamMsgMonthInfo> msgInfoList = null;
		msgInfoList=JSONHelper.toList(arrayResult, WxDataCubeStreamMsgMonthInfo.class);
		return msgInfoList;
	}
	return null;
}
 
Example #24
Source Project: blueocean-plugin   Author: jenkinsci   File: FavoriteListStatePreloader.java    License: MIT License 6 votes vote down vote up
@CheckForNull
@Override
public String getStateJson() {
    User jenkinsUser = User.current();
    if (jenkinsUser == null) {
        return null;
    }
    FavoriteUserProperty fup = jenkinsUser.getProperty(FavoriteUserProperty.class);
    if (fup == null) {
        return null;
    }
    Set<String> favorites = fup.getAllFavorites();
    if (favorites == null) {
        return null;
    }
    return JSONArray.fromObject(favorites).toString();
}
 
Example #25
Source Project: ssm-demo   Author: ZHENFENG13   File: UserController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param page
 * @param rows
 * @param s_user
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/list")
public String list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, User s_user, HttpServletResponse response) throws Exception {
    PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("userName", StringUtil.formatLike(s_user.getUserName()));
    map.put("start", pageBean.getStart());
    map.put("size", pageBean.getPageSize());
    List<User> userList = userService.findUser(map);
    Long total = userService.getTotalUser(map);
    JSONObject result = new JSONObject();
    JSONArray jsonArray = JSONArray.fromObject(userList);
    result.put("rows", jsonArray);
    result.put("total", total);
    log.info("request: user/list , map: " + map.toString());
    ResponseUtil.write(response, result);
    return null;
}
 
Example #26
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: JSONConverter.java    License: Apache License 2.0 5 votes vote down vote up
private static JSONArray calculateIntervals(List<SampleResult> list) {
    Map<Long, List<SampleResult>> intervals = new HashMap<>();

    for (SampleResult sample : list) {
        long time = sample.getEndTime() / 1000;
        if (!intervals.containsKey(time)) {
            intervals.put(time, new LinkedList<SampleResult>());
        }
        intervals.get(time).add(sample);
    }

    JSONArray result = new JSONArray();
    for (Long second : intervals.keySet()) {
        JSONObject intervalResult = new JSONObject();

        List<SampleResult> intervalValues = intervals.get(second);

        intervalResult.put("ts", second);
        intervalResult.put("n", intervalValues.size());
        intervalResult.put("rc", generateResponseCodec(intervalValues));
        int fails = getFails(intervalValues);
        intervalResult.put("ec", fails);
        intervalResult.put("failed", fails);
        intervalResult.put("na", getThreadsCount(intervalValues));

        final Map<String, Object> mainMetrics = getMainMetrics(intervalValues);
        int intervalSize = intervalValues.size();
        intervalResult.put("t", generateTimestamp(mainMetrics, intervalSize));
        intervalResult.put("lt", generateLatencyTime(mainMetrics, intervalSize));
        intervalResult.put("by", generateBytes(mainMetrics, intervalSize));

        result.add(intervalResult);
    }

    return result;
}
 
Example #27
Source Project: mobi   Author: inovexcorp   File: ExplorableDatasetRestTest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createInstanceTest() {
    //Setup:
    JSONObject instance = new JSONObject().element("@id", NEW_INSTANCE_ID_STR).element(_Thing.title_IRI,
            new JSONArray().element(new JSONObject().element("@value", "title")));

    Response response = target().path("explorable-datasets/" + encode(RECORD_ID_STR) + "/instances").request()
            .post(Entity.json(instance.toString()));
    assertEquals(response.getStatus(), 201);
    assertEquals(response.readEntity(String.class), NEW_INSTANCE_ID_STR);
}
 
Example #28
Source Project: SmartEducation   Author: lawlite19   File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static JSONArray jsonListFilter(List objList, String[] filterNames){
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setIgnoreDefaultExcludes(false);    
    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);    //防止自包含 
    //jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
    if(filterNames != null){
        //这里是核心,过滤掉不想使用的属性
        jsonConfig .setExcludes(filterNames) ;
    }
    JSONArray jsonArray = JSONArray.fromObject(objList, jsonConfig);
    return jsonArray;
}
 
Example #29
Source Project: primecloud-controller   Author: primecloud-controller-org   File: ItemClient.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * アイテム情報を削除します。<br/>
 * itemidsパラメータを必ず指定する必要があります。<br/>
 * 存在しないitemidを指定した場合、例外をスローします。
 *
 * @param itemids itemids
 * @return 削除したアイテム情報のitemidのリスト
 */
public List<String> delete(List<String> itemids) {
    if (itemids == null || itemids.isEmpty()) {
        throw new IllegalArgumentException("itemid is required.");
    }

    JSONArray params = JSONArray.fromObject(itemids, defaultConfig);
    JSONObject result = (JSONObject) accessor.execute("item.delete", params);

    JSONArray itemIds = result.getJSONArray("itemids");
    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(String.class);

    List<?> list = (List<?>) JSONArray.toCollection(itemIds, config);

    List<String> itemIdsList = new ArrayList<String>();
    for (Object object : list) {
        if (object instanceof String) {
            itemIdsList.add(String.class.cast(object));
        } else {
            itemIdsList.add(object.toString());
        }
    }

    return itemIdsList;
}
 
Example #30
Source Project: JavaWeb   Author: tank2140896   File: JsonResponseReturnUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void jsonOut(HttpServletResponse response,Object obj) throws IOException{
	PrintWriter printWriter = response.getWriter();
	response.setCharacterEncoding("UTF-8");   
	response.setHeader("Cache-Control", "no-cache");   
	if(obj instanceof JSONObject){
		obj = JSONObject.fromObject(obj);
	}else if(obj instanceof JSONArray){
		obj = JSONArray.fromObject(obj);
	}else{
		obj = "";
	}
	printWriter.write(obj.toString());  
}