Java Code Examples for com.alibaba.fastjson.JSONArray#isEmpty()

The following examples show how to use com.alibaba.fastjson.JSONArray#isEmpty() . 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: NodeInfo.java    From litchi with Apache License 2.0 6 votes vote down vote up
public static Map<String, List<NodeInfo>> getNodeMaps(JSONObject jsonObject, String nodeId) {
    Map<String, List<NodeInfo>> maps = new HashMap<>();

    for (String nodeType : jsonObject.keySet()) {
        JSONArray itemArrays = jsonObject.getJSONArray(nodeType);
        if (itemArrays.isEmpty()) {
            continue;
        }

        List<NodeInfo> list = itemArrays.toJavaList(NodeInfo.class);
        for (NodeInfo si : list) {
            si.setNodeType(nodeType);
            if (si.getNodeId().equals(nodeId)) {
                si.setPid(RuntimeUtils.pid());
            }
        }

        List<NodeInfo> serverInfoList = maps.getOrDefault(nodeType, new ArrayList<>());
        if (serverInfoList.isEmpty()) {
            maps.put(nodeType, serverInfoList);
        }
        serverInfoList.addAll(list);
    }
    return maps;
}
 
Example 2
Source File: ChartData.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 维度轴
 * 
 * @return
 */
public Dimension[] getDimensions() {
	JSONArray items = config.getJSONObject("axis").getJSONArray("dimension");
	if (items == null || items.isEmpty()) {
		return new Dimension[0];
	}
	
	List<Dimension> list = new ArrayList<>();
	for (Object o : items) {
		JSONObject item = (JSONObject) o;
		Field[] validFields = getValidFields(item);
		Dimension dim = new Dimension(
				validFields[0], getFormatSort(item), getFormatCalc(item),
				item.getString("label"),
				validFields[1]);
		list.add(dim);
	}
	return list.toArray(new Dimension[0]);
}
 
Example 3
Source File: KafkaZabbixSender.java    From kafka-zabbix with Apache License 2.0 6 votes vote down vote up
void checkHostGroup(String hostGroup) {
	if (hostGroupCache.get(hostGroup) == null) {
		JSONObject filter = new JSONObject();
		filter.put("name", new String[] { hostGroup });
		Request getRequest = RequestBuilder.newBuilder()
				.method("hostgroup.get").paramEntry("filter", filter)
				.build();
		JSONObject getResponse = zabbixApi.call(getRequest);
		JSONArray result = getResponse.getJSONArray("result");
		if (!result.isEmpty()) { // host group exists.
			String groupid = result.getJSONObject(0).getString("groupid");
			hostGroupCache.put(hostGroup, groupid);
		} else {// host group not exists, create it.
			Request createRequest = RequestBuilder.newBuilder()
					.method("hostgroup.create")
					.paramEntry("name", hostGroup).build();
			JSONObject createResponse = zabbixApi.call(createRequest);
			String hostGroupId = createResponse.getJSONObject("result")
					.getJSONArray("groupids").getString(0);
			hostGroupCache.put(hostGroup, hostGroupId);
		}
	}
}
 
Example 4
Source File: PlainPermissionManager.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public AclConfig getAllAclConfig() {
    AclConfig aclConfig = new AclConfig();
    List<PlainAccessConfig> configs = new ArrayList<>();
    List<String> whiteAddrs = new ArrayList<>();
    JSONObject plainAclConfData = AclUtils.getYamlDataObject(fileHome + File.separator + fileName,
            JSONObject.class);
    if (plainAclConfData == null || plainAclConfData.isEmpty()) {
        throw new AclException(String.format("%s file  is not data", fileHome + File.separator + fileName));
    }
    JSONArray globalWhiteAddrs = plainAclConfData.getJSONArray(AclConstants.CONFIG_GLOBAL_WHITE_ADDRS);
    if (globalWhiteAddrs != null && !globalWhiteAddrs.isEmpty()) {
        whiteAddrs = globalWhiteAddrs.toJavaList(String.class);
    }
    JSONArray accounts = plainAclConfData.getJSONArray(AclConstants.CONFIG_ACCOUNTS);
    if (accounts != null && !accounts.isEmpty()) {
        configs = accounts.toJavaList(PlainAccessConfig.class);
    }
    aclConfig.setGlobalWhiteAddrs(whiteAddrs);
    aclConfig.setPlainAccessConfigs(configs);
    return aclConfig;
}
 
Example 5
Source File: BaseDynamicService.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 处理子级数据
 *
 * @param classFeature 功能
 * @param roleId       角色id
 * @param dataId       数据id
 * @param jsonObject   parent
 * @return 是否包含子级
 */
default boolean doChildren(ClassFeature classFeature, String roleId, String dataId, JSONObject jsonObject) {
    Set<ClassFeature> children = DynamicData.getChildren(classFeature);
    if (children == null) {
        return false;
    }
    JSONArray childrens = new JSONArray();
    children.forEach(classFeature1 -> {
        RoleService bean = SpringUtil.getBean(RoleService.class);
        JSONArray jsonArray1 = bean.listDynamic(roleId, classFeature1, dataId);
        if (jsonArray1 == null || jsonArray1.isEmpty()) {
            return;
        }
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("children", jsonArray1);
        jsonObject1.put("title", classFeature1.getName());
        jsonObject1.put("id", classFeature1.name());
        childrens.add(jsonObject1);
    });
    if (!childrens.isEmpty()) {
        jsonObject.put("children", childrens);
    }
    return true;
}
 
Example 6
Source File: AuthRenrenRequest.java    From JustAuth with MIT License 5 votes vote down vote up
private String getAvatarUrl(JSONObject userObj) {
    JSONArray jsonArray = userObj.getJSONArray("avatar");
    if (Objects.isNull(jsonArray) || jsonArray.isEmpty()) {
        return null;
    }
    return jsonArray.getJSONObject(0).getString("url");
}
 
Example 7
Source File: KafkaZabbixSender.java    From kafka-zabbix with Apache License 2.0 5 votes vote down vote up
void checkItem(String host, String item) {

		if (itemCache.get(itemCacheKey(host, item)) == null) {
			JSONObject search = new JSONObject();
			search.put("key_", item);
			Request getRequest = RequestBuilder.newBuilder().method("item.get")
					.paramEntry("hostids", hostCache.get(host))
					.paramEntry("search", search).build();
			JSONObject getResponse = zabbixApi.call(getRequest);
			JSONArray result = getResponse.getJSONArray("result");
			if (result.isEmpty()) {
				// create item
				int type = 2; // trapper
				int value_type = 0; // float
				int delay = 30;
				Request request = RequestBuilder.newBuilder()
						.method("item.create").paramEntry("name", item)
						.paramEntry("key_", item)
						.paramEntry("hostid", hostCache.get(host))
						.paramEntry("type", type)
						.paramEntry("value_type", value_type)
						.paramEntry("delay", delay).build();

				JSONObject response = zabbixApi.call(request);
				String itemId = response.getJSONObject("result")
						.getJSONArray("itemids").getString(0);
				itemCache.put(itemCacheKey(host, item), itemId);
			} else {
				// put into cache
				itemCache.put(itemCacheKey(host, item), result.getJSONObject(0)
						.getString("itemid"));
			}
		}
	}
 
Example 8
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static List<List<Object>> genRspHeaders(String parentKey, JSONArray jsonArray) {

        if (jsonArray == null || jsonArray.isEmpty()) {
            return new ArrayList<>();
        }
        List<List<Object>> result = new ArrayList<>();
        if (parentKey == null) {
            Object[] header = new Object[]{"参数名称", "是否必须", "描述"};
            result.add(Arrays.asList(header));
        }
        if (parentKey != null) {
            parentKey += PLACEHOLDER_CHILDPARAM;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject entry = jsonArray.getJSONObject(i);
            String name = entry.getString("name");
            if (parentKey != null) {
                name = parentKey + name;
            }
            String require = entry.getString("require");
            String description = entry.getString("description");
            Object[] param = new Object[]{name, require, description};
            result.add(Arrays.asList(param));
            JSONArray children = entry.getJSONArray("children");
            if (children != null && !children.isEmpty()) {
                parentKey = parentKey == null ? "" : parentKey;
                result.addAll(genRspHeaders(parentKey, children));
            }
        }

        return result;
    }
 
Example 9
Source File: PdfExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 5 votes vote down vote up
private static List<List<Object>> genReqHeaders(String parentKey, JSONArray jsonArray) {

        if (jsonArray == null || jsonArray.isEmpty()) {
            return new ArrayList<>();
        }
        List<List<Object>> result = new ArrayList<>();
        if (parentKey == null) {
            Object[] header = new Object[]{"参数名称", "是否必须", "默认值", "描述"};
            result.add(Arrays.asList(header));
        }
        if (parentKey != null) {
            parentKey += PLACEHOLDER_CHILDPARAM;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject entry = jsonArray.getJSONObject(i);
            String name = entry.getString("name");
            if (parentKey != null) {
                name = parentKey + name;
            }
            String require = entry.getString("require");
            String defaultValue = entry.getString("defaultValue");
            String description = entry.getString("description");
            Object[] param = new Object[]{name, require, defaultValue, description};
            result.add(Arrays.asList(param));
            JSONArray children = entry.getJSONArray("children");
            if (children != null && !children.isEmpty()) {
                parentKey = parentKey == null ? "" : parentKey;
                result.addAll(genReqHeaders(parentKey, children));
            }
        }

        return result;
    }
 
Example 10
Source File: PlainPermissionManager.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void load() {

        Map<String, PlainAccessResource> plainAccessResourceMap = new HashMap<>();
        List<RemoteAddressStrategy> globalWhiteRemoteAddressStrategy = new ArrayList<>();

        JSONObject plainAclConfData = AclUtils.getYamlDataObject(fileHome + File.separator + fileName,
            JSONObject.class);
        if (plainAclConfData == null || plainAclConfData.isEmpty()) {
            throw new AclException(String.format("%s file  is not data", fileHome + File.separator + fileName));
        }
        log.info("Broker plain acl conf data is : ", plainAclConfData.toString());
        JSONArray globalWhiteRemoteAddressesList = plainAclConfData.getJSONArray("globalWhiteRemoteAddresses");
        if (globalWhiteRemoteAddressesList != null && !globalWhiteRemoteAddressesList.isEmpty()) {
            for (int i = 0; i < globalWhiteRemoteAddressesList.size(); i++) {
                globalWhiteRemoteAddressStrategy.add(remoteAddressStrategyFactory.
                        getRemoteAddressStrategy(globalWhiteRemoteAddressesList.getString(i)));
            }
        }

        JSONArray accounts = plainAclConfData.getJSONArray(AclConstants.CONFIG_ACCOUNTS);
        if (accounts != null && !accounts.isEmpty()) {
            List<PlainAccessConfig> plainAccessConfigList = accounts.toJavaList(PlainAccessConfig.class);
            for (PlainAccessConfig plainAccessConfig : plainAccessConfigList) {
                PlainAccessResource plainAccessResource = buildPlainAccessResource(plainAccessConfig);
                plainAccessResourceMap.put(plainAccessResource.getAccessKey(),plainAccessResource);
            }
        }

        // For loading dataversion part just
        JSONArray tempDataVersion = plainAclConfData.getJSONArray(AclConstants.CONFIG_DATA_VERSION);
        if (tempDataVersion != null && !tempDataVersion.isEmpty()) {
            List<DataVersion> dataVersion = tempDataVersion.toJavaList(DataVersion.class);
            DataVersion firstElement = dataVersion.get(0);
            this.dataVersion.assignNewOne(firstElement);
        }

        this.globalWhiteRemoteAddressStrategy = globalWhiteRemoteAddressStrategy;
        this.plainAccessResourceMap = plainAccessResourceMap;
    }
 
Example 11
Source File: StormToplogyOpHelper.java    From DBus with Apache License 2.0 5 votes vote down vote up
public String getTopoRunningInfoById(String topologyId) {
        String topoWorkers = getForResult(stormRestApi + "/topology-workers/" + topologyId);
        //目前都是单worker部署,取index 0
        JSONObject topoWorkersObj = JSON.parseObject(topoWorkers);
        JSONArray hostPortInfo = topoWorkersObj.getJSONArray("hostPortList");
        if (!hostPortInfo.isEmpty()) {
            String hostInfo = hostPortInfo.getJSONObject(0).getString("host");
            String port = hostPortInfo.getJSONObject(0).getString("port");
            return String.format("%s:%s", hostInfo, port);
        }
        return "";
//        String url = stormRestApi + "/topology/" + topologyId + "/visualization";
//        logger.info("url:{}", url);
//        String result = getForResult(url);
//        JSONObject topoInfo = JSON.parseObject(result);
//        String host = null;
//        String port = null;
//        for (Map.Entry<String, Object> entry : topoInfo.entrySet()) {
//            JSONObject value = (JSONObject) entry.getValue();
//            if (value.containsKey(":stats")) {
//                JSONObject stats = value.getJSONArray(":stats").getJSONObject(0);
//                host = stats.getString(":host");
//                port = stats.getString(":port");
//                break;
//            }
//        }
//        return String.format("%s:%s", host, port);
    }
 
Example 12
Source File: NavBuilder.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param user
 * @return
 */
public JSONArray getNavPortal(ID user) {
    ConfigEntry config = getLayoutOfNav(user);
    if (config == null) {
        return NAVS_DEFAULT;
    }

    // 过滤
    JSONArray navs = (JSONArray) config.getJSON("config");
    for (Iterator<Object> iter = navs.iterator(); iter.hasNext(); ) {
        JSONObject nav = (JSONObject) iter.next();
        JSONArray subNavs = nav.getJSONArray("sub");

        if (subNavs != null && !subNavs.isEmpty()) {
            for (Iterator<Object> subIter = subNavs.iterator(); subIter.hasNext(); ) {
                JSONObject subNav = (JSONObject) subIter.next();
                if (isFilterNav(subNav, user)) {
                    subIter.remove();
                }
            }

            // 无子级,移除主菜单
            if (subNavs.isEmpty()) {
                iter.remove();
            }
        } else if (isFilterNav(nav, user)) {
            iter.remove();
        }
    }
    return navs;
}
 
Example 13
Source File: RobotApprovalManager.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取用户可用流程
 * 
 * @param record
 * @param user
 * @return
 */
public FlowDefinition[] getFlowDefinitions(ID record, ID user) {
	FlowDefinition[] defs = getFlowDefinitions(MetadataHelper.getEntity(record.getEntityCode()));
	if (defs.length == 0) {
		return new FlowDefinition[0];
	}
	
	ID owning = Application.getRecordOwningCache().getOwningUser(record);
	// 过滤可用的
	List<FlowDefinition> workable = new ArrayList<>();
	for (FlowDefinition def : defs) {
		if (def.isDisabled() || def.getJSON("flowDefinition") == null) {
			continue;
		}
		
		FlowParser flowParser = def.createFlowParser();
		FlowNode root = flowParser.getNode("ROOT");  // 发起人节点
		
		// 发起人匹配
		JSONArray users = root.getDataMap().getJSONArray("users");
		if (users == null || users.isEmpty()) {
			users = JSON.parseArray("['OWNS']");
		}
		if (FlowNode.USER_ALL.equals(users.getString(0))
				|| (FlowNode.USER_OWNS.equals(users.getString(0)) && owning.equals(user))
				|| UserHelper.parseUsers(users, record).contains(user)) {
			workable.add(def);
		}
	}
	return workable.toArray(new FlowDefinition[0]);
}
 
Example 14
Source File: BaseDynamicService.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 查询功能下面的所有动态数据
 *
 * @param classFeature 功能
 * @param roleId       角色id
 * @param dataId       上级数据id
 * @return tree array
 */
default JSONArray listDynamic(ClassFeature classFeature, String roleId, String dataId) {
    JSONArray listToArray;
    try {
        listToArray = listToArray(dataId);
        if (listToArray == null || listToArray.isEmpty()) {
            return null;
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("拉取动态信息错误", e);
        return null;
    }
    JSONArray jsonArray = new JSONArray();
    listToArray.forEach(obj -> {
        JSONObject jsonObject = new JSONObject();
        JSONObject data = (JSONObject) obj;
        String name = data.getString("name");
        String id = data.getString("id");
        jsonObject.put("title", name);
        jsonObject.put("id", StrUtil.emptyToDefault(dataId, "") + StrUtil.COLON + classFeature.name() + StrUtil.COLON + id);
        boolean doChildren = this.doChildren(classFeature, roleId, id, jsonObject);
        if (!doChildren) {
            // 没有子级
            RoleService bean = SpringUtil.getBean(RoleService.class);
            List<String> checkList = bean.listDynamicData(roleId, classFeature, dataId);
            if (checkList != null && checkList.contains(id)) {
                jsonObject.put("checked", true);
            }
        }
        jsonArray.add(jsonObject);
    });
    return jsonArray;
}
 
Example 15
Source File: RDBAnalyzeResultService.java    From RCT with Apache License 2.0 5 votes vote down vote up
public JSONArray getPrefixType(Long id, Long scheduleId) throws Exception {
	if (null == id) {
		throw new Exception("pid should not null!");
	}
	JSONArray count = getJsonArrayFromResult(id, scheduleId, IAnalyzeDataConverse.PREFIX_KEY_BY_COUNT);
	JSONArray memory = getJsonArrayFromResult(id, scheduleId, IAnalyzeDataConverse.PREFIX_KEY_BY_MEMORY);
	if(null == memory || memory.isEmpty()) {
		return count;
	}
	Map<String, JSONObject> memMap = getJsonObject(memory);
	JSONArray result = getPrefixArrayAddMem(count, memMap, "memorySize");
	return result;
}
 
Example 16
Source File: TableImpl.java    From tephra with MIT License 5 votes vote down vote up
@Override
public void parseShape(ReaderContext readerContext, XSLFGraphicFrame xslfGraphicFrame, JSONObject shape) {
    if (!(xslfGraphicFrame instanceof XSLFTable))
        return;

    XSLFTable xslfTable = (XSLFTable) xslfGraphicFrame;
    JSONObject table = new JSONObject();
    XSLFTheme xslfTheme = readerContext.getTheme();
    CTTableStyle ctTableStyle = findTableStyle(readerContext, xslfTable);
    if (xslfTheme != null && ctTableStyle != null)
        parseFill(xslfTheme, ctTableStyle, table);
    JSONArray rows = new JSONArray();
    xslfTable.getRows().forEach(xslfTableRow -> {
        JSONArray cells = new JSONArray();
        xslfTableRow.getCells().forEach(xslfTableCell -> {
            JSONObject cell = new JSONObject();
            parseSpan(xslfTableCell, cell);
            parseBorder(xslfTableCell, cell);
            parser.parseShape(readerContext, xslfTableCell, cell);
            cells.add(cell);
        });
        if (cells.isEmpty())
            return;

        JSONObject row = new JSONObject();
        row.put("cells", cells);
        rows.add(row);
    });
    if (rows.isEmpty())
        return;

    table.put("rows", rows);
    shape.put("table", table);
}
 
Example 17
Source File: NavBuilder.java    From rebuild with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 渲染导航菜單
 *
 * @param item
 * @param activeNav
 * @return
 */
public String renderNavItem(JSONObject item, String activeNav) {
    final boolean isUrlType = "URL".equals(item.getString("type"));
    String navName = item.getString("value");
    String navUrl = item.getString("value");

    boolean isOutUrl = isUrlType && navUrl.startsWith("http");
    if (isUrlType) {
        navName = "nav_url-" + navName.hashCode();
        if (isOutUrl) {
            navUrl = ServerListener.getContextPath() + "/commons/url-safe?url=" + CodecUtils.urlEncode(navUrl);
        } else {
            navUrl = ServerListener.getContextPath() + navUrl;
        }
    } else if (NAV_FEEDS.equals(navName)) {
        navName = "nav_entity-Feeds";
        navUrl = ServerListener.getContextPath() + "/feeds/home";
    } else if (NAV_FILEMRG.equals(navName)) {
        navName = "nav_entity-Attachment";
        navUrl = ServerListener.getContextPath() + "/files/home";
    } else {
        navName = "nav_entity-" + navName;
        navUrl = ServerListener.getContextPath() + "/app/" + navUrl + "/list";
    }

    String navIcon = StringUtils.defaultIfBlank(item.getString("icon"), "texture");
    String navText = item.getString("text");

    JSONArray subNavs = null;
    if (activeNav != null) {
        subNavs = item.getJSONArray("sub");
        if (subNavs == null || subNavs.isEmpty()) {
            subNavs = null;
        }
    }

    StringBuilder navHtml = new StringBuilder()
            .append(String.format("<li class=\"%s\"><a href=\"%s\" target=\"%s\"><i class=\"icon zmdi zmdi-%s\"></i><span>%s</span></a>",
                    navName + (subNavs == null ? StringUtils.EMPTY : " parent"),
                    subNavs == null ? navUrl : "###",
                    isOutUrl ? "_blank" : "_self",
                    navIcon,
                    navText));
    if (subNavs != null) {
        StringBuilder subHtml = new StringBuilder()
                .append("<ul class=\"sub-menu\"><li class=\"title\">")
                .append(navText)
                .append("</li><li class=\"nav-items\"><div class=\"content\"><ul class=\"sub-menu-ul\">");

        for (Object o : subNavs) {
            JSONObject subNav = (JSONObject) o;
            subHtml.append(renderNavItem(subNav, null));
        }
        subHtml.append("</ul></div></li></ul>");
        navHtml.append(subHtml);
    }
    navHtml.append("</li>");

    if (activeNav != null) {
        Document navBody = Jsoup.parseBodyFragment(navHtml.toString());
        for (Element nav : navBody.select("." + activeNav)) {
            nav.addClass("active");
            if (activeNav.startsWith("nav_entity-")) {
                Element navParent = nav.parent();
                if (navParent != null && navParent.hasClass("sub-menu-ul")) {
                    navParent.parent().parent().parent().parent().addClass("open active");
                }
            }
        }
        return navBody.selectFirst("li").outerHtml();
    }
    return navHtml.toString();
}
 
Example 18
Source File: KafkaZabbixSender.java    From kafka-zabbix with Apache License 2.0 4 votes vote down vote up
void checkHost(String host, String ip) {
	if (hostCache.get(host) == null) {
		JSONObject filter = new JSONObject();
		filter.put("host", new String[] { host });
		Request getRequest = RequestBuilder.newBuilder().method("host.get")
				.paramEntry("filter", filter).build();
		JSONObject getResponse = zabbixApi.call(getRequest);
		JSONArray result = getResponse.getJSONArray("result");
		if (!result.isEmpty()) { // host exists.
			String hostid = result.getJSONObject(0).getString("hostid");
			hostCache.put(host, hostid);
		} else {// host not exists, create it.
			JSONArray groups = new JSONArray();
			JSONObject group = new JSONObject();
			group.put("groupid", hostGroupCache.get(hostGroup));
			groups.add(group);

			// "interfaces": [
			// {
			// "type": 1,
			// "main": 1,
			// "useip": 1,
			// "ip": "192.168.3.1",
			// "dns": "",
			// "port": "10050"
			// }
			// ],

			JSONObject interface1 = new JSONObject();
			interface1.put("type", 1);
			interface1.put("main", 1);
			interface1.put("useip", 1);
			interface1.put("ip", ip);
			interface1.put("dns", "");
			interface1.put("port", "10051");

			Request request = RequestBuilder.newBuilder()
					.method("host.create").paramEntry("host", host)
					.paramEntry("groups", groups)
					.paramEntry("interfaces", new Object[] { interface1 })
					.build();
			JSONObject response = zabbixApi.call(request);
			String hostId = response.getJSONObject("result")
					.getJSONArray("hostids").getString(0);
			hostCache.put(host, hostId);
		}
	}
}
 
Example 19
Source File: Menu.java    From weixin4j with Apache License 2.0 4 votes vote down vote up
private void recursion(JSONObject jsonButton, SingleButton menuButton) {
    String type = null;
    if (jsonButton.containsKey("type")) {
        type = jsonButton.getString("type");
    }
    SingleButton singleButton = null;
    //判断对象type
    if (type == null) {
        //有子的自定义菜单
        singleButton = new SingleButton(jsonButton.getString("name"));
    } else if (type.equals(ButtonType.Click.toString())) {
        //转成点击按钮
        singleButton = new ClickButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.View.toString())) {
        //转成view按钮
        singleButton = new ViewButton(jsonButton.getString("name"), jsonButton.getString("url"));
    } else if (type.equals(ButtonType.Scancode_Push.toString())) {
        //扫码推事件
        singleButton = new ScancodePushButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Scancode_Waitmsg.toString())) {
        //扫码推事件且弹出“消息接收中”提示框
        singleButton = new ScancodeWaitMsgButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Pic_SysPhoto.toString())) {
        //弹出系统拍照发图
        singleButton = new PicSysPhotoButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Pic_Photo_OR_Album.toString())) {
        //弹出拍照或者相册发图
        singleButton = new PicPhotoOrAlbumButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Pic_Weixin.toString())) {
        //弹出微信相册发图器
        singleButton = new PicWeixinButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Location_Select.toString())) {
        //弹出地理位置选择器
        singleButton = new LocationSelectButton(jsonButton.getString("name"), jsonButton.getString("key"));
    } else if (type.equals(ButtonType.Media_Id.toString())) {
        //永久素材(图片、音频、视频、图文消息)
        singleButton = new MediaIdButton(jsonButton.getString("name"), jsonButton.getString("media_id"));
    } else if (type.equals(ButtonType.View_Limited.toString())) {
        //永久素材(图文消息)
        singleButton = new ViewLimitedButton(jsonButton.getString("name"), jsonButton.getString("media_id"));
    } else if (type.equals(ButtonType.Miniprogram.toString())) {
        //小程序菜单
        singleButton = new MiniprogramButton(jsonButton.getString("name"), jsonButton.getString("appid"),
                jsonButton.getString("pagepath"), jsonButton.getString("url"));
    }
    if (jsonButton.containsKey("sub_button")) {
        JSONArray sub_button = jsonButton.getJSONArray("sub_button");
        //判断是否存在子菜单
        if (!sub_button.isEmpty()) {
            //如果不为空,则添加到singleButton中
            for (int i = 0; i < sub_button.size(); i++) {
                JSONObject jsonSubButton = sub_button.getJSONObject(i);
                recursion(jsonSubButton, singleButton);
            }
        }
    }
    //判断是否存在子菜单
    if (menuButton == null) {
        //只添加一级菜单到集合中
        button.add(singleButton);
    } else {
        //添加到二级自定义菜单中
        menuButton.getSubButton().add(singleButton);
    }
}
 
Example 20
Source File: HbaseImpl.java    From tephra with MIT License 4 votes vote down vote up
@Override
public JSONObject findOneAsJson(HbaseQuery query) {
    JSONArray array = queryAsJson(query.size(1));

    return array.isEmpty() ? null : array.getJSONObject(0);
}