Java Code Examples for com.alibaba.fastjson.JSONObject#get()

The following examples show how to use com.alibaba.fastjson.JSONObject#get() . These examples are extracted from open source projects. 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: uReplicator   File: TestAdminHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetControllerAutobalancing() throws Exception {
    ControllerHelixManager mockHelixManager = EasyMock.createMock(ControllerHelixManager.class);
    AdminHelper helper = new AdminHelper(mockHelixManager);
    Map<String, PriorityQueue<InstanceTopicPartitionHolder>> instanceMap = new HashMap<>();
    PriorityQueue<InstanceTopicPartitionHolder> sjc1aTosjc1Agg1 = new PriorityQueue<>();
    String pipeline = ControllerUtils.getPipelineName("sjc1a", "sjc1-agg1");
    InstanceTopicPartitionHolder ith = new InstanceTopicPartitionHolder("compute9527-sjc1",
        new TopicPartition(pipeline, 0));
    sjc1aTosjc1Agg1.add(ith);
    instanceMap.put(pipeline, sjc1aTosjc1Agg1);
    EasyMock.expect(mockHelixManager.getPipelineToInstanceMap()).andReturn(instanceMap).atLeastOnce();
    EasyMock.expect(mockHelixManager.getControllerAutobalancingStatus("compute9527-sjc1"))
        .andReturn(false);
    EasyMock.replay(mockHelixManager);
    JSONObject status = helper.getControllerAutobalancingStatus();
    Assert.assertEquals(status.size(), 1);
    JSONObject detail = (JSONObject) status.get("compute9527-sjc1");
    Assert.assertEquals(detail.get("autoBalance"), false);
    EasyMock.verify(mockHelixManager);
}
 
Example 2
/**
 * @param content
 * @return
 */
public String parseRef(String content) {
    String[] fieldAndEntity = content.split("\\.");
    if (fieldAndEntity.length != 2 || !MetadataHelper.checkAndWarnField(fieldAndEntity[1], fieldAndEntity[0])) {
        return null;
    }

    Field field = MetadataHelper.getField(fieldAndEntity[1], fieldAndEntity[0]);
    String referenceDataFilter = EasyMeta.valueOf(field).getExtraAttr("referenceDataFilter");

    if (JSONUtils.wellFormat(referenceDataFilter)) {
        JSONObject advFilter = JSON.parseObject(referenceDataFilter);
        if (advFilter.get("items") != null && !advFilter.getJSONArray("items").isEmpty()) {
            return new AdvFilterParser(advFilter).toSqlWhere();
        }
    }
    return null;
}
 
Example 3
Source Project: yue-library   File: MapUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * 以安全的方式从Map中获取一组数据,组合成一个新的JSONObject
    * @param paramMap 需要从中获取数据的map
    * @param keys 获取的keys
    * @return 结果
    */
public static JSONObject getJSONObject(Map<String, Object> paramMap, String... keys) {
	JSONObject paramJson = new JSONObject(paramMap);
	if (!isContainsOneOfKey(paramJson, keys)) {
		return null;
	}

	JSONObject resultJson = new JSONObject();
	for (String key : keys) {
		Object value = paramJson.get(key);
		if (value != null) {
			resultJson.put(key, value);
		}
	}

	return resultJson;
}
 
Example 4
Source Project: weixin4j   File: TagsComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 删除标签
 *
 * @param id 标签Id
 * @throws org.weixin4j.WeixinException 微信操作异常 删除分组异常
 */
public void delete(int id) throws WeixinException {
    //拼接参数
    JSONObject postParam = new JSONObject();
    JSONObject postId = new JSONObject();
    postId.put("id", id);
    postParam.put("tag", postId);
    //创建请求对象
    HttpsClient http = new HttpsClient();
    //调用获取access_token接口
    Response res = http.post("https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=" + weixin.getToken().getAccess_token(), postParam);
    //根据请求结果判定,是否验证成功
    JSONObject jsonObj = res.asJSONObject();
    if (jsonObj != null) {
        if (Configuration.isDebug()) {
            System.out.println("/tags/delete返回json:" + jsonObj.toString());
        }
        Object errcode = jsonObj.get("errcode");
        if (errcode != null && !errcode.toString().equals("0")) {
            //返回异常信息
            throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
        }
    }
}
 
Example 5
Source Project: NutzSite   File: WeixinToken.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("WeixinToken Job 定时任务启动了");
        //封装请求数据
        String params = "grant_type=client_credential&appid="+ MpConfig.appID +"&secret="+ MpConfig.appSecret;
        //发送GET请求
        String data = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        // 解析相应内容(转换成json对象)
        JSONObject jsonObject = JSON.parseObject(data);
//        拿到accesstoken
        String accesstoken = (String) jsonObject.get("access_token");
//        System.out.println(accesstoken);
        Config config =configService.fetch("token");
        if(config==null){
            config =new Config();
            config.setConfigKey("token");
            config.setConfigValue(accesstoken);
            configService.insert(config);
        }else {
            config.setConfigValue(accesstoken);
            configService.update(config);
        }

    }
 
Example 6
Source Project: wd.java   File: Session.java    License: MIT License 5 votes vote down vote up
public void createSession(JSONObject jsonObj) throws Exception {

        JSONObject desiredCapabilities = jsonObj.getJSONObject("desiredCapabilities");
        if (desiredCapabilities.get("host") != null) {
            String host = (String) desiredCapabilities.get("host");
            this.driver.setRemoteHost(host);
        }

        if (desiredCapabilities.get("port") != null) {
            int port = (int) desiredCapabilities.get("port");
            this.driver.setRemotePort(port);
        }

        if (System.getenv("MACACA_UDID") != null) {
            jsonObj.put("udid", System.getenv("MACACA_UDID"));
        }

        if (System.getenv("MACACA_APP_NAME") != null) {
            jsonObj.put("package", System.getenv("MACACA_APP_NAME"));
        }

        JSONObject response = (JSONObject) utils.request("POST", DriverCommand.CREATE_SESSION, jsonObj);
        String sessionId = (String) response.get("sessionId");
        this.driver.setSessionId(sessionId);

        this.driver.setCapabilities(response);
    }
 
Example 7
Source Project: PeonyFramwork   File: ConfigService.java    License: Apache License 2.0 5 votes vote down vote up
public Object getFieldVerifyDef(String fileName, String fieldName) {
    if(!configVerifyDef.containsKey(fileName)) {
        return null;
    }
    JSONObject fileDef = configVerifyDef.getJSONObject(fileName);
    if(!fileDef.containsKey(fieldName)) {
        return null;
    }
    return fileDef.get(fieldName);
}
 
Example 8
/**
     * 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
     *
     * @param businessOrgCommunity 隶属小区信息
     */
    protected void autoSaveDelBusinessOrgCommunity(Business business, JSONObject businessOrgCommunity) {
//自动插入DEL
        Map info = new HashMap();
        info.put("orgCommunityId", businessOrgCommunity.getString("orgCommunityId"));
        info.put("statusCd", StatusConstant.STATUS_CD_VALID);
        List<Map> currentOrgCommunityInfos = getOrgCommunityServiceDaoImpl().getOrgCommunityInfo(info);
        if (currentOrgCommunityInfos == null || currentOrgCommunityInfos.size() != 1) {
            throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
        }

        Map currentOrgCommunityInfo = currentOrgCommunityInfos.get(0);

        currentOrgCommunityInfo.put("bId", business.getbId());

        currentOrgCommunityInfo.put("orgName", currentOrgCommunityInfo.get("org_name"));
        currentOrgCommunityInfo.put("operate", currentOrgCommunityInfo.get("operate"));
        currentOrgCommunityInfo.put("communityName", currentOrgCommunityInfo.get("community_name"));
        currentOrgCommunityInfo.put("communityId", currentOrgCommunityInfo.get("community_id"));
        currentOrgCommunityInfo.put("storeId", currentOrgCommunityInfo.get("store_id"));
        currentOrgCommunityInfo.put("orgId", currentOrgCommunityInfo.get("org_id"));
        currentOrgCommunityInfo.put("orgCommunityId", currentOrgCommunityInfo.get("org_community_id"));


        currentOrgCommunityInfo.put("operate", StatusConstant.OPERATE_DEL);
        getOrgCommunityServiceDaoImpl().saveBusinessOrgCommunityInfo(currentOrgCommunityInfo);

        for (Object key : currentOrgCommunityInfo.keySet()) {
            if (businessOrgCommunity.get(key) == null) {
                businessOrgCommunity.put(key.toString(), currentOrgCommunityInfo.get(key));
            }
        }
    }
 
Example 9
/**
 * @TODO 提取数据加入集合
 * @param result
 * @param rowJson
 * @param realFields
 */
private static void addRow(List result, JSONObject rowJson, String[] realFields) {
	Object cell;
	List row = new ArrayList();
	for (String str : realFields) {
		cell = rowJson.get(str);
		if (cell instanceof JSONObject) {
			row.add(((JSONObject) cell).get("value"));
		} else {
			row.add(cell);
		}
	}
	result.add(row);
}
 
Example 10
/**
 * 是否需要忽略mapping优化
 * @return
 */
public static boolean isNotOptimze(JSONObject define) {
    if (define.containsKey(TYPE_STR)) {
        String v = define.getString(TYPE_STR);
        if (NESTED_STR.equalsIgnoreCase(v) || OBJECT_STR.equalsIgnoreCase(v)) {
            return true;
        }
    } else if (define.containsKey(FIELDS_STR)) {
        //                    \"artifact\": {\n"
        //                              \"type\": \"string\",\n"
        //                              \"fields\": {\n"
        //                                \"raw\": {\n"
        //                                  \"ignore_above\": 1024,\n"
        //                                  \"index\": \"not_analyzed\",\n"
        //                                   \"type\": \"string\"\n"
        //                                }\n"
        //                              }\n"
        if (define.get(FIELDS_STR) instanceof JSONObject) {
            JSONObject fieldsObj = define.getJSONObject(FIELDS_STR);
            if (fieldsObj.containsKey(RAW_STR)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 11
/**
     * 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
     *
     * @param businessOwnerAppUser 绑定业主信息
     */
    protected void autoSaveDelBusinessOwnerAppUser(Business business, JSONObject businessOwnerAppUser) {
//自动插入DEL
        Map info = new HashMap();
        info.put("appUserId", businessOwnerAppUser.getString("appUserId"));
        info.put("statusCd", StatusConstant.STATUS_CD_VALID);
        List<Map> currentOwnerAppUserInfos = getOwnerAppUserServiceDaoImpl().getOwnerAppUserInfo(info);
        if (currentOwnerAppUserInfos == null || currentOwnerAppUserInfos.size() != 1) {
            throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
        }

        Map currentOwnerAppUserInfo = currentOwnerAppUserInfos.get(0);

        currentOwnerAppUserInfo.put("bId", business.getbId());

        currentOwnerAppUserInfo.put("idCard", currentOwnerAppUserInfo.get("id_card"));
        currentOwnerAppUserInfo.put("openId", currentOwnerAppUserInfo.get("open_id"));
        currentOwnerAppUserInfo.put("link", currentOwnerAppUserInfo.get("link"));
        currentOwnerAppUserInfo.put("remark", currentOwnerAppUserInfo.get("remark"));
        currentOwnerAppUserInfo.put("operate", currentOwnerAppUserInfo.get("operate"));
        currentOwnerAppUserInfo.put("appUserName", currentOwnerAppUserInfo.get("app_user_name"));
        currentOwnerAppUserInfo.put("communityName", currentOwnerAppUserInfo.get("community_name"));
        currentOwnerAppUserInfo.put("state", currentOwnerAppUserInfo.get("state"));
        currentOwnerAppUserInfo.put("appUserId", currentOwnerAppUserInfo.get("app_user_id"));
        currentOwnerAppUserInfo.put("communityId", currentOwnerAppUserInfo.get("community_id"));
        currentOwnerAppUserInfo.put("appTypeCd", currentOwnerAppUserInfo.get("app_type_cd"));
        currentOwnerAppUserInfo.put("memberId", currentOwnerAppUserInfo.get("member_id"));
        currentOwnerAppUserInfo.put("userId", currentOwnerAppUserInfo.get("user_id"));
        currentOwnerAppUserInfo.put("appType", currentOwnerAppUserInfo.get("app_type"));


        currentOwnerAppUserInfo.put("operate", StatusConstant.OPERATE_DEL);
        getOwnerAppUserServiceDaoImpl().saveBusinessOwnerAppUserInfo(currentOwnerAppUserInfo);

        for (Object key : currentOwnerAppUserInfo.keySet()) {
            if (businessOwnerAppUser.get(key) == null) {
                businessOwnerAppUser.put(key.toString(), currentOwnerAppUserInfo.get(key));
            }
        }
    }
 
Example 12
/**
 * 是否需要忽略mapping优化
 * @return
 */
public static boolean isNotOptimze(JSONObject define) {
    if (define.containsKey(TYPE_STR)) {
        String v = define.getString(TYPE_STR);
        if (NESTED_STR.equalsIgnoreCase(v) || OBJECT_STR.equalsIgnoreCase(v)) {
            return true;
        }
    } else if (define.containsKey(FIELDS_STR)) {
        //                    \"artifact\": {\n"
        //                              \"type\": \"string\",\n"
        //                              \"fields\": {\n"
        //                                \"raw\": {\n"
        //                                  \"ignore_above\": 1024,\n"
        //                                  \"index\": \"not_analyzed\",\n"
        //                                   \"type\": \"string\"\n"
        //                                }\n"
        //                              }\n"
        if (define.get(FIELDS_STR) instanceof JSONObject) {
            JSONObject fieldsObj = define.getJSONObject(FIELDS_STR);
            if (fieldsObj.containsKey(RAW_STR)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 13
@Override
public void notifyProcess(KvBean configValue) throws Exception {
    LOGGER.info("notify " + configValue.getKey() + " " + configValue.getValue() + " " + configValue.getChangeType());
    KvBean lock = ClusterHelper.getKV(ClusterPathUtil.getConfChangeLockPath());
    if (ClusterGeneralConfig.getInstance().getValue(ClusterParamCfg.CLUSTER_CFG_MYID).equals(lock.getValue())) {
        return;
    }
    if (configValue.getValue() != null && !"".equals(configValue.getValue())) {
        JSONObject jsonObj = JSONObject.parseObject(configValue.getValue());
        if (jsonObj.get(PROPERTIES_CACHESERVER_NAME) != null) {
            String sequenceConf = jsonObj.getString(PROPERTIES_CACHESERVER_NAME);
            ConfFileRWUtils.writeFile(PROPERTIES_CACHESERVER_NAME + PROPERTIES_SUFFIX, sequenceConf);
        }
    }
}
 
Example 14
Source Project: notes   File: ProfessorControler.java    License: Apache License 2.0 5 votes vote down vote up
public List<Map> per(String url){
        logger.info("[INFO] read message");
        if (url == null){
            url = "https://api.zsxq.com/v1.10/groups/222454121411/topics?scope=by_owner&count=20";
        }
        //问答 https://api.zsxq.com/v1.10/groups/222454121411/topics?scope=by_owner&count=20。
        JSONObject jsonObject = professorService.professorService(url);
        Map resp_date =(Map) jsonObject.get("resp_data");
        Object topics = resp_date.get("topics");

        List<Map> maps = JSON.parseArray(JSON.toJSONString(topics), Map.class);
        if (maps.size()==20){
            String create_time = (String) maps.get(19).get("create_time");
            String substring = StringUtils.substring(create_time, create_time.length() - 8, create_time.length() - 5);
            Integer i = Integer.parseInt(substring) - 1;
            String cont = i.toString();
            if (i<100){
                cont = "0" + cont;
            }
            String join = StringUtils.join(StringUtils.substring(create_time, 0, create_time.length() - 8), cont,"+0800");
            try {
//                String s = URLEncoder.encode(join, "UTF-8").toLowerCase();
//                String replace = StringUtils.replace(s, "t", "T", 1);
                url = "https://api.zsxq.com/v1.10/groups/222454121411/topics?scope=by_owner&count=20" +"&end_time="+join;
                List<Map> start = this.start(url);
                if (start == null){
                    return maps;
                }
                maps.addAll(start);
            } catch (Exception e) {
                logger.error("[ERROR] 转移错误",e);

            }
        }else {
            return maps;
        }

        return maps;
    }
 
Example 15
/**
 * @todo 提取实际json对象
 * @param rowJson
 * @param realFields
 * @return
 */
private static Object getRealJSONObject(JSONObject rowJson, String[] realFields, boolean isSuggest) {
	Object result = rowJson.get("_source");
	if (result != null && result instanceof JSONObject) {
		return result;
	}
	result = rowJson.get("buckets");
	if (result != null) {
		if (result instanceof JSONArray) {
			return result;
		} else if (result instanceof JSONObject) {
			return getRealJSONObject((JSONObject) result, realFields, isSuggest);
		}
	}
	result = rowJson.get("hits");
	if (result != null) {
		if (result instanceof JSONArray) {
			return result;
		} else if (result instanceof JSONObject) {
			return getRealJSONObject((JSONObject) result, realFields, isSuggest);
		}
	}

	// suggest模式
	if (isSuggest) {
		result = rowJson.get("options");
		if (result != null) {
			if (result instanceof JSONArray) {
				return result;
			} else if (result instanceof JSONObject) {
				return getRealJSONObject((JSONObject) result, realFields, isSuggest);
			}
		}
	}
	if (rowJson.containsKey("key") && rowJson.containsKey("doc_count")) {
		if (isRoot(rowJson, realFields)) {
			return rowJson;
		}
		Object[] keys = rowJson.keySet().toArray();
		for (Object key : keys) {
			if (!key.equals("key") && !key.equals("doc_count")) {
				result = rowJson.get(key.toString());
				if (result instanceof JSONObject) {
					return getRealJSONObject((JSONObject) result, realFields, isSuggest);
				}
				return result;
			}
		}
	} else if (rowJson.keySet().size() == 1) {
		// 单一取值
		if (rowJson.keySet().iterator().next().equalsIgnoreCase(realFields[0]) && realFields.length == 1) {
			return rowJson;
		}
		result = rowJson.values().iterator().next();
		if (result instanceof JSONObject) {
			JSONObject tmp = (JSONObject) result;
			// {value:xxx} 模式
			if (tmp.keySet().size() == 1 && tmp.keySet().iterator().next().toLowerCase().equals("value")) {
				return rowJson;
			}
			return getRealJSONObject(tmp, realFields, isSuggest);
		} else if (result instanceof JSONArray) {
			return result;
		}
	}
	return rowJson;
}
 
Example 16
Source Project: RCT   File: AnalyzerStatusThread.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void handleAnalyzerStatusMessage(JSONObject message) {
	String analyzeIP = message.getString("ip");
	if (message.get("scheduleInfo") == null || "".equals(message.getString("scheduleInfo").trim())) {
		return;
	}
	JSONObject scheduleInfo = message.getJSONObject("scheduleInfo");
	Long scheduleID = scheduleInfo.getLong("scheduleID");
	Map<String, Map<String, String>> rdbAnalyzeStatus = (Map<String, Map<String, String>>) message
			.get("rdbAnalyzeStatus");
	List<ScheduleDetail> scheduleDetails = new ArrayList<>();

	Map<String, String> newScheduleDtailsInstance = new HashMap<>();

	for (Entry<String, Map<String, String>> entry : rdbAnalyzeStatus.entrySet()) {
		String port = entry.getKey();
		if (entry.getValue() == null) {
			continue;
		}
		Map<String, String> analyzeInfo = entry.getValue();

		AnalyzeStatus status = AnalyzeStatus.fromString(analyzeInfo.get("status"));
		String count = analyzeInfo.get("count");
		String instance = analyzeIP + ":" + port;
		if (count == null || count.equals("")) {
			count = "0";
		}
		ScheduleDetail s = new ScheduleDetail(scheduleID, instance, Integer.parseInt(count), true, status);
		scheduleDetails.add(s);
		newScheduleDtailsInstance.put(instance, instance);
	}
	// 将新旧信息合并
	List<ScheduleDetail> oldScheduleDetails = AppCache.scheduleDetailMap.get(rdbAnalyze.getId());
	List<ScheduleDetail> oldNeedScheduleDetails = new ArrayList<>();

	if (oldScheduleDetails != null && oldScheduleDetails.size() > 0) {
		for (ScheduleDetail detail : oldScheduleDetails) {
			if (newScheduleDtailsInstance.containsKey(detail.getInstance())) {
				continue;
			}
			oldNeedScheduleDetails.add(detail);
		}
		scheduleDetails.addAll(oldNeedScheduleDetails);
	}

	AppCache.scheduleDetailMap.put(rdbAnalyze.getId(), scheduleDetails);
}
 
Example 17
/**
 * @decription 数据同步(Greenplum-->MongoDB)
 * @author yi.zhang
 * @time 2017年8月4日 下午5:26:59
 * @param source	数据源
 * @param target	目标库
 * @param mapper	表映射
 * @param filter_columns	字段过滤
 */
protected void greenplum2mongodb(Config source,Config target,Map<String,String> mapper,List<String> filter_columns){
	if(source==null||target==null){
		return;
	}
	GreenplumFactory factory = new GreenplumFactory();
	factory.init(source.getServers(), source.getDatabase(), source.getSchema(), source.getUsername(), source.getPassword(), true, 100, 10);
	Map<String,String> mapping = new HashMap<String,String>();
	if(mapper==null||mapper.size()==0){
		List<String> tables = factory.queryTables();
		for (String table : tables) {
			mapping.put(table, table);
		}
	}else{
		mapping = mapper;
	}
	MongoDBFactory tfactory = new MongoDBFactory();
	tfactory.init(target.getServers(), target.getDatabase(), target.getSchema(), target.getUsername(), target.getPassword());
	List<String> stables = factory.queryTables();
	List<String> ttables = tfactory.queryTables();
	for(String stable : mapping.keySet()){
		String ttable = mapping.get(stable);
		if(!(stables.contains(stable)&&ttables.contains(ttable))){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]不存在--");
			continue;
		}
		Map<String,String> reflect = new LinkedHashMap<String,String>();
		Map<String, String> scolumns = factory.queryColumns(stable);
		Map<String, String> tcolumns = tfactory.queryColumns(ttable);
		if(scolumns==null||scolumns.isEmpty()||tcolumns==null||tcolumns.isEmpty()){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无合适字段--");
			continue;
		}
		for(String scolumn:scolumns.keySet()){
			String s_column = scolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
			if(filter_columns!=null&&(filter_columns.contains(scolumn)||filter_columns.contains(s_column))){
				continue;
			}
			for(String tcolumn:tcolumns.keySet()){
				String t_column = tcolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
				if(filter_columns!=null&&(filter_columns.contains(tcolumn)||filter_columns.contains(t_column))){
					continue;
				}
				if(scolumn.equalsIgnoreCase(tcolumn)||scolumn.equalsIgnoreCase(t_column)||s_column.equalsIgnoreCase(tcolumn)||s_column.equalsIgnoreCase(t_column)){
					reflect.put(scolumn, tcolumn);
				}
			}
		}
		if(reflect.isEmpty()){
			System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无对应字段--");
			continue;
		}
		String ssql = "select "+StringUtils.join(reflect.keySet(), ",")+" from "+stable;
		List<?> datas = factory.executeQuery(ssql, null);
		System.out.println("--数据表["+stable+"]数据量:"+datas.size());
		for (Object data : datas) {
			Map<String,Object> tdata = new LinkedHashMap<String,Object>();
			JSONObject json = (JSONObject)data;
			for(String key:json.keySet()){
				Object value = json.get(key);
				if(!key.matches("(\\w+)")){
					continue;
				}
				tdata.replace(reflect.get(key), value);
			}
			tfactory.save(ttable, tdata);
		}
	}
}
 
Example 18
/**
 * 插件监控的服务正常运行时的內建监控报告
 * 若有些特殊的监控值无法用配置文件进行配置监控,可利用此方法进行硬编码形式进行获取
 * 注:此方法只有在监控对象可用时,才会调用,并加入到监控值报告中,一并上传
 *
 * @param metricsValueInfo 当前的JMXMetricsValueInfo信息
 * @return
 */
@Override
public Collection<FalconReportObject> inbuiltReportObjectsForValid(JMXMetricsValueInfo metricsValueInfo) {
    // 指定配置中配置的监控值
    int pid = metricsValueInfo.getJmxConnectionInfo().getPid();
    Set<FalconReportObject> result = new HashSet<>();
    String configPath = pluginDir + File.separator + metricsConfFile;
    try {
        String selfNodeId = ElasticSearchConfig.getNodeId(pid);
        String selfNodeName = ElasticSearchConfig.getNodeName(pid);
        if(StringUtils.isEmpty(selfNodeId) || StringUtils.isEmpty(selfNodeName)){
            log.error("获取es:{} 的服务信息失败",metricsValueInfo.getJmxConnectionInfo().getName());
        }else{
            HashMap<String,Object> confMap = Yaml.loadType(new FileInputStream(configPath),HashMap.class);
            if(confMap != null){
                for (String key : confMap.keySet()) {
                    String urlSuffix = key.substring(0,key.lastIndexOf('.'));
                    String url = ElasticSearchConfig.getConnectionUrl(pid) + "/" + urlSuffix;
                    Map<String,String> config = (Map<String, String>) confMap.get(key);

                    String method = config.get("method");
                    String metrics = config.get("metrics");
                    String valuePath = config.get("valuePath").replace("{selfNodeId}",selfNodeId).replace("{selfNodeName}",selfNodeName);
                    String counterType = config.get("counterType");
                    String valueExpress = config.get("valueExpress");

                    String tag = config.get("tag");
                    if("get".equalsIgnoreCase(method)){
                        String responseText = HttpUtil.get(url).getResult();
                        JSONObject jsonObject = JSONObject.parseObject(responseText);
                        if(jsonObject != null){
                            String[] paths = valuePath.split("\\.");
                            for(int i=0;i<paths.length;i++){
                                if(i == paths.length -1){
                                    Object value = jsonObject.get(paths[i]);
                                    if(value instanceof JSONObject){
                                        log.error("elasticSearch http获取值异常,检查{}路径(valuePath)是否为叶子节点:{}",key,config.get("valuePath"));
                                    }else{
                                        //服务的标识后缀名
                                        String name = metricsValueInfo.getJmxConnectionInfo().getName();

                                        FalconReportObject falconReportObject = new FalconReportObject();
                                        MetricsCommon.setReportCommonValue(falconReportObject,step);
                                        falconReportObject.setTimestamp(metricsValueInfo.getTimestamp());
                                        falconReportObject.setMetric(MetricsCommon.getMetricsName(metrics));

                                        falconReportObject.setValue(String.valueOf(executeJsExpress(valueExpress,value)));

                                        falconReportObject.setCounterType(CounterType.valueOf(counterType));

                                        falconReportObject.appendTags(MetricsCommon.getTags(name,this,serverName(), MetricsType.HTTP_URL_CONF)).
                                                appendTags(tag);

                                        result.add(falconReportObject);
                                    }
                                }else{
                                    jsonObject = jsonObject.getJSONObject(paths[i]);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        log.error("elasticSearch监控值获取发生异常",e);
    }

    return result;
}
 
Example 19
Source Project: weixin4j   File: MessageComponent.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 发送模板消息(带跳转小程序或链接)
 *
 * <p>
 * 注:url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。</p>
 *
 * @param openid 接收者
 * @param templateId 模板消息ID
 * @param datas 模板数据
 * @param miniprogram 跳小程序所需数据,不需跳小程序可不用传该数据
 * @param url 模板跳转链接
 * @throws org.weixin4j.WeixinException 微信操作异常
 */
public void sendTemplateMessage(String openid, String templateId, List<TemplateData> datas, Miniprogram miniprogram, String url) throws WeixinException {
    //内部业务验证
    if (openid == null || openid.equals("")) {
        throw new IllegalStateException("openid can not be null or empty");
    }
    if (templateId == null || templateId.equals("")) {
        throw new IllegalStateException("templateId can not be null or empty");
    }
    if (datas == null || datas.isEmpty()) {
        throw new IllegalStateException("datas can not be null or empty");
    }
    JSONObject json = new JSONObject();
    json.put("touser", openid);
    json.put("template_id", templateId);
    //添加模板跳转链接
    if (url != null && !url.equals("")) {
        json.put("url", url);
    }
    //添加小程序
    if (miniprogram != null) {
        JSONObject program = new JSONObject();
        program.put("appid", miniprogram.getAppid());
        program.put("pagepath", miniprogram.getPagepath());
        json.put("miniprogram", program);
    }
    //添加模板数据
    JSONObject data = new JSONObject();
    for (TemplateData templateData : datas) {
        JSONObject dataContent = new JSONObject();
        dataContent.put("value", templateData.getValue());
        dataContent.put("color", templateData.getColor());
        data.put(templateData.getKey(), dataContent);
    }
    json.put("data", data);
    //创建请求对象
    HttpsClient http = new HttpsClient();
    Response res = http.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weixin.getToken().getAccess_token(), json);
    //根据请求结果判定,是否验证成功
    JSONObject jsonObj = res.asJSONObject();
    if (jsonObj != null) {
        if (Configuration.isDebug()) {
            System.out.println("sendTemplateMessage返回json:" + jsonObj.toString());
        }
        Object errcode = jsonObj.get("errcode");
        if (errcode != null && !errcode.toString().equals("0")) {
            //返回异常信息
            throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
        }
    }
}
 
Example 20
/**
	 * @decription 数据同步([MySQL|SQL Server|Oracle]-->[Cassandra])
	 * @author yi.zhang
	 * @time 2017年8月4日 下午5:26:59
	 * @param source	数据源
	 * @param target	目标库
	 * @param mapper	表映射
	 * @param filter_columns	字段过滤
	 */
	protected void sql2cassandra(Config source,Config target,Map<String,String> mapper,List<String> filter_columns){
		if(source==null||target==null){
			return;
		}
		JDBCFactory factory = new JDBCFactory();
		String driverName=null,url = null;
		if(source.getType()==3.1){//MySQL
			driverName="com.mysql.jdbc.Driver";
			url = "jdbc:mysql://"+source.getServers()+(source.getPort()>0?":"+source.getPort():"")+"/"+source.getDatabase()+"?useUnicode=true&characterEncoding=UTF8";
		}
		if(source.getType()==3.2){//SQL Server
			driverName="com.microsoft.jdbc.sqlserver.SQLServerDriver";
			url = "jdbc:microsoft://"+source.getServers()+(source.getPort()>0?":"+source.getPort():"")+";database="+source.getDatabase()+";encrypt=true;trustServerCertificate=false;useUnicode=true;characterEncoding=UTF8";
		}
		if(source.getType()==3.3){//Oracle
			driverName="oracle.jdbc.driver.OracleDriver";
			url = "jdbc:oracle:thin:@"+source.getServers()+(source.getPort()>0?":"+source.getPort():"")+":"+source.getDatabase();
		}
		factory.init(driverName, url,source.getUsername(), source.getPassword(), true, 100, 10);
		Map<String,String> mapping = new HashMap<String,String>();
		if(mapper==null||mapper.size()==0){
			List<String> tables = factory.queryTables();
			for (String table : tables) {
				mapping.put(table, table);
			}
		}else{
			mapping = mapper;
		}
		CassandraFactory tfactory = new CassandraFactory();
		tfactory.init(target.getServers(), target.getKeyspace(), target.getUsername(), target.getPassword());
		List<String> stables = factory.queryTables();
//		List<String> ttables = tfactory.queryTables();
		for(String stable : mapping.keySet()){
			String ttable = mapping.get(stable);
			if(!(stables.contains(stable))){
				System.out.println("--数据表["+stable+"]或目标表["+ttable+"]不存在--");
				continue;
			}
			Map<String,String> reflect = new LinkedHashMap<String,String>();
			Map<String, String> scolumns = factory.queryColumns(stable);
			Map<String, String> tcolumns = tfactory.queryColumns(ttable);
			if(scolumns==null||scolumns.isEmpty()||tcolumns==null||tcolumns.isEmpty()){
				System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无合适字段--");
				continue;
			}
			for(String scolumn:scolumns.keySet()){
				String s_column = scolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
				if(filter_columns!=null&&(filter_columns.contains(scolumn)||filter_columns.contains(s_column))){
					continue;
				}
				for(String tcolumn:tcolumns.keySet()){
					String t_column = tcolumn.trim().toLowerCase().replaceAll("(_+?|-+?)", "");
					if(filter_columns!=null&&(filter_columns.contains(tcolumn)||filter_columns.contains(t_column))){
						continue;
					}
					if(scolumn.equalsIgnoreCase(tcolumn)||scolumn.equalsIgnoreCase(t_column)||s_column.equalsIgnoreCase(tcolumn)||s_column.equalsIgnoreCase(t_column)){
						reflect.put(scolumn, tcolumn);
					}
				}
			}
			if(reflect.isEmpty()){
				System.out.println("--数据表["+stable+"]或目标表["+ttable+"]无对应字段--");
				continue;
			}
			String ssql = "select "+StringUtils.join(reflect.keySet(), ",")+" from "+stable;
			List<?> datas = factory.executeQuery(ssql, null);
			System.out.println("--数据表["+stable+"]数据量:"+datas.size());
			for (Object data : datas) {
				Map<String,Object> tdata = new LinkedHashMap<String,Object>();
				JSONObject json = (JSONObject)data;
				for(String key:json.keySet()){
					Object value = json.get(key);
					if(value instanceof Date){
						value = DateUtil.formatDateTimeStr((Date)value);
					}
					if(value instanceof String){
						value = "\""+json.getString(key)+"\"";
					}
					tdata.replace(reflect.get(key), value);
				}
				String sql = "insert into "+ttable+"("+StringUtils.join(tdata.keySet(), ",")+")values("+StringUtils.join(tdata.values(), ",")+")";
				tfactory.executeUpdate(sql);
			}
		}
	}