Java Code Examples for net.sf.json.JSONArray#fromObject()

The following examples show how to use net.sf.json.JSONArray#fromObject() . 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: DingTalkGlobalConfig.java    From dingtalk-plugin with MIT License 6 votes vote down vote up
@Override
  public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
//    System.out.println("============ old form data =============");
//    System.out.println(json.toString());
    Object robotConfigObj = json.get("robotConfigs");
    if (robotConfigObj == null) {
      json.put("robotConfigs", new JSONArray());
    } else {
      JSONArray robotConfigs = JSONArray.fromObject(robotConfigObj);
      robotConfigs.removeIf(item -> {
        JSONObject jsonObject = JSONObject.fromObject(item);
        String webhook = jsonObject.getString("webhook");
        return StringUtils.isEmpty(webhook);
      });
    }
//    System.out.println("============ new form data =============");
//    System.out.println(json.toString());
    req.bindJSON(this, json);
    this.save();
    return super.configure(req, json);
  }
 
Example 2
Source File: JSONHelper.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/***
 * 将对象转换为List对象
 * 
 * @param object
 * @return
 */
public static List toArrayList(Object object) {
	List arrayList = new ArrayList();

	JSONArray jsonArray = JSONArray.fromObject(object);

	Iterator it = jsonArray.iterator();
	while (it.hasNext()) {
		JSONObject jsonObject = (JSONObject) it.next();

		Iterator keys = jsonObject.keys();
		while (keys.hasNext()) {
			Object key = keys.next();
			Object value = jsonObject.get(key);
			arrayList.add(value);
		}
	}

	return arrayList;
}
 
Example 3
Source File: StateRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getStatesWithoutFiltersTest() {
    Response response = target().path("states").request().get();
    assertEquals(response.getStatus(), 200);
    verify(stateManager).getStates(anyString(), anyString(), anySetOf(Resource.class));
    try {
        String str = response.readEntity(String.class);
        JSONArray arr = JSONArray.fromObject(str);
        assertEquals(results.size(), arr.size());
        for (int i = 0; i < arr.size(); i++) {
            JSONObject object = arr.optJSONObject(i);
            assertNotNull(object);
            assertTrue(results.keySet().contains(vf.createIRI(object.get("id").toString())));
        }
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 4
Source File: JSONHelper.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/***
 * 将对象转换为List对象
 * 
 * @param object
 * @return
 */
public static List toArrayList(Object object) {
	List arrayList = new ArrayList();

	JSONArray jsonArray = JSONArray.fromObject(object);

	Iterator it = jsonArray.iterator();
	while (it.hasNext()) {
		JSONObject jsonObject = (JSONObject) it.next();

		Iterator keys = jsonObject.keys();
		while (keys.hasNext()) {
			Object key = keys.next();
			Object value = jsonObject.get(key);
			arrayList.add(value);
		}
	}

	return arrayList;
}
 
Example 5
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 6
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 6 votes vote down vote up
/***
 * 将对象转换为List<Map<String,Object>>
 * 
 * @param object
 * @return
 */
// 返回非实体类型(Map<String,Object>)的List
public static List<Map<String, Object>> toList(Object object) {
	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	JSONArray jsonArray = JSONArray.fromObject(object);
	for (Object obj : jsonArray) {
		JSONObject jsonObject = (JSONObject) obj;
		Map<String, Object> map = new HashMap<String, Object>();
		Iterator it = jsonObject.keys();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = jsonObject.get(key);
			map.put((String) key, value);
		}
		list.add(map);
	}
	return list;
}
 
Example 7
Source File: GroupRest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the list of users for the specified Group in Mobi.
 *
 * @param groupTitle the title of the Group to retrieve users from
 * @return a Response with a JSON array of the users of the Group in Mobi
 */
@GET
@Path("{groupTitle}/users")
@RolesAllowed("user")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("List users of a Mobi Group")
public Response getGroupUsers(@PathParam("groupTitle") String groupTitle) {
    if (StringUtils.isEmpty(groupTitle)) {
        throw ErrorUtils.sendError("Group title must be provided", Response.Status.BAD_REQUEST);
    }

    try {
        Group savedGroup = engineManager.retrieveGroup(groupTitle).orElseThrow(() ->
                ErrorUtils.sendError("Group " + groupTitle + " not found", Response.Status.BAD_REQUEST));
        Set<User> members = savedGroup.getMember_resource().stream()
                .map(iri -> engineManager.getUsername(iri).orElseThrow(() ->
                        ErrorUtils.sendError("Unable to get User: " + iri, Response.Status.INTERNAL_SERVER_ERROR)))
                .map(username -> engineManager.retrieveUser(username).orElseThrow(() ->
                        ErrorUtils.sendError("Unable to get User: " + username,
                                Response.Status.INTERNAL_SERVER_ERROR)))
                .collect(Collectors.toSet());

        JSONArray result = JSONArray.fromObject(members.stream()
                .map(member -> {
                    member.clearPassword();
                    return member.getModel().filter(member.getResource(), null, null);
                })
                .map(roleModel -> modelToJsonld(roleModel, transformer))
                .map(RestUtils::getObjectFromJsonld)
                .collect(Collectors.toList()));
        return Response.ok(result).build();
    } catch (IllegalArgumentException ex) {
        throw ErrorUtils.sendError(ex.getMessage(), Response.Status.BAD_REQUEST);
    }
}
 
Example 8
Source File: DelimitedRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void isJsonld(String str) {
    try {
        JSONArray result = JSONArray.fromObject(str);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 9
Source File: DelimitedRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void testResultsRows(Response response, List<String> expectedLines, int rowNum) {
    String body = response.readEntity(String.class);
    JSONArray lines = JSONArray.fromObject(body);
    assertEquals(lines.size(), rowNum + 1);
    for (int i = 0; i < lines.size(); i++) {
        JSONArray line = lines.getJSONArray(i);
        String expectedLine = expectedLines.get(i);
        for (Object item : line) {
            assertTrue(expectedLine.contains(item.toString()));
        }
    }
}
 
Example 10
Source File: ExplorableDatasetRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getInstanceDetailsWithNextLinkTest() {
    //Setup:
    String pathString = "explorable-datasets/" + encode(RECORD_ID_STR) + "/classes/" + encode(CLASS_ID_STR)
            + "/instance-details";

    Response response = target().path(pathString).queryParam("offset", 0).queryParam("limit", 3).request().get();
    assertEquals(response.getStatus(), 200);
    JSONArray responseArray = JSONArray.fromObject(response.readEntity(String.class));
    assertEquals(responseArray.size(), 3);
    assertEquals(response.getHeaders().get("X-Total-Count").get(0), "13");
    Link link = response.getLink("next");
    assertTrue(link.getUri().getRawPath().contains(pathString));
    assertTrue(link.getRel().equals("next"));
}
 
Example 11
Source File: BookAction.java    From sdudoc with MIT License 5 votes vote down vote up
@Action("checkDynasty")
public String checkDynasty(){
	dynastyList=bookService.checkDynasty();
	JSONArray jsonArray = JSONArray.fromObject(dynastyList);
	//ajax返回客户端
	jsonArray.toString();
	HttpServletResponse response = ServletActionContext.getResponse();
	response.setContentType("application/html;charset=UTF-8");
	try {
		response.getWriter().write(jsonArray.toString());
	} catch (IOException e) {
		e.printStackTrace();
	} 
	return null;
}
 
Example 12
Source File: CommitRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getCommitHistoryWithEntityAndTargetTest() {
    when(catalogManager.getCommitEntityChain(any(Resource.class), any(Resource.class), any(Resource.class))).thenReturn(entityCommits);
    Response response = target().path("commits/" + encode(COMMIT_IRIS[1]) + "/history")
            .queryParam("targetId", encode(COMMIT_IRIS[0]))
            .queryParam("entityId", encode(vf.createIRI("http://mobi.com/test/class5")))
            .request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager).getCommitEntityChain(vf.createIRI(COMMIT_IRIS[1]), vf.createIRI(COMMIT_IRIS[0]), vf.createIRI("http://mobi.com/test/class5"));
    MultivaluedMap<String, Object> headers = response.getHeaders();
    assertEquals(headers.get("X-Total-Count").get(0), "" + ENTITY_IRI.length);
    Set<Link> links = response.getLinks();
    assertEquals(links.size(), 0);
    links.forEach(link -> {
        assertTrue(link.getUri().getRawPath().contains("commits/" + encode(COMMIT_IRIS[1]) + "/history"));
        assertTrue(link.getRel().equals("prev") || link.getRel().equals("next"));
    });
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
        JSONObject commitObj = result.getJSONObject(0);
        assertTrue(commitObj.containsKey("id"));
        assertEquals(commitObj.getString("id"), COMMIT_IRIS[1]);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 13
Source File: ContentReviewServiceTurnitinOC.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public ArrayList<Webhook> getWebhooks() throws Exception {
	ArrayList<Webhook> webhooks = new ArrayList<>();

	HashMap<String, Object> response = makeHttpCall("GET",
			getNormalizedServiceUrl() + "webhooks",
			BASE_HEADERS,
			null,
			null);

	// Get response:
	int responseCode = !response.containsKey(RESPONSE_CODE) ? 0 : (int) response.get(RESPONSE_CODE);
	String responseMessage = !response.containsKey(RESPONSE_MESSAGE) ? "" : (String) response.get(RESPONSE_MESSAGE);
	String responseBody = !response.containsKey(RESPONSE_BODY) ? "" : (String) response.get(RESPONSE_BODY);

	if(StringUtils.isNotEmpty(responseBody) 
			&& responseCode >= 200 
			&& responseCode < 300
			&& !"[]".equals(responseBody)) {
		// Loop through response via JSON, convert objects to Webhooks
		JSONArray webhookList = JSONArray.fromObject(responseBody);
		for (int i=0; i < webhookList.size(); i++) {
			JSONObject webhookJSON = webhookList.getJSONObject(i);
			if (webhookJSON.has("id") && webhookJSON.has("url")) {
				webhooks.add(new Webhook(webhookJSON.getString("id"), webhookJSON.getString("url")));
			}
		}
	}else {
		log.info("getWebhooks: " + responseMessage);
	}
	
	return webhooks;
}
 
Example 14
Source File: CatalogRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getCatalogsWithBadTypeTest() {
    Response response = target().path("catalogs").queryParam("type", "error").request().get();
    assertEquals(response.getStatus(), 200);
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 0);
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 15
Source File: SparkJobServerClientImpl.java    From SparkJobServerClient with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<SparkJobInfo> getJobs() throws SparkJobServerClientException {
	List<SparkJobInfo> sparkJobInfos = new ArrayList<SparkJobInfo>();
	final CloseableHttpClient httpClient = buildClient();
	try {
		HttpGet getMethod = new HttpGet(jobServerUrl + "jobs");
		getMethod.setConfig(getRequestConfig());
           setAuthorization(getMethod);
		HttpResponse response = httpClient.execute(getMethod);
		int statusCode = response.getStatusLine().getStatusCode();
		String resContent = getResponseContent(response.getEntity());
		if (statusCode == HttpStatus.SC_OK) {
			JSONArray jsonArray = JSONArray.fromObject(resContent);
			Iterator<?> iter = jsonArray.iterator();
			while (iter.hasNext()) {
				JSONObject jsonObj = (JSONObject)iter.next();
				SparkJobInfo jobInfo = createSparkJobInfo(jsonObj);
				sparkJobInfos.add(jobInfo);
			}
		} else {
			logError(statusCode, resContent, true);
		}
	} catch (Exception e) {
		processException("Error occurs when trying to get information of jobs:", e);
	} finally {
		close(httpClient);
	}
	return sparkJobInfos;
}
 
Example 16
Source File: CloudLogic.java    From FreeServer with Apache License 2.0 5 votes vote down vote up
/**
 * 检查审核状态
 * @param json
 * @param userInfo
 * @param infoMapper
 * @return
 */
public static int checkCheckStatus(JSONObject json, UserInfo userInfo, UserInfoMapper infoMapper, Map<String,String> cookieMap) throws Exception {
    String userKey = getUserKey(userInfo);
    json = JSONObject.fromObject(json.getString("msg"));
    JSONArray array = JSONArray.fromObject(json.getString("content"));
    if(array.size()>0){
        json = JSONObject.fromObject(array.get(0));
        String state = json.getString("State");
        String url = json.getString("url");
        if("待审核".equals(state)){
            log.info(userKey + "审核中,无需审核!!!");
            return 1;
        }else if("审核通过".equals(state)){
            log.info(userKey + "审核通过!!!");
            if(userInfo.getBlogUrl().equals(url)){
                MailUtil.sendMaid(userKey+"审核通过",userKey+"审核通过");
                userInfo.setBlogUrl("success");
                infoMapper.updateByPrimaryKey(userInfo);
                deleteBlogByType(userInfo,url,cookieMap);
                log.info("修改url为success,删除延期博客!!!");
            }
            return 2;
        }else{
            log.info(userKey + "审核失败,审核结果:"+state);
            if(userInfo.getBlogUrl().equals(url)){
                MailUtil.sendMaid(userKey+"审核失败","审核结果:"+state+","+json.toString());
                userInfo.setBlogUrl("error");
                infoMapper.updateByPrimaryKey(userInfo);
                deleteBlogByType(userInfo,url,cookieMap);
                log.info("修改url为error,删除延期博客!!!");
            }
            return 3;
        }
    }else{
        log.info("没有延期记录!!!");
        return 4;
    }
}
 
Example 17
Source File: ExplorableDatasetRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getInstanceDetailsWithOffsetAndLimitTest() {
    //Setup:
    String pathString = "explorable-datasets/" + encode(RECORD_ID_STR) + "/classes/" + encode(CLASS_ID_STR)
            + "/instance-details";

    Response response = target().path(pathString).queryParam("offset", 0).queryParam("limit", 13).request().get();
    assertEquals(response.getStatus(), 200);
    JSONArray responseArray = JSONArray.fromObject(response.readEntity(String.class));
    assertEquals(responseArray.size(), 13);
    assertEquals(response.getHeaders().get("X-Total-Count").get(0), "13");
    assertEquals(response.getLinks().size(), 0);
}
 
Example 18
Source File: MessageServlet.java    From mytwitter with Apache License 2.0 5 votes vote down vote up
private void toAddFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
	HttpSession session = request.getSession();
	Users user = (Users) session.getAttribute("user");
	int fuid = user.getUid();
	List<Usersall> usersalls = messageDao.addFriend(fuid);
	JsonConfig config = new JsonConfig();
	config.setExcludes(new String[] { "upwd" });
	JSONArray array = JSONArray.fromObject(usersalls, config);
	response.getWriter().print(array.toString());
}
 
Example 19
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
public static Object json2Array(String json, Class valueClz) {
	JSONArray jsonArray = JSONArray.fromObject(json);
	return JSONArray.toArray(jsonArray, valueClz);
}
 
Example 20
Source File: JSONHelper.java    From jeecg with Apache License 2.0 2 votes vote down vote up
/***
 * 将对象转换为传入类型的List
 * 
 * @param <T>
 * @param jsonArray
 * @param objectClass
 * @return
 */
public static <T> List<T> toList(Object object, Class<T> objectClass) {
	JSONArray jsonArray = JSONArray.fromObject(object);

	return JSONArray.toList(jsonArray, objectClass);
}