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 File: UserController.java    From ssm-demo with 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 #2
Source File: MergeRequestRest.java    From mobi with 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 #3
Source File: GeoServerRestClient.java    From geowave with 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 #4
Source File: VoteDeleted.java    From gerrit-events with 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 #5
Source File: SparqlRestTest.java    From mobi with 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 #6
Source File: ParallelsDesktopConnectorSlaveComputer.java    From jenkins-parallels with 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 #7
Source File: HistoDbClientImpl.java    From ipst with 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 #8
Source File: WorkflowController.java    From openemm with 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 #9
Source File: DatasetRestTest.java    From mobi with 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 #10
Source File: CatalogRestTest.java    From mobi with 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 #11
Source File: UsergroupClient.java    From primecloud-controller with 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 #12
Source File: JSONHelper.java    From jeecg with 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 #13
Source File: Config.java    From pdf-extract with 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 #14
Source File: RemoteApiITest.java    From warnings-ng-plugin with 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 #15
Source File: Http.java    From BotLibre with 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 #16
Source File: FavoriteListStatePreloader.java    From blueocean-plugin with 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 #17
Source File: JwDataCubeAPI.java    From jeewx-api with 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 #18
Source File: ValueConverter.java    From geowave with 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 #19
Source File: AgencyUserController.java    From wangmarket with 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 #20
Source File: UsergroupClient.java    From primecloud-controller with 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 File: JsonTools.java    From sso-oauth2 with 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 #22
Source File: WebhookJobPropertyDescriptor.java    From office-365-connector-plugin with 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 #23
Source File: HiddenFilesScanRule.java    From zap-extensions with 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 #24
Source File: GoodsAction.java    From xxshop with 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 #25
Source File: MarathonRecorderTest.java    From marathon-plugin with 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 #26
Source File: JsonUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * java对象序列化返回json字符串
 * @param obj
 * @return
 */
public static String toJson(Object obj){
    try {
        if(obj instanceof Collection){
            return JSONArray.fromObject(obj).toString();
        }else{
            return JSONObject.fromObject(obj).toString();
        }
    } catch (Exception e) {
        logger.warn("write to json string error:" + obj, e);
        return null;
    }
}
 
Example #27
Source File: JsonResponseReturnUtil.java    From JavaWeb with 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());  
}
 
Example #28
Source File: ConceptMapping.java    From Criteria2Query with Apache License 2.0 5 votes vote down vote up
public static String generateConceptSetByConcepts(List<Concept> concepts){
	//type 1 concept 1  VS. concept 1 and concept 2
	//[{"conceptId":201826,"isExcluded":0,"includeDescendants":1,"includeMapped":1},{"conceptId":316866,"isExcluded":0,"includeDescendants":1,"includeMapped":1}]
	JSONArray conceptSet=new JSONArray();
	for(Concept c:concepts){
		JSONObject jo=formatOneitem(c.getCONCEPT_ID());
		conceptSet.add(jo);		
	}
	//System.out.println("conceptSet="+conceptSet.toString());	
	return conceptSet.toString();
}
 
Example #29
Source File: JsonSecurityRule.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public SecurityRuleExpression toExpression(double purityThreshold) {
    JSONArray inputs = jsonTree.getJSONArray("attributes");
    JSONObject tree = jsonTree.getJSONObject("tree");
    JSONObject stats = jsonTree.getJSONObject("stats");

    int trueIdx = Integer.MIN_VALUE;
    JSONArray symbols = tree.getJSONArray("symbols");
    for (int i = 0; i < symbols.size(); i++) {
        if ("true".equals(symbols.get(i))) {
            trueIdx = i;
        }
    }

    JSONObject root = tree.getJSONObject("root");
    if (treeSize == 1) {
        return new SecurityRuleExpression(id, isTrueCondition(stats, root, purityThreshold, trueIdx) ? SecurityRuleStatus.ALWAYS_SECURE : SecurityRuleStatus.ALWAYS_UNSECURE, null);
    } else {
        List<SecondLevelNode> trueConditions = new ArrayList<>(1);
        processTreeNode(root, inputs, purityThreshold, null, trueConditions, stats, trueIdx);

        if (trueConditions.isEmpty()) {
            return new SecurityRuleExpression(id, SecurityRuleStatus.ALWAYS_UNSECURE, null);
        } else {
            SecondLevelNode n = null;
            for (SecondLevelNode trueCondition: trueConditions) {
                if (n != null) {
                    n = new OrOperator(n, trueCondition);
                } else {
                    n = trueCondition;
                }
            }
            return new SecurityRuleExpression(id, SecurityRuleStatus.SECURE_IF, n);
        }
    }
}
 
Example #30
Source File: AdminRequestLogController.java    From wangmarket with Apache License 2.0 5 votes vote down vote up
/**
 * 折线图,当月(最近30天),每天的访问情况
 */
@RequiresPermissions("adminRequestLogFangWen")
@RequestMapping("dayLineForCurrentMonth${url.suffix}")
@ResponseBody
public RequestLogDayLineVO dayLineForCurrentMonth(HttpServletRequest request) throws LogException{
	RequestLogDayLineVO vo = new RequestLogDayLineVO();
	
	//当前10位时间戳
	int currentTime = DateUtil.timeForUnix10();
	String query = "Mozilla | timeslice 24h | count as c";
	
	//当月访问量统计
	ArrayList<QueriedLog> jinriQlList = Log.aliyunLogUtil.queryList(query, "", DateUtil.getDateZeroTime(currentTime - 2592000), currentTime, 0, 100, true);
	
	JSONArray jsonArrayDate = new JSONArray();	//天数
	JSONArray jsonArrayFangWen = new JSONArray();	//某天访问量,pv
	for (int i = 0; i < jinriQlList.size(); i++) {
		LogItem li = jinriQlList.get(i).GetLogItem();
		JSONObject json = JSONObject.fromObject(li.ToJsonString());
		try {
			jsonArrayDate.add(DateUtil.dateFormat(json.getInt("logtime"), "MM-dd"));
		} catch (NotReturnValueException e) {
			e.printStackTrace();
		}
		jsonArrayFangWen.add(json.getInt("c"));
	}
	vo.setJsonArrayFangWen(jsonArrayFangWen);
	vo.setJsonArrayDate(jsonArrayDate);
	
	AliyunLog.addActionLog(0, "总管理后台,获取最近30天的访问数据统计记录");
	
	return vo;
}