com.alibaba.fastjson.TypeReference Java Examples

The following examples show how to use com.alibaba.fastjson.TypeReference. 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: ReplicateConsumePosRequestDecoder.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Object decode(final JoyQueueHeader header, final ByteBuf buffer) throws Exception {
    String consumePositions;
    if (header.getVersion() == JoyQueueHeader.VERSION_V1) {
        consumePositions = Serializer.readString(buffer, Serializer.SHORT_SIZE);
    } else {
        consumePositions = Serializer.readString(buffer, Serializer.INT_SIZE);
    }

    if (consumePositions != null) {
        Map<ConsumePartition, Position> connections = JSON.parseObject(consumePositions, new TypeReference<Map<ConsumePartition, Position>>() {
        });
        return new ReplicateConsumePosRequest(connections);
    }
    return new ReplicateConsumePosRequest();
}
 
Example #2
Source File: ZookeeperDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void loadRules2() {

        final String remoteAddress = "127.0.0.1:2181";
        // 引入groupId和dataId的概念,是为了方便和Nacos进行切换
        final String groupId = "Sentinel-Demo";
        final String flowDataId = "SYSTEM-CODE-DEMO-FLOW";
        // final String degradeDataId = "SYSTEM-CODE-DEMO-DEGRADE";
        // final String systemDataId = "SYSTEM-CODE-DEMO-SYSTEM";


        // 规则会持久化到zk的/groupId/flowDataId节点
        // groupId和和flowDataId可以用/开头也可以不用
        // 建议不用以/开头,目的是为了如果从Zookeeper切换到Nacos的话,只需要改数据源类名就可以
        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, flowDataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

        // ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, degradeDataId,
        //         source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {}));
        // DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());
        //
        // ReadableDataSource<String, List<SystemRule>> systemRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, systemDataId,
        //         source -> JSON.parseObject(source, new TypeReference<List<SystemRule>>() {}));
        // SystemRuleManager.register2Property(systemRuleDataSource.getProperty());

    }
 
Example #3
Source File: LocalFileStore.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
/**
 * 恢复快照
 *
 * @return
 * @throws IOException
 */
public ConcurrentMap<ConsumePartition, Position> recover() throws IOException {
    ConcurrentMap<ConsumePartition, Position> consumePositionCache = new ConcurrentHashMap<>();

    Map<Joint, List<ConsumeBill>> consumeBills;
    try {
        consumeBills = loadFromFile(indexFile, new TypeReference<Map<Joint, List<ConsumeBill>>>() {
        });
    } catch (Exception e) {
        consumeBills = loadFromFile(indexFileBack, new TypeReference<Map<Joint, List<ConsumeBill>>>() {
        });
    }

    if (consumeBills != null) {
        consumeBills.entrySet().stream().forEach(entry -> {
            Joint key = entry.getKey();
            entry.getValue().stream().forEach(val ->
                    consumePositionCache.putIfAbsent(new ConsumePartition(key.getTopic(), key.getApp(), val.getPartition()),
                            new Position(val.getAckStartIndex(), val.getAckCurIndex(), val.getPullStartIndex(), val.getPullCurIndex()))
            );
        });
    }

    return consumePositionCache;
}
 
Example #4
Source File: ApolloDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void loadRules() {
    // Set up basic information, only for demo purpose. You may adjust them based on your actual environment.
    // For more information, please refer https://github.com/ctripcorp/apollo
    String appId = "sentinel-demo";
    String apolloMetaServerAddress = "http://localhost:8080";
    System.setProperty("app.id", appId);
    System.setProperty("apollo.meta", apolloMetaServerAddress);

    String namespaceName = "application";
    String flowRuleKey = "flowRules";
    // It's better to provide a meaningful default value.
    String defaultFlowRules = "[]";

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
        flowRuleKey, defaultFlowRules, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
    }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #5
Source File: EurekaDataSourceTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEurekaDataSource() throws Exception {
    String url = "http://localhost:" + port + "/eureka";

    EurekaDataSource<List<FlowRule>> eurekaDataSource = new EurekaDataSource(appname, instanceId, Arrays.asList(url)
            , SENTINEL_KEY, new Converter<String, List<FlowRule>>() {
        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    FlowRuleManager.register2Property(eurekaDataSource.getProperty());

    await().timeout(15, TimeUnit.SECONDS)
            .until(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return FlowRuleManager.getRules().size() > 0;
                }
            });
    Assert.assertTrue(FlowRuleManager.getRules().size() > 0);
}
 
Example #6
Source File: ModifyServerNamespaceSetHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
        RecordLog.info("[ModifyServerNamespaceSetHandler] Receiving cluster server namespace set: " + data);
        Set<String> set = JSON.parseObject(data, new TypeReference<Set<String>>() {});
        ClusterServerConfigManager.loadServerNamespaceSet(set);
        return CommandResponse.ofSuccess("success");
    } catch (Exception e) {
        RecordLog.warn("[ModifyServerNamespaceSetHandler] Decode cluster server namespace set error", e);
        return CommandResponse.ofFailure(e, "decode client cluster config error");
    }
}
 
Example #7
Source File: UpdateGatewayRuleCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
    } catch (Exception e) {
        RecordLog.info("Decode gateway rule data error", e);
        return CommandResponse.ofFailure(e, "decode gateway rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));

    String result = SUCCESS_MSG;
 Set<GatewayFlowRule> flowRules = JSON.parseObject(data, new TypeReference<Set<GatewayFlowRule>>() {
 });
    GatewayRuleManager.loadRules(flowRules);
    if (!writeToDataSource(gatewayFlowWds, flowRules)) {
        result = WRITE_DS_FAILURE_MSG;
    }
    return CommandResponse.ofSuccess(result);
}
 
Example #8
Source File: FileDataSourceInit.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws Exception {
    // A fake path.
    String flowRuleDir = System.getProperty("user.home") + "/sentinel/rules";
    String flowRuleFile = "flowRule.json";
    String flowRulePath = flowRuleDir + "/" + flowRuleFile;

    ReadableDataSource<String, List<FlowRule>> ds = new FileRefreshableDataSource<>(
        flowRulePath, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})
    );
    // Register to flow rule manager.
    FlowRuleManager.register2Property(ds.getProperty());

    WritableDataSource<List<FlowRule>> wds = new FileWritableDataSource<>(flowRulePath, this::encodeJson);
    // Register to writable data source registry so that rules can be updated to file
    // when there are rules pushed from the Sentinel Dashboard.
    WritableDataSourceRegistry.registerFlowDataSource(wds);
}
 
Example #9
Source File: UserController.java    From microservice-recruit with Apache License 2.0 5 votes vote down vote up
@GetMapping("/recommend")
public ResponseMessage getRecommendUser(
        @RequestParam String param) {
    List<CompanyAndJob> companyAndJobList = JSONObject.parseObject(param, new TypeReference<List<CompanyAndJob>>() {
    });
    return ResponseMessage.successMessage(userInfoService.getRecommendUser(companyAndJobList));
}
 
Example #10
Source File: FastJsonServiceInstanceSerializer.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<T> deserialize(byte[] bytes) {
    return JSON.parseObject(new String(bytes), new TypeReference<ServiceInstance<T>>() {
        @Override
        public Type getType() {
            return tClass.getComponentType();
        }
    });
}
 
Example #11
Source File: Stat.java    From UserCenter with MIT License 5 votes vote down vote up
public List<Address> getCityList() {
    if (StringUtils.isBlank(this.city)) {
        return new ArrayList<>();
    }
    this.cityList = JSONObject.parseObject(city, new TypeReference<List<Address>>(){});
    return cityList;
}
 
Example #12
Source File: Misc.java    From Almost-Famous with MIT License 5 votes vote down vote up
public static <K, V> Map<K, V> parseToMap(String json,
                                          Class<K> keyType,
                                          Class<V> valueType) {
    return JSON.parseObject(json,
            new TypeReference<Map<K, V>>(keyType, valueType) {
            });
}
 
Example #13
Source File: AbstractRedisUtil.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public <T> Map<String, T> entries(String key, TypeReference<T> type) {
    HashOperations<String, String, String> ops = redisTemplate.opsForHash();
    Map<String, T> rs = new HashMap<>();
    ops.entries(formatKey(key)).forEach((k, v) -> {
        rs.put(k, parseObject(v, type));
    });
    return rs;
}
 
Example #14
Source File: WebSocketServer.java    From smart-admin with MIT License 5 votes vote down vote up
/**
 * 更新用户过期时间
 *
 * @param json
 */
private void heartBeatHandle(String json) {
    Long currentDate = System.currentTimeMillis();
    Long expireTime = currentDate + 5 * 1000;
    WebSocketHeartBeatDTO heartBeatDTO = JSON.parseObject(json, new TypeReference<WebSocketHeartBeatDTO>() {});
    Long employeeId = heartBeatDTO.getEmployeeId();
    onLineUser.put(employeeId, expireTime);
}
 
Example #15
Source File: WebSocketServer.java    From smart-admin with MIT License 5 votes vote down vote up
/**
 * 此方法接收 前台信息
 *
 * @param message
 * @param session
 */
@OnMessage
public void onMessage(String message, Session session) {
    if (StringUtils.isEmpty(message)) {
        return;
    }
    MessageCommonDTO messageCommonDTO = JSON.parseObject(message, new TypeReference<MessageCommonDTO>() {});
    if (MessageTypeEnum.HEART_BEAT.getValue().equals(messageCommonDTO.getMessageType())) {
        this.heartBeatHandle(messageCommonDTO.getJsonStr());
    }
}
 
Example #16
Source File: DemoClusterInitFunc.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void initServerTransportConfigProperty() {
    ReadableDataSource<String, ServerTransportConfig> serverTransportDs = new NacosDataSource<>(remoteAddress, groupId,
        clusterMapDataId, source -> {
        List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {});
        return Optional.ofNullable(groupList)
            .flatMap(this::extractServerTransportConfig)
            .orElse(null);
    });
    ClusterServerConfigManager.registerServerTransportProperty(serverTransportDs.getProperty());
}
 
Example #17
Source File: DemoClusterInitFunc.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void initStateProperty() {
    // Cluster map format:
    // [{"clientSet":["112.12.88.66@8729","112.12.88.67@8727"],"ip":"112.12.88.68","machineId":"112.12.88.68@8728","port":11111}]
    // machineId: <ip@commandPort>, commandPort for port exposed to Sentinel dashboard (transport module)
    ReadableDataSource<String, Integer> clusterModeDs = new NacosDataSource<>(remoteAddress, groupId,
        clusterMapDataId, source -> {
        List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {});
        return Optional.ofNullable(groupList)
            .map(this::extractMode)
            .orElse(ClusterStateManager.CLUSTER_NOT_STARTED);
    });
    ClusterStateManager.registerProperty(clusterModeDs.getProperty());
}
 
Example #18
Source File: NacosDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void loadMyNamespaceRules() {
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
    properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #19
Source File: X8sMainActivity.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public void initCameraParams(JSONObject rt) {
    CameraCurParamsJson curParamsJson = (CameraCurParamsJson) JSON.parseObject(rt.toString(), new TypeReference<CameraCurParamsJson>() {
    }, new Feature[0]);
    if (curParamsJson != null && curParamsJson != null) {
        X8sMainActivity.this.mX8MainBottomParameterController.initCameraParam(curParamsJson);
    }
}
 
Example #20
Source File: ElectionMetadata.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
protected void parse(byte [] data) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(data);

    parseString(byteBuffer); //version
    version = Integer.valueOf(parseString(byteBuffer));

    parseString(byteBuffer); //electType
    electType = ElectType.valueOf(Integer.valueOf(parseString(byteBuffer)));

    String allNodesStr = parseString(byteBuffer);
    allNodes = JSON.parseObject(allNodesStr,
            new TypeReference<Collection<DefaultElectionNode>>() {
            });

    String learnersStr = parseString(byteBuffer);
    learners = JSON.parseObject(learnersStr,
            new TypeReference<Set<Integer>>() {
            });

    parseString(byteBuffer); //localNodeId
    localNodeId = Integer.valueOf(parseString(byteBuffer));

    parseString(byteBuffer); //leaderId
    leaderId = Integer.valueOf(parseString(byteBuffer));

    parseString(byteBuffer); //voteFor
    votedFor = Integer.valueOf(parseString(byteBuffer));

    parseString(byteBuffer); //currentTerm
    currentTerm = Integer.valueOf(parseString(byteBuffer));
}
 
Example #21
Source File: RoleRestControllerImpl.java    From Goku.Framework.CoreUI with MIT License 5 votes vote down vote up
@Override
@RequestMapping("/menuauth")
@RequiresRoles("admin_sys")
@RequiresPermissions(value={"sys:role:auth"})
public String menuauth(@RequestBody Map<String, Object> sys) {
    List<SysMenu> sysMenus = JSON.parseObject(String.valueOf(JSON.toJSON(sys.get("sysMenus"))), new TypeReference<List<SysMenu>>() {});
    String roleId= (String) sys.get("roleId");
    String moduleId= (String) sys.get("moduleId");
    int result=sysRoleService.menuAuth(sysMenus,roleId,moduleId);
    if(result>0) {
        return JSON.toJSONString ("true");
    }else{
        return JSON.toJSONString ("false");
    }
}
 
Example #22
Source File: ZookeeperDataSourceTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testZooKeeperDataSource() throws Exception {
    TestingServer server = new TestingServer(21812);
    server.start();

    final String remoteAddress = server.getConnectString();
    final String path = "/sentinel-zk-ds-demo/flow-HK";

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, path,
            new Converter<String, List<FlowRule>>() {
                @Override
                public List<FlowRule> convert(String source) {
                    return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                    });
                }
            });
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

    CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress,
            new ExponentialBackoffRetry(3, 1000));
    zkClient.start();
    Stat stat = zkClient.checkExists().forPath(path);
    if (stat == null) {
        zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
    }

    final String resourceName = "HK";
    publishThenTestFor(zkClient, path, resourceName, 10);
    publishThenTestFor(zkClient, path, resourceName, 15);

    zkClient.close();
    server.stop();
}
 
Example #23
Source File: DescribeBinlogFilesRequest.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
@Override
protected DescribeBinlogFileResult processResult(HttpResponse response) throws Exception {
    String result = EntityUtils.toString(response.getEntity());
    DescribeBinlogFileResult describeBinlogFileResult = JSONObject.parseObject(result,
        new TypeReference<DescribeBinlogFileResult>() {
        });
    return describeBinlogFileResult;
}
 
Example #24
Source File: BaseService.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
/**
 * 用户登录时,存入jwt信息,更新用户无法,更新jwt
 *
 * @param token
 * @return
 */
public RedisUser jwtUser(String token) {
    String tok = jwtTokenUtil.getUsernameFromToken(token);
    RedisUser redisUser = JSON.parseObject(tok, new TypeReference<RedisUser>() {
    });
    return redisUser;
}
 
Example #25
Source File: NacosDataSourceDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void loadMyNamespaceRules() {
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
    properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #26
Source File: HDFSUtil.java    From DataLink with Apache License 2.0 5 votes vote down vote up
/**
 * 解析json串,返回List<ColumnMeta>
 *
 * @param json
 * @return
 */
private static List<ColumnMeta> parseColumnsJson(String json) {
    LinkedHashMap<String, String> jsonMap = JSON.parseObject(json, new TypeReference<LinkedHashMap<String, String>>() {
    });
    List<ColumnMeta> columns = new ArrayList<>();
    for (Map.Entry<String, String> hdfs_meta : jsonMap.entrySet()) {
        if ("fields".equals(hdfs_meta.getKey())) {
            //如果key是fields,则继续遍历获取所有字段类型
            ArrayList<String> list = JSON.parseObject(hdfs_meta.getValue(), new TypeReference<ArrayList<String>>() {
            });
            for (String types : list) {
                //第三层遍历,获取所有类型
                LinkedHashMap<String, String> types_info = JSON.parseObject(types, new TypeReference<LinkedHashMap<String, String>>() {
                });
                for (Map.Entry<String, String> field_type : types_info.entrySet()) {
                    ColumnMeta cm = new ColumnMeta();
                    cm.setName(field_type.getKey());
                    cm.setType(field_type.getValue());
                    //cm.set
                    columns.add(cm);
                }
            }
        }
    }

    return columns;
}
 
Example #27
Source File: CommonFastJsonUtils.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, TypeReference<T> typeReference) {
    try {
        return JSON.parseObject(json, typeReference);
    } catch (Exception e) {
        LOGGER.error("toObject exception, err:{}", e.getMessage(), e);
    }
    return null;
}
 
Example #28
Source File: TableServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public void addColumn(TableField tableField) {
    //添加字典
    addColumnToDict(tableField);
    addFiledCommentValue(tableField);
    String json = JSONObject.toJSONString(tableField);
    Map<String,Object> map = JSON.parseObject(json,new TypeReference<HashMap<String,Object>>() {});
    tableDao.addColumn(map);
    changeTableComment(tableField.getTableName(),tableField.getTableComment(),tableField.getTableType());
}
 
Example #29
Source File: ClusterServer.java    From sentinel-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化集群限流的Supplier
 * 这样如果后期集群限流的规则发生变更的话,系统可以自动感知到
 */
private void initClusterFlowSupplier() {
    // 为集群流控注册一个Supplier,该Supplier会根据namespace动态创建数据源
    ClusterFlowRuleManager.setPropertySupplier(namespace -> {
        // 使用 Nacos 数据源作为配置中心,需要在 REMOTE_ADDRESS 上启动一个 Nacos 的服务
        ReadableDataSource<String, List<FlowRule>> ds = new NacosDataSource<>(REMOTE_ADDRESS, GROUP_ID,
                namespace + FLOW_POSTFIX,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
        return ds.getProperty();
    });
}
 
Example #30
Source File: ClusterServer.java    From sentinel-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化集群热点参数限流的Supplier
 * 这样如果后期集群热点参数限流的规则发生变更的话,系统可以自动感知到
 */
public void initClusterParamFlowSupplier() {
    // 为集群热点参数流控注册一个Supplier,该Supplier会根据namespace动态创建数据源
    ClusterParamFlowRuleManager.setPropertySupplier(namespace -> {
        // 使用 Nacos 数据源作为配置中心,需要在 REMOTE_ADDRESS 上启动一个 Nacos 的服务
        ReadableDataSource<String, List<ParamFlowRule>> ds = new NacosDataSource<>(REMOTE_ADDRESS, GROUP_ID,
                namespace + PARAM_FLOW_POSTFIX,
                source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {}));
        return ds.getProperty();
    });
}