com.alibaba.druid.support.json.JSONUtils Java Examples

The following examples show how to use com.alibaba.druid.support.json.JSONUtils. 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: DruidStatTest.java    From metrics with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    TabularData sqlList = JdbcStatManager.getInstance().getSqlList();
    if (sqlList.size() > 0) {
        for (Object item : JdbcStatManager.getInstance().getSqlList().values()) {
            String text = JSONUtils.toJSONString(item);
            System.out.println(text);
        }
    }

    Assert.assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());

    dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mock:xx");
    dataSource.setFilters("mergeStat");
    dataSource.setDbType("mysql");
}
 
Example #2
Source File: SwitchCommitListener.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private void forceTableRuleToLocal(String path, TaskNode taskNode) throws Exception {
    Path localPath = Paths.get(this.getClass()
            .getClassLoader()
            .getResource(ZookeeperPath.ZK_LOCAL_WRITE_PATH.getKey()).toURI());
    // 获得公共的xml转换器对象
    XmlProcessBase xmlProcess = new XmlProcessBase();

    try {
        forceTableToLocal(localPath, xmlProcess);
        forceRulesToLocal(localPath, xmlProcess);
        //保证先有table再有rule
        forceRuleDataToLocal(taskNode);
        ReloadConfig.reload();
        LOGGER.error("migrate 中 reload 配置成功");
    } catch (Exception e) {
        taskNode.addException(e.getLocalizedMessage());
        //异常to  Zk
        ZKUtils.getConnection().setData().forPath(path, JSONUtils.toJSONString(taskNode).getBytes());
        LOGGER.error("migrate 中 强制更新本地文件失败");
        LOGGER.error("error:", e);
    }
}
 
Example #3
Source File: MigrateDumpRunner.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private void pushMsgToZK(String rootZkPath, String child, int status, String msg, String binlogFile, String pos) throws Exception {
    LOGGER.error(msg);
    String path = rootZkPath + "/" + child;
    TaskStatus taskStatus = new TaskStatus();
    taskStatus.setMsg(msg);
    taskStatus.setStatus(status);
    task.setStatus(status);
    taskStatus.setBinlogFile(binlogFile);
    taskStatus.setPos(Long.parseLong(pos));

    if (ZKUtils.getConnection().checkExists().forPath(path) == null) {
        ZKUtils.getConnection().create().forPath(path, JSONUtils.toJSONString(taskStatus).getBytes());
    } else {
        ZKUtils.getConnection().setData().forPath(path, JSONUtils.toJSONString(taskStatus).getBytes());
    }
}
 
Example #4
Source File: BubbleSort.java    From notes with Apache License 2.0 5 votes vote down vote up
/**
 * @return void
 * @Author fruiqi
 * @Description 对数组内容进行冒泡排序算法的实现
 * 目标:从大到小排序 相反的顺序也是可以的 判断条件需要进行改变
 * 重点:冒泡排序进行比较相邻两个元素
 * @Date 12:35 2019/4/21
 * @Param [nums]
 **/
public void bubbleSortFirst(Integer[] nums) {
    int size = nums.length;

    // 小于2 的情况不用排序
    if (size < 2) {
        return;
    }

    // 全部循环遍历完毕 时间复杂度是O(n*n)
    for (int i = 0; i < size; i++) {
        // 标志位,当一次循环中,没有数据交换
        boolean isFlag = false;
        for (int j = i; j < size - 1; j++) {
            if (nums[j] < nums[j + 1]) {
                //进行数据的交换
                int value = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = value;
                isFlag = true;
            }
        }

        if (!isFlag) {
            break;
        }
    }
    logger.info("message {}", JSONUtils.toJSONString(nums));
}
 
Example #5
Source File: MigrateHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
    String sql = "migrate    -table=test  -add=dn2,dn3,dn4  " + " \n -additional=\"a=b\"";
    Map map = parse(sql);
    System.out.println();
    for (int i = 0; i < 100; i++) {
        System.out.println(i % 5);
    }

    TaskNode taskNode = new TaskNode();
    taskNode.setSql(sql);


    System.out.println(JSONUtils.toJSONString(taskNode));
}
 
Example #6
Source File: SqlExecuteListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void pushMsgToZK(String rootZkPath, String child, int status, String msg) throws Exception {
    String path = rootZkPath + "/" + child;
    TaskStatus taskStatus = new TaskStatus();
    taskStatus.setMsg(msg);
    taskStatus.setStatus(status);
    task.setStatus(status);

    if (ZKUtils.getConnection().checkExists().forPath(path) == null) {
        ZKUtils.getConnection().create().forPath(path, JSONUtils.toJSONString(taskStatus).getBytes());
    } else {
        ZKUtils.getConnection().setData().forPath(path, JSONUtils.toJSONString(taskStatus).getBytes());
    }
}
 
Example #7
Source File: SwitchCommitListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static CuratorTransactionFinal modifyZkRules(CuratorTransactionFinal transactionFinal, String ruleName, List<String> newDataNodes)
        throws Exception {
    CuratorFramework client = ZKUtils.getConnection();
    String rulePath = ZKUtils.getZKBasePath() + "rules/function";
    TypeToken<List<Function>> typeToken = new TypeToken<List<Function>>() {
    };
    List<Function> jsonArray = new  Gson().fromJson(new String(client.getData().forPath(rulePath), "UTF-8"),typeToken.getType());
    for (Function obj : jsonArray) {
        Function func = (Function) obj;
        if (ruleName.equalsIgnoreCase(func.getName())) {
            List<Property> property = func.getProperty();
            for (Property o : property) {
                Property count = (Property) o;
                if ("count".equals(count.getName())) {
                    Integer xcount = Integer.parseInt(count.getValue());
                    count.setValue( String.valueOf(xcount + newDataNodes.size()));

                    if (transactionFinal == null) {
                        transactionFinal = ZKUtils.getConnection().inTransaction().setData().forPath(rulePath, JSONUtils.toJSONString(jsonArray).getBytes()).and();
                    } else {
                        transactionFinal.setData().forPath(rulePath, JSONUtils.toJSONString(jsonArray).getBytes());
                    }
                }
            }
        }

    }
    return transactionFinal;
}
 
Example #8
Source File: SwitchCommitListener.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static CuratorTransactionFinal modifyTableConfigRules(CuratorTransactionFinal transactionFinal, String schemal, String table, List<String> newDataNodes)
        throws Exception {
    CuratorFramework client = ZKUtils.getConnection();
    String rulePath = ZKUtils.getZKBasePath() + "schema/schema";
    TypeToken<List<Schema>> typeToken = new TypeToken<List<Schema>>() {
    };
    List<Schema> schemas = new Gson().fromJson(new String(client.getData().forPath(rulePath), "UTF-8"),typeToken.getType());
    for (Schema func : schemas) {
        if (schemal.equalsIgnoreCase(func.getName())) {

            List<Table> property = func.getTable();
            for (Table o : property) {
                Table tt = (Table) o;
                String tableName = tt.getName();
                String dataNode = tt.getDataNode();
                if (table.equalsIgnoreCase(tableName)) {
                    List<String> allDataNodes = new ArrayList<>();
                    allDataNodes.add(dataNode);
                    allDataNodes.addAll(newDataNodes);
                    tt.setDataNode( Joiner.on(",").join(allDataNodes));
                    if (transactionFinal == null) {
                        transactionFinal = ZKUtils.getConnection().inTransaction().setData().forPath(rulePath, JSONUtils.toJSONString(schemas).getBytes()).and();
                    } else {
                        transactionFinal.setData().forPath(rulePath, JSONUtils.toJSONString(schemas).getBytes());
                    }
                }

            }
        }
    }
    return transactionFinal;
}
 
Example #9
Source File: GlobalTableUtil.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
/**
	 * 每次处理 一种 check 的结果,不会交叉同时处理 多种不同 check 的结果
	 * @param list
	 * @return
	 */
	public static List<SQLQueryResult<Map<String, String>>>
					finished(List<SQLQueryResult<Map<String, String>>> list){
		lock.lock();
		try{
			//[{"dataNode":"db3","result":{"count(*)":"1"},"success":true,"tableName":"COMPANY"}]
			LOGGER.debug("list:::::::::::" + JSONUtils.toJSONString(list));
			for(SQLQueryResult<Map<String, String>> map : list){
				Map<String, String> row = map.getResult();
				if(row != null){
					if(row.containsKey(GlobalTableUtil.MAX_COLUMN)){
						LOGGER.info(map.getDataNode() + "." + map.getTableName() 
								+ "." + GlobalTableUtil.MAX_COLUMN
								+ ": "+ map.getResult().get(GlobalTableUtil.MAX_COLUMN));
					}
					if(row.containsKey(GlobalTableUtil.COUNT_COLUMN)){
						LOGGER.info(map.getDataNode() + "." + map.getTableName() 
								+ "." + GlobalTableUtil.COUNT_COLUMN
								+ ": "+ map.getResult().get(GlobalTableUtil.COUNT_COLUMN));
					}
					if(row.containsKey(GlobalTableUtil.INNER_COLUMN)){
						String columnsList = null;
						try{
							if(StringUtils.isNotBlank(row.get(GlobalTableUtil.INNER_COLUMN)))
								columnsList = row.get(GlobalTableUtil.INNER_COLUMN); // id,name,_mycat_op_time
							LOGGER.debug("columnsList: " + columnsList);
						}catch(Exception e){
							LOGGER.warn(row.get(GlobalTableUtil.INNER_COLUMN) + ", " + e.getMessage());
						}finally{
							if(columnsList == null 
									|| columnsList.indexOf(GlobalTableUtil.GLOBAL_TABLE_MYCAT_COLUMN) == -1){
								LOGGER.warn(map.getDataNode() + "." + map.getTableName() 
										+ " inner column: " 
										+ GlobalTableUtil.GLOBAL_TABLE_MYCAT_COLUMN
										+ " is not exist.");
								if(StringUtils.isNotBlank(map.getTableName())){
									for(SQLQueryResult<Map<String, String>> sqr : innerColumnNotExist){
										String name = map.getTableName();
										String node = map.getDataNode();
										if(name != null && !name.equalsIgnoreCase(sqr.getTableName())
												|| node != null && !node.equalsIgnoreCase(sqr.getDataNode())){
											innerColumnNotExist.add(map);
										}
									}
								}
							}else{
								LOGGER.debug("columnsList: " + columnsList);
								// COMPANY -> "id,name,_mycat_op_time",获得了全局表的所有列,并且知道了全局表是否有内部列
								// 所有列,在 insert into t values(xx,yy) 语法中需要用到
								tableColumsMap.put(map.getTableName().toUpperCase(), columnsList);
							}
//							isInnerColumnCheckFinished = 1;
						}
					}
				}
			}
		}finally{
			isInnerColumnCheckFinished = 1;
			isColumnCountCheckFinished = 1;
			lock.unlock();
		}
		return list;
	}
 
Example #10
Source File: XmltoZkMain.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws JAXBException, InterruptedException {
    // 加载zk总服务
    ZookeeperProcessListen zkListen = new ZookeeperProcessListen();

    // 得到集群名称
    String custerName = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_CLUSTERID);
    // 得到基本路径
    String basePath = ZookeeperPath.ZK_SEPARATOR.getKey() + ZookeeperPath.FLOW_ZK_PATH_BASE.getKey();
    basePath = basePath + ZookeeperPath.ZK_SEPARATOR.getKey() + custerName;
    zkListen.setBasePath(basePath);

    // 获得zk的连接信息
    CuratorFramework zkConn = buildConnection(ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_URL));

    // 获得公共的xml转换器对象
    XmlProcessBase xmlProcess = new XmlProcessBase();

    // 进行xmltozk的schema文件的操作
    new SchemasxmlTozkLoader(zkListen, zkConn, xmlProcess);

    // 进行xmltozk的server文件的操作
    new ServerxmlTozkLoader(zkListen, zkConn, xmlProcess);

    // 进行rule文件到zk的操作
    new RulesxmlTozkLoader(zkListen, zkConn, xmlProcess);

    // 进行序列信息入zk中
    new SequenceTozkLoader(zkListen, zkConn, xmlProcess);

    // 缓存配制信息
    new EcachesxmlTozkLoader(zkListen, zkConn, xmlProcess);

    // 将其他信息加载的zk中
    new OthermsgTozkLoader(zkListen, zkConn, xmlProcess);

    // 初始化xml转换操作
    xmlProcess.initJaxbClass();


    // 加载通知进程
    zkListen.notifly(ZkNofiflyCfg.ZK_NOTIFLY_LOAD_ALL.getKey());



    String clusterNodes=    ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_CLUSTER_NODES);
    String clusterSize=    ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_CLUSTER_SIZE);
    ClusterInfo info=new ClusterInfo();
    info.setClusterNodes(clusterNodes);
    info.setClusterSize(Integer.parseInt(clusterSize));
    try {
        zkConn.setData().forPath(basePath, JSONUtils.toJSONString(info).getBytes());
    } catch (Exception e) {
        LOGGER.error("error",e);
    }

}
 
Example #11
Source File: PostgreSQLBackendConnectionHandler.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
/***
 * 进行连接处理
 * 
 * @param con
 * @param buf
 * @param start
 * @param readedLength
 */
private void doConnecting(PostgreSQLBackendConnection con, ByteBuffer buf,
		int start, int readedLength) {
	try {
		List<PostgreSQLPacket> packets = PacketUtils.parsePacket(buf, 0,
				readedLength);
		LOGGER.debug(JSONUtils.toJSONString(packets));
		if (!packets.isEmpty()
				&& packets.get(0) instanceof AuthenticationPacket) {
			// pg认证信息
				AuthenticationPacket packet = (AuthenticationPacket) packets
						.get(0);
				AuthType aut = packet.getAuthType();
				if (aut != AuthType.Ok) {
					PasswordMessage pak = new PasswordMessage(
							con.getUser(), con.getPassword(), aut,
							((AuthenticationPacket) packet).getSalt());
					
					ByteBuffer buffer = con.allocate(); //allocate(pak.getLength() + 1);
					pak.write(buffer);
					
					con.write(buffer);
				} else {// 登入成功了....

					for (int i = 1; i < packets.size(); i++) {
						PostgreSQLPacket _p = packets.get(i);
						if (_p instanceof BackendKeyData) {
							con.setServerSecretKey(((BackendKeyData) _p)
									.getSecretKey());
						}
					}
					LOGGER.debug("SUCCESS Connected TO PostgreSQL , con id is {}",con.getId());
					con.setState(BackendConnectionState.connected);
					con.getResponseHandler().connectionAcquired(con);// 连接已经可以用来

				}


		}

	} catch (IOException e) {
		LOGGER.error("error",e);
	}
}
 
Example #12
Source File: ExplainTest.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
@Test
public void testStatsGroupsExplain() throws SqlParseException, SQLFeatureNotSupportedException {
    Map map = (Map) JSONUtils.parse(explain("SELECT /*! STATS(group1, group2) */ * FROM index"));
    assertThat(map.get("stats").toString(), equalTo("[group1, group2]"));
}