repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/BaseApiInfoVO.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/BaseApiInfoVO.java
package cn.crabc.core.app.entity.vo; import cn.crabc.core.app.entity.BaseEntity; import lombok.Getter; import lombok.Setter; import java.util.Date; /** * API基本信息 * * @author yuqf */ @Setter @Getter public class BaseApiInfoVO extends BaseEntity { /** * api业务唯一ID */ private Long apiId; /** * 接口名称 */ private String apiName; /** * 接口路径 */ private String apiPath; /** * 请求方式 get、post、put、delete、aptch */ private String apiMethod; /** * API类型:sql、table */ private String apiType; /** * 授权类型:none、code、secret */ private String authType; /** * 权限级别:public、default、private */ private String apiLevel; /** * 开放启用 1/0 */ private Integer enabled; /** * API描述 */ private String remarks; /** * 版本 */ private String version; /** * sql类型,select、insert、update、delete */ private String sqlType; /** * 分页设置,不分页:0、只分页:page、分页并统计:pageCount */ private Integer pageSetup; private String sqlScript; private String showSqlScript; /** * 发布时间 */ private Date releaseTime; private Integer applyed; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/ColumnParseVo.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/ColumnParseVo.java
package cn.crabc.core.app.entity.vo; import lombok.Getter; import lombok.Setter; @Setter @Getter public class ColumnParseVo { private String colName; private String colType; private Integer itemIndex; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/ApiInfoVO.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/ApiInfoVO.java
package cn.crabc.core.app.entity.vo; import cn.crabc.core.app.entity.BaseApiInfo; import cn.crabc.core.app.entity.BaseApiParam; import cn.crabc.core.app.entity.BaseApiSql; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; /** * API详情 */ @Setter @Getter public class ApiInfoVO { /** * 基本信息 */ private BaseApiInfo baseInfo; /** * sql */ private BaseApiSql sqlInfo; /** * 查询引擎 */ private String queryEngine; /** * 请求参数 */ private List<BaseApiParam> requestParam = new ArrayList<>(); /** * 返回参数 */ private List<BaseApiParam> responseParam = new ArrayList<>(); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/BaseGroupVO.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/BaseGroupVO.java
package cn.crabc.core.app.entity.vo; import cn.crabc.core.app.entity.BaseGroup; import java.util.ArrayList; import java.util.List; /** * 分组对象 * */ public class BaseGroupVO extends BaseGroup { private List<BaseGroupVO> children = new ArrayList<>(); private List<ApiComboBoxVO> apis = new ArrayList<>(); public List<BaseGroupVO> getChildren() { return children; } public void setChildren(List<BaseGroupVO> children) { this.children = children; } public List<ApiComboBoxVO> getApis() { return apis; } public void setApis(List<ApiComboBoxVO> apis) { this.apis = apis; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/GroupApiVO.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/vo/GroupApiVO.java
package cn.crabc.core.app.entity.vo; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * 分组下的API */ @Setter @Getter public class GroupApiVO implements Serializable { private Integer groupId; private String groupName; private Integer apiId; private String apiName; private Integer parentId; private List<GroupApiVO> child = new ArrayList<>(); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/UserParam.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/UserParam.java
package cn.crabc.core.app.entity.param; import lombok.Getter; import lombok.Setter; /** * 用户请求对象 * * @author yuqf */ @Setter @Getter public class UserParam { private Long userId; private String username; /** 用户昵称 */ private String nickname; /** 用户邮箱 */ private String email; /** 手机号码 */ private String phone; /** 用户性别 */ private String sex; /** 用户头像 */ private String picture; /** 密码 */ private String password; private String newPassword; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiTestParam.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiTestParam.java
package cn.crabc.core.app.entity.param; import lombok.Getter; import lombok.Setter; @Setter @Getter public class ApiTestParam { private String sqlScript; private String datasourceId; private String datasourceType; private String schemaName; private String sqlParams; private Integer pageSetup; private String resultType; private Object requestParams; private String bodyData; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiLogParam.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiLogParam.java
package cn.crabc.core.app.entity.param; import lombok.Getter; import lombok.Setter; /** * API日志查询请求参数 * * @author yuqf */ @Setter @Getter public class ApiLogParam { private String result; private String keyword; private String startTime; private String endTime; private Integer pageNum; private Integer pageSize; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiInfoParam.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/entity/param/ApiInfoParam.java
package cn.crabc.core.app.entity.param; import cn.crabc.core.app.entity.BaseApiInfo; import cn.crabc.core.app.entity.BaseApiParam; import cn.crabc.core.app.entity.BaseApiSql; import lombok.Getter; import lombok.Setter; import java.util.List; /** * API请求参数 * * @author yuqf */ @Setter @Getter public class ApiInfoParam { /** * 基本信息 */ private BaseApiInfo baseInfo; /** * sql */ private BaseApiSql sqlInfo; /** * 请求参数 */ private List<BaseApiParam> requestParam; /** * 返回参数 */ private List<BaseApiParam> responseParam; /** * 查询引擎 */ private String queryEngine; }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/InterceptorConfig.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/InterceptorConfig.java
package cn.crabc.core.app.config; import cn.crabc.core.app.filter.ApiFilter; import cn.crabc.core.app.filter.AuthInterceptor; import cn.crabc.core.app.filter.JwtInterceptor; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 注册拦截器 * * @author yuqf */ @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Bean public AuthInterceptor apiInterceptor() { return new AuthInterceptor(); } @Bean public JwtInterceptor jwtInterceptor() { return new JwtInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { // 登录拦截器 registry.addInterceptor(jwtInterceptor()) .addPathPatterns("/api/box/**") // 需要拦截的请求 .excludePathPatterns("/api/box/sys/user/login", "/api/box/sys/user/loginout", "/api/box/sys/user/register"); // 不拦截的请求 // API开放接口拦截器 registry.addInterceptor(apiInterceptor()) .addPathPatterns("/api/web/**"); // 需要拦截的请求 } /** * 日志过滤器 * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Bean public FilterRegistrationBean builderRegistrationBean(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new ApiFilter()); registration.addUrlPatterns("/api/web/*"); registration.setName("apiFilter"); registration.setOrder(-1); return registration; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/CacheConfig.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/CacheConfig.java
package cn.crabc.core.app.config; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.cache.CacheManager; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.TimeUnit; @Configuration public class CacheConfig { /** * 临时缓存对象(5分钟) * @return */ @Bean("dataCache") public Cache<String, Object> dataCache() { return Caffeine.newBuilder() .expireAfterWrite(300, TimeUnit.SECONDS) .build(); } /** * 缓存API对象 10小时 * @return */ @Bean("apiCache") public Cache<String, Object> apiCaffeine() { return Caffeine.newBuilder() .expireAfterAccess(10, TimeUnit.HOURS) .build(); } /** * 元数据配置缓存管理器 * * @return */ @Bean("metaDataManager") public CacheManager metaDataCacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager(); Caffeine<Object, Object> caffeine = Caffeine.newBuilder() // 设置最后一次写入或访问后经过固定时间过期 .expireAfterAccess(1800, TimeUnit.SECONDS); cacheManager.setCaffeine(caffeine); return cacheManager; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/WebConfiguration.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/WebConfiguration.java
package cn.crabc.core.app.config; import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * web配置 * * @author yuqf */ @Configuration public class WebConfiguration implements WebMvcConfigurer { /** * 跳转首页 * * @return */ @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { return factory -> { ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html"); factory.addErrorPages(error404Page); }; } /** * 跨域处理 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowCredentials(false) .allowedMethods("*") .allowedHeaders("*"); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/DataSourceConfig.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/DataSourceConfig.java
package cn.crabc.core.app.config; import cn.crabc.core.datasource.config.JdbcDataSourceRouter; import cn.crabc.core.datasource.driver.DataSourceManager; import cn.crabc.core.datasource.driver.jdbc.JdbcDataSourceDriver; import cn.crabc.core.datasource.mapper.BaseDataHandleMapper; import cn.crabc.core.spi.DataSourceDriver; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import java.util.HashMap; /** * 数据源路由配置 * * @author yuqf */ @EnableCaching @EnableScheduling @Configuration public class DataSourceConfig { @Value("${spring.datasource.url}") private String jdbcUrl; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; /** * 默认系统数据源 * * @return */ @Bean public JdbcDataSourceRouter defaultDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(jdbcUrl); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setInitialSize(1); dataSource.setMinIdle(1); dataSource.setMaxActive(20); // 配置获取连接等待超时的时间 dataSource.setMaxWait(6000); dataSource.setKeepAlive(true); // 配置一个连接在池中最小生存的时间,单位是毫秒 dataSource.setMinEvictableIdleTimeMillis(300000); dataSource.setMaxEvictableIdleTimeMillis(900000); // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 dataSource.setTimeBetweenEvictionRunsMillis(60000); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setTestOnReturn(false); JdbcDataSourceRouter dynamic = new JdbcDataSourceRouter(); dynamic.setTargetDataSources(new HashMap<>()); // 设置默认数据源 dynamic.setDefaultTargetDataSource(dataSource); return dynamic; } /** * JDBC 数据源驱动 * * @param baseDataHandleMapper * @return */ @Bean public DataSourceDriver dataSourceDriver(BaseDataHandleMapper baseDataHandleMapper) { return new JdbcDataSourceDriver(baseDataHandleMapper); } /** * 数据源插件驱动 * * @param jdbcDataSourceDriver * @return */ @Bean public DataSourceManager dataSourceDriverManager(DataSourceDriver jdbcDataSourceDriver) { return new DataSourceManager(jdbcDataSourceDriver); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/LoadingData.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/config/LoadingData.java
package cn.crabc.core.app.config; import cn.crabc.core.app.service.system.IBaseApiInfoService; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * 加载数据 */ @Component public class LoadingData implements InitializingBean { @Autowired private IBaseApiInfoService iBaseApiInfoService; /** * 启动加载 * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { iBaseApiInfoService.initApi(); } /** * 定时加载 */ @Scheduled(cron = "${crabc.corn.api:0 0/5 * * * ?}") // 每5分钟全量加载一次 public void task() { iBaseApiInfoService.initApi(); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseUserMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseUserMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 用户信息 接口 * * @author yuqf */ @Mapper public interface BaseUserMapper { /** * 用户列表 * @return */ List<BaseUser> selectList(String userName); /** * 查询用户信息 * @param userId * @param userName * @return */ BaseUser selectOne(@Param("userId") Long userId, @Param("userName") String userName); /** * 编辑用户 * @param baseUser * @return */ Integer updateUser(BaseUser baseUser); /** * 新增用户 * @param baseUser * @return */ Integer insertUser(BaseUser baseUser); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiInfoMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiInfoMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseApiInfo; import cn.crabc.core.app.entity.dto.ApiInfoDTO; import cn.crabc.core.app.entity.vo.ApiComboBoxVO; import cn.crabc.core.app.entity.vo.BaseApiInfoVO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * API基本信息 Mapper接口 * * @author yuqf */ @Mapper public interface BaseApiInfoMapper { /** * API列表 * * @param apiName * @return */ List<BaseApiInfo> selectList(@Param("apiName") String apiName, @Param("devType") String devType); /** * 分组查询API信息 * * @param groupId * @return */ List<ApiComboBoxVO> selectApiGroup(@Param("groupId") Integer groupId, @Param("userId") String userId); /** * 查询关联应用的API * * @param appId * @return */ List<ApiComboBoxVO> selectApiApp(Long appId); /** * 根据Id查询基本信息 * * @param apiId * @return */ BaseApiInfo selectApiById(Long apiId); /** * 根据Id查询api基本信息 * * @param apiId * @return */ BaseApiInfoVO selectBaseApi(Long apiId); /** * 校验api地址是否已经存在 * * @param apiPath * @param method * @return */ Integer checkApiPath(@Param("apiId") Long apiId, @Param("apiPath") String apiPath, @Param("method") String method); /** * 根据apiId查询信息 * @param apiId * @return */ List<ApiInfoDTO> selectApiDetail(@Param("apiId") Long apiId); /** * 插入API * * @param apiInfo * @return */ Integer insertApiInfo(BaseApiInfo apiInfo); /** * 编辑API信息 * * @param apiInfo * @return */ Integer updateApiInfo(BaseApiInfo apiInfo); /** * 更新API状态 * * @param apiInfo * @return */ Integer updateApiState(BaseApiInfo apiInfo); /** * 删除API * @param apiId * @return */ Integer deleteApiInfo(@Param("apiId") Long apiId,@Param("userId") String userId); /** * API校验统计 * * @param apiId * @return */ Integer countApi(Long apiId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiLogMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiLogMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseApiLog; import cn.crabc.core.app.entity.param.ApiLogParam; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * API访问日志 Mapper接口 * * @author yuqf */ @Mapper public interface BaseApiLogMapper { /** * 添加日志 * * @param log * @return */ Integer insert(BaseApiLog log); /** * 日志列表 * * @param param * @return */ List<BaseApiLog> selectList(ApiLogParam param); /** * 日志详情 * * @param logId * @return */ BaseApiLog selectOne(Long logId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseAppMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseAppMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseApp; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * 应用配置 Mapper接口 * * @author yuqf */ @Mapper public interface BaseAppMapper { /** * 应用列表 * @return */ List<BaseApp> selectList(String appName); /** * 应用和API的关系 * @return */ List<BaseApp> selectApiApp(Long apiId); /** * 应用对象 * @param appId * @return */ BaseApp selectOne(Long appId); /** * 新增应用 * @param app * @return */ Integer insert(BaseApp app); /** * 编辑应用 * @param app * @return */ Integer update(BaseApp app); /** * 删除应用 * @param appId * @return */ Integer delete(Long appId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiParamMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseApiParamMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseApiParam; import cn.crabc.core.app.entity.vo.RequestParamsVO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * API参数 Mapper接口 * * @author yuqf */ @Mapper public interface BaseApiParamMapper { /** * API请求参数 * @param apiId * @return */ List<BaseApiParam> selectReqParams(Long apiId); /** * 查询API参数列表 * @param apiId * @return */ List<BaseApiParam> selectList(Long apiId); /** * 查询api详情参数 * @param apiId * @return */ List<RequestParamsVO> selectApiParams(Long apiId); /** * 新增参数 * @param param * @return */ Long insert(BaseApiParam param); /** * 批量新增 * @param list * @return */ Long insertBatch(@Param("list") List<BaseApiParam> list, @Param("apiId") Long apiId); /** * 删除API参数 * @param apiId * @return */ Integer delete(Long apiId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseAppApiMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseAppApiMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseAppApi; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface BaseAppApiMapper { /** * 新增关系 * * @param list * @return */ Integer insert(List<BaseAppApi> list); /** * 删除关系 * * @param appId * @param userId * @return */ Integer delete(@Param("appId") Long appId, @Param("userId") String userId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseDataSourceMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseDataSourceMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseDatasource; import cn.crabc.core.spi.bean.BaseDataSource; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * 数据源 Mapper接口 * * @author yuqf */ @Mapper public interface BaseDataSourceMapper { List<BaseDataSource> list(); /** * * 数据源列表 * @param dataSourceName * @return */ List<BaseDatasource> selectList(String dataSourceName); /** * 查询数据源详情 * @param datasourceId * @return */ BaseDatasource selectOne(Integer datasourceId); /** * 插入数据源 * @param dataSource * @return */ Integer insertDataSource(BaseDatasource dataSource); /** * 更新数据源 * @param dataSource * @return */ Integer updateDataSource(BaseDatasource dataSource); /** * 删除数据源 * @param datasourceId * @return */ Integer deleteDataSource(Integer datasourceId); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseGroupMapper.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/mapper/BaseGroupMapper.java
package cn.crabc.core.app.mapper; import cn.crabc.core.app.entity.BaseGroup; import cn.crabc.core.app.entity.vo.BaseGroupVO; import cn.crabc.core.app.entity.vo.GroupApiVO; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * api分组 接口 * * @author yuqf */ @Mapper public interface BaseGroupMapper { /** * 新增分组 */ Integer insert(BaseGroup group); /** * 编辑分组 */ Integer update(BaseGroup group); /** * 删除分组 * @param groupId */ Integer delete(Integer groupId); /** * 删除用户分组 * @param userId */ Integer deleteAll(String userId); /** * 查询分组列表 * @param userId */ List<BaseGroupVO> selectList(String userId); /** * 查询详情 * @param groupId */ BaseGroup selectOne(Integer groupId); /** * 获取分组下API * * @return */ List<GroupApiVO> selectGroupApi(); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ApiStateEnum.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ApiStateEnum.java
package cn.crabc.core.app.enums; /** * API生命周期状态枚举 * * @author yuqf */ public enum ApiStateEnum { EDIT("edit", "编辑"), AUDIT("audit", "审批"), RELEASE("release", "发布"), DESTROY("destroy", "销毁"), HISTORY("history", "历史"); private String name; private String value; ApiStateEnum(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ResultTypeEnum.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ResultTypeEnum.java
package cn.crabc.core.app.enums; /** * 返回结果类型 操作枚举 * * @author yuqf */ public enum ResultTypeEnum { ONE("one", "对象"), ARRAY("array", "数组"), EXCEL("excel", "excel文件"); private String name; private String value; ResultTypeEnum(String name, String value) { this.name = name; this.value = value; } /** * 校验是否存在类型 * @param name * @return */ public static boolean checkType(String name){ for (ResultTypeEnum type : values()){ if (type.getName().equals(name.toLowerCase())){ return true; } } return false; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/SqlTypeEnum.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/SqlTypeEnum.java
package cn.crabc.core.app.enums; /** * SQL DML操作枚举 * * @author yuqf */ public enum SqlTypeEnum { SELECT("select", "查询"), INSERT("insert", "插入"), UPDATE("update", "修改"), DELETE("delete", "删除"); private String name; private String value; SqlTypeEnum(String name, String value) { this.name = name; this.value = value; } /** * 校验是否存在类型 * @param name * @return */ public static boolean checkType(String name){ for (SqlTypeEnum type : values()){ if (type.getName().equals(name.toLowerCase())){ return true; } } return false; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ApiAuthEnum.java
crabc-boot/crabc-core/src/main/java/cn/crabc/core/app/enums/ApiAuthEnum.java
package cn.crabc.core.app.enums; /** * API认证方式枚举 * * @author yuqf */ public enum ApiAuthEnum { NONE("none", "无认证"), CODE("app_code", "code认证"), APP_SECRET("app_secret", "密钥认证"); private String name; private String value; ApiAuthEnum(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/util/PageInfo.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/util/PageInfo.java
package cn.crabc.core.datasource.util; import com.github.pagehelper.PageSerializable; import java.util.List; /** * 分页对象 * * @author yuqf * */ public class PageInfo<T> extends PageSerializable<T> { private int pageNum; private int pageSize; public PageInfo() { } public PageInfo(List<? extends T> list, int pageNum, int pageSize) { super(list); this.pageNum = pageNum; this.pageSize = pageSize; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/constant/BaseConstant.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/constant/BaseConstant.java
package cn.crabc.core.datasource.constant; import java.util.Arrays; import java.util.List; /** * 常量类 * * @author yuqf */ public class BaseConstant { /** * SQL脚本 */ public final static String BASE_SQL = "base_sql"; /** * 数据源ID */ public final static String DATA_SOURCE_ID = "data_source_id"; /** * 页码 */ public final static String PAGE_NUM = "pageNum"; /** * 每页大小 */ public final static String PAGE_SIZE = "pageSize"; /** * 分页设置 */ public final static String PAGE_SETUP = "pageSetup"; /** * 数据源类型 */ public final static String DATA_SOURCE_TYPE = "data_source_type"; /** * 分页统计 */ public final static Integer PAGE_COUNT = 2; /** * 只分页 */ public final static Integer PAGE_ONLY = 1; /** * redis */ public final static String REDIS_CACHE = "redis"; /** * API数据缓存 */ public static final String CACHE_API_DETAIL = "api_detail"; public static final String CACHE_METADATA_CATALOG = "metadata_catalog:"; /** * redis缓存schema */ public static final String CACHE_METADATA_SCHEMA = "metadata_schema:"; /** * redis缓存表 */ public static final String CACHE_METADATA_TABLE = "metadata_table:"; /** * redis缓存字段 */ public static final String CACHE_METADATA_COLUMN = "metadata_column:"; /** * SQL执行方式 */ public static final String BASE_API_EXEC_TYPE = "base_api_exec_type:"; /** * 需要指定catalog的数据源 */ public static final List<String> CATALOG_DATA_SOURCE = Arrays.asList("sybase","mysql","mariadb","doris","starrocks","tidb","tdsql"); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/exception/CustomException.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/exception/CustomException.java
package cn.crabc.core.datasource.exception; /** * 自定义异常结构 * * @author yuqf */ public class CustomException extends RuntimeException { private int code; private String msg; public CustomException(int code, String message) { this.code = code; this.msg = message; } public int getCode() { return code; } public String getMsg() { return msg; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/config/JdbcDataSourceRouter.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/config/JdbcDataSourceRouter.java
package cn.crabc.core.datasource.config; import cn.crabc.core.datasource.constant.BaseConstant; import cn.crabc.core.datasource.driver.DataSourceManager; import cn.crabc.core.datasource.enums.ErrorStatusEnum; import cn.crabc.core.datasource.exception.CustomException; import com.alibaba.druid.pool.DruidDataSource; import com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * JDBC数据源 动态路由 * * @author yuqf */ public class JdbcDataSourceRouter extends AbstractRoutingDataSource { private static final Logger log = LoggerFactory.getLogger(JdbcDataSourceRouter.class); /** * 当前线程数据源KEY */ private static final ThreadLocal<String> DATA_SOURCE_KEY = new InheritableThreadLocal<>(); /** * 获取数据源key */ public static String getDataSourceKey() { return DATA_SOURCE_KEY.get(); } /** * 设置数据源key */ public static void setDataSourceKey(String key) { DATA_SOURCE_KEY.set(key); } /** * 移除数据源 */ public static void remove() { DATA_SOURCE_KEY.remove(); } /** * 判断数据源是否存在 */ public static boolean exist(String dataSourceId) { return DataSourceManager.DATA_SOURCE_POOL_JDBC.get(getDataSourceId(dataSourceId)) != null; } /** * 获取数据源ID * @param dataSourceId * @return */ private static String getDataSourceId(String dataSourceId) { return dataSourceId == null ? null : dataSourceId.split(":")[0]; } /** * 销毁数据源 */ public static void destroy(String dataSourceId) { DataSource dataSource = DataSourceManager.DATA_SOURCE_POOL_JDBC.get(getDataSourceId(dataSourceId)); if (dataSource == null) { return; } try { if (dataSource instanceof DruidDataSource druidDataSource) { druidDataSource.close(); } else if (dataSource instanceof HikariDataSource hikariDataSource) { hikariDataSource.close(); } } finally { DataSourceManager.DATA_SOURCE_POOL_JDBC.remove(dataSourceId); } } /** * 获取指定数据源 */ public static DataSource getDataSource(String dataSourceId) { DataSource dataSource = DataSourceManager.DATA_SOURCE_POOL_JDBC.get(getDataSourceId(dataSourceId)); if (dataSource == null) { throw new CustomException(ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getCode(), ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getMassage()); } return dataSource; } /** * 获取当前数据源 */ public static DataSource getDataSource() { String dataSourceKey = getDataSourceKey(); DataSource dataSource = DataSourceManager.DATA_SOURCE_POOL_JDBC.get(getDataSourceId(dataSourceKey)); if (dataSource == null) { throw new CustomException(ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getCode(), ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getMassage()); } return dataSource; } /** * 添加数据源 * * @param dataSourceId **/ public static void setDataSource(String dataSourceId, DataSource dataSource) { DataSourceManager.DATA_SOURCE_POOL_JDBC.put(dataSourceId, dataSource); } /** * 切换数据源 */ @Override protected DataSource determineTargetDataSource() { Object dataSourceKey = determineCurrentLookupKey(); if (dataSourceKey == null) { return super.getResolvedDefaultDataSource(); } String dataSourceId = getDataSourceId(dataSourceKey.toString()); DataSource dataSource = DataSourceManager.DATA_SOURCE_POOL_JDBC.get(dataSourceId); if (dataSource == null) { throw new CustomException(ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getCode(), ErrorStatusEnum.DATASOURCE_NOT_FOUNT.getMassage()); } return dataSource; } /** * 获取连接 * * @return * @throws SQLException */ @Override public Connection getConnection() throws SQLException { Connection connection = null; Object dataSourceKey = null; try { connection = determineTargetDataSource().getConnection(); dataSourceKey = determineCurrentLookupKey(); if (dataSourceKey != null && dataSourceKey.toString().contains(":")) { String[] dataSourceInfo = dataSourceKey.toString().split(":"); if (dataSourceInfo.length == 3) { setConnectionSchema(connection, dataSourceInfo[1], dataSourceInfo[2]); } } return connection; } catch (Exception e) { log.error("数据源连接获取失败, dataSourceKey: {}", dataSourceKey, e); throw e; } } /** * 设置连接的schema */ private void setConnectionSchema(Connection connection, String dataSourceType, String schema) throws SQLException { if (BaseConstant.CATALOG_DATA_SOURCE.contains(dataSourceType)) { connection.setCatalog(schema); } else { connection.setSchema(schema); } } @Override protected Object determineCurrentLookupKey() { return getDataSourceKey(); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/DataSourceManager.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/DataSourceManager.java
package cn.crabc.core.datasource.driver; import cn.crabc.core.datasource.exception.CustomException; import cn.crabc.core.spi.DataSourceDriver; import cn.crabc.core.spi.MetaDataMapper; import cn.crabc.core.spi.StatementMapper; import cn.crabc.core.spi.bean.BaseDataSource; import com.zaxxer.hikari.HikariDataSource; import javax.sql.DataSource; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 数据源驱动管理 * * @author yuqf */ public class DataSourceManager { /** * JDBC数据源连接池 */ public static final Map<String, DataSource> DATA_SOURCE_POOL_JDBC = new ConcurrentHashMap<>(); /** * 默认数据源驱动实现 */ private DataSourceDriver defaultDriver; public DataSourceManager(DataSourceDriver dataSourceDriver) { // 默认JDBC驱动 this.defaultDriver = dataSourceDriver; } /** * 创建数据源 * * @param dataSource */ public void createDataSource(BaseDataSource dataSource) { this.defaultDriver.init(dataSource); } /** * 测试数据源 * * @param dataSource * @return */ public String test(BaseDataSource dataSource) { return defaultDriver.test(dataSource); } /** * 获取数据源驱动 * * @param datasourceId * @return */ public DataSourceDriver getDataSource(String datasourceId) { DataSourceDriver dataSourceDriver = null; DataSource dataSource = DATA_SOURCE_POOL_JDBC.get(datasourceId); if (dataSource != null) { dataSourceDriver = this.defaultDriver; } if (dataSourceDriver == null) { throw new CustomException(51001, "数据源不存在!"); } return dataSourceDriver; } /** * 元数据对象 * @param datasourceId * @return */ public MetaDataMapper getMetaData(String datasourceId){ DataSourceDriver dataSource = this.getDataSource(datasourceId); return dataSource.getMetaData(); } /** * 数据处理对象 * @param datasourceId * @return */ public StatementMapper getStatementMapper(String datasourceId){ DataSourceDriver dataSource = this.getDataSource(datasourceId); return dataSource.getStatement(); } /** * 删除数据源驱动 * * @param datasourceId */ public void remove(String datasourceId) { DataSource dataSource = DATA_SOURCE_POOL_JDBC.get(datasourceId); if (dataSource instanceof HikariDataSource) { HikariDataSource hikariDataSource = (HikariDataSource) dataSource; hikariDataSource.close(); } DATA_SOURCE_POOL_JDBC.remove(datasourceId); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcStatement.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcStatement.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.datasource.driver.jdbc; import cn.crabc.core.datasource.config.JdbcDataSourceRouter; import cn.crabc.core.datasource.constant.BaseConstant; import cn.crabc.core.datasource.enums.ErrorStatusEnum; import cn.crabc.core.datasource.exception.CustomException; import cn.crabc.core.datasource.mapper.BaseDataHandleMapper; import cn.crabc.core.datasource.util.PageInfo; import cn.crabc.core.spi.StatementMapper; import com.github.pagehelper.PageHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.regex.Pattern; public class JdbcStatement implements StatementMapper { private static final Logger log = LoggerFactory.getLogger(JdbcStatement.class); private final BaseDataHandleMapper baseMapper; private static final int PAGE_SIZE = 50; private static final int PAGE_NUM = 1; public JdbcStatement(BaseDataHandleMapper baseMapper) { this.baseMapper = baseMapper; } @Override public Map<String, Object> selectOne(String dataSourceId, String schema, String sql, Object params) { List<Map<String, Object>> maps = selectList(dataSourceId, schema, sql, params); return maps.isEmpty() ? new HashMap<>() : maps.get(0); } @Override public List<Map<String, Object>> selectList(String dataSourceId, String schema, String sql, Object params) { PageInfo page = selectPage(dataSourceId, schema, sql, params, PAGE_NUM, PAGE_SIZE); return page.getList(); } @Override public PageInfo selectPage(String dataSourceId, String schema, String sql, Object params, int pageNum, int pageSize) { String execType = null; List<LinkedHashMap<String, Object>> list = new ArrayList<>(); try { Map<String, Object> paramsMap = setParams(dataSourceId, schema, sql, params); execType = (String)paramsMap.get(BaseConstant.BASE_API_EXEC_TYPE); Object pageSetup = paramsMap.get(BaseConstant.PAGE_SETUP); int pageCount = pageSetup != null ? Integer.parseInt(pageSetup.toString()) : 0; if (pageCount != 0 && !checkPage(sql)) { PageHelper.startPage(pageNum, pageSize); } list = baseMapper.executeQuery(paramsMap); } catch (Exception e) { Throwable cause = e.getCause(); String errorMsg = cause == null ? e.getMessage() : cause.getMessage(); log.error("SQL执行失败,请检查SQL是否正常: {}", errorMsg); if (execType == null) { throw new CustomException(51000, errorMsg); } else { LinkedHashMap<String, Object> errorMap = new LinkedHashMap<>(); errorMap.put("执行异常", "SQL执行失败:" + errorMsg); list.add(errorMap); } } finally { PageHelper.clearPage(); JdbcDataSourceRouter.remove(); } return new PageInfo<>(list, pageNum, pageSize); } @Override public int insert(String dataSourceId, String schema, String sql, Object params) { try { Map<String, Object> paramsMap = setParams(dataSourceId, schema, sql, params); return baseMapper.executeInsert(paramsMap); } catch (Exception e) { log.error("SQL执行失败,请检查SQL是否正常", e); throw new CustomException(ErrorStatusEnum.API_SQL_ERROR.getCode(), ErrorStatusEnum.API_SQL_ERROR.getMassage()); } finally { JdbcDataSourceRouter.remove(); } } @Override public int delete(String dataSourceId, String schema, String sql, Object params) { try { Map<String, Object> paramsMap = setParams(dataSourceId, schema, sql, params); return baseMapper.executeDelete(paramsMap); } catch (Exception e) { log.error("SQL执行失败,请检查SQL是否正常", e); throw new CustomException(ErrorStatusEnum.API_SQL_ERROR.getCode(), ErrorStatusEnum.API_SQL_ERROR.getMassage()); } finally { JdbcDataSourceRouter.remove(); } } @Override public int update(String dataSourceId, String schema, String sql, Object params) { try { Map<String, Object> paramsMap = setParams(dataSourceId, schema, sql, params); return baseMapper.executeUpdate(paramsMap); } catch (Exception e) { log.error("SQL执行失败,请检查SQL是否正常", e); throw new CustomException(ErrorStatusEnum.API_SQL_ERROR.getCode(), ErrorStatusEnum.API_SQL_ERROR.getMassage()); } finally { JdbcDataSourceRouter.remove(); } } private Map<String, Object> setParams(String dataSourceId, String schema, String sql, Object params) { Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put(BaseConstant.BASE_SQL, sql); if (params instanceof Map) { paramsMap.putAll((Map<String, Object>) params); } if (schema != null && !schema.isEmpty()) { String dataSourceType = (String)paramsMap.getOrDefault(BaseConstant.DATA_SOURCE_TYPE, ""); dataSourceId = String.format("%s:%s:%s", dataSourceId, dataSourceType, schema); } JdbcDataSourceRouter.setDataSourceKey(dataSourceId); return paramsMap; } private boolean checkPage(String sql) { String[] patterns = { "(?i)limit.*?\\d", // mysql,tidb "(?i)offset.*?\\d", // postgres, sqlserver2012+ "(?i)ROWNUM.*?\\d" // oracle }; for (String pattern : patterns) { if (Pattern.compile(pattern).matcher(sql).find()) { return true; } } return false; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcDataSourceDriver.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcDataSourceDriver.java
package cn.crabc.core.datasource.driver.jdbc; import cn.crabc.core.datasource.mapper.BaseDataHandleMapper; import cn.crabc.core.spi.MetaDataMapper; import cn.crabc.core.spi.StatementMapper; /** * JDBC通用操作实现类 * * @author yuqf */ public class JdbcDataSourceDriver extends DefaultDataSourceDriver { private BaseDataHandleMapper baseDataHandleMapper; private JdbcStatement jdbcStatement; private JdbcMetaData jdbcMetaData; public JdbcDataSourceDriver(BaseDataHandleMapper baseDataHandleMapper) { this.baseDataHandleMapper = baseDataHandleMapper; jdbcStatement = new JdbcStatement(baseDataHandleMapper); jdbcMetaData = new JdbcMetaData(); } @Override public MetaDataMapper getMetaData() { return jdbcMetaData; } @Override public StatementMapper getStatement() { return jdbcStatement; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcMetaData.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/JdbcMetaData.java
package cn.crabc.core.datasource.driver.jdbc; import cn.crabc.core.datasource.config.JdbcDataSourceRouter; import cn.crabc.core.datasource.exception.CustomException; import cn.crabc.core.spi.MetaDataMapper; import cn.crabc.core.spi.bean.Column; import cn.crabc.core.spi.bean.Schema; import cn.crabc.core.spi.bean.Table; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JdbcMetaData implements MetaDataMapper { @Override public List<Schema> getCatalogs(String dataSourceId) { List<Schema> catalogs = new ArrayList<>(); try (Connection connection = JdbcDataSourceRouter.getDataSource(dataSourceId).getConnection(); ResultSet resultSet = connection.getMetaData().getCatalogs()) { while (resultSet.next()) { String schemaName = resultSet.getString(1); if (isSystemSchema(schemaName)) { continue; } Schema schema = new Schema(); schema.setSchema(schemaName); schema.setCatalog(schemaName); catalogs.add(schema); } return catalogs; } catch (Exception e) { throw new IllegalStateException("查询catalogs失败", e); } } @Override public List<Schema> getSchemas(String dataSourceId, String catalog) { List<Schema> schemas = new ArrayList<>(); try (Connection connection = JdbcDataSourceRouter.getDataSource(dataSourceId).getConnection(); ResultSet resultSet = connection.getMetaData().getSchemas(catalog, null)) { while (resultSet.next()) { String schemaName = resultSet.getString(1); if (isSystemSchema(schemaName)) { continue; } Schema schema = new Schema(); schema.setSchema(schemaName); schema.setCatalog(catalog); schemas.add(schema); } return schemas; } catch (Exception e) { throw new CustomException(51002, "查询schema失败,请检查数据源是否正确"); } } @Override public List<Table> getTables(String dataSourceId, String catalog, String schema) { List<Table> tables = new ArrayList<>(); String[] tableType = {"TABLE", "VIEW"}; try (Connection connection = JdbcDataSourceRouter.getDataSource(dataSourceId).getConnection()) { // 获取表和视图 try (ResultSet resultSet = connection.getMetaData().getTables(catalog, schema, "%", tableType)) { while (resultSet.next()) { tables.add(buildTable(resultSet, schema)); } } // 获取存储过程 try (ResultSet procedures = connection.getMetaData().getProcedures(catalog, schema, null)) { while (procedures.next()) { tables.add(buildProcedure(procedures, schema)); } } catch (Exception ignored) {} return tables; } catch (Exception e) { throw new CustomException(51003, "查询table失败,请检查数据源是否正确"); } } @Override public List<Column> getColumns(String dataSourceId, String catalog, String schema, String table) { List<Column> columns = new ArrayList<>(); try (Connection connection = JdbcDataSourceRouter.getDataSource(dataSourceId).getConnection(); ResultSet resultSet = connection.getMetaData().getColumns(catalog, schema, table, null)) { while (resultSet.next()) { columns.add(buildColumn(resultSet, schema, table)); } return columns; } catch (Exception e) { throw new CustomException(51004, "查询字段失败,请检查数据源是否正确"); } } private boolean isSystemSchema(String schemaName) { return "information_schema".equalsIgnoreCase(schemaName) || "performance_schema".equalsIgnoreCase(schemaName) || "pg_catalog".equals(schemaName); } private Table buildTable(ResultSet rs, String schema) throws SQLException { Table table = new Table(); table.setTableName(rs.getString("TABLE_NAME")); table.setRemarks(rs.getString("REMARKS")); table.setTableType(rs.getString("TABLE_TYPE")); table.setCatalog(rs.getString("TABLE_CAT")); table.setSchema(schema); return table; } private Table buildProcedure(ResultSet rs, String schema) throws SQLException { Table table = new Table(); table.setTableName(rs.getString("PROCEDURE_NAME")); table.setRemarks(rs.getString("REMARKS")); table.setTableType("PROCEDURE"); table.setCatalog(rs.getString("PROCEDURE_CAT")); table.setSchema(schema); return table; } private Column buildColumn(ResultSet rs, String schema, String table) throws SQLException { Column column = new Column(); column.setColumnName(rs.getString("COLUMN_NAME")); column.setRemarks(rs.getString("REMARKS")); column.setColumnType(rs.getString("TYPE_NAME")); column.setColumnSize(rs.getString("COLUMN_SIZE")); column.setColumnDefault(rs.getString("COLUMN_DEF")); column.setDecimalDigits(rs.getString("DECIMAL_DIGITS")); column.setCatalog(rs.getString("TABLE_CAT")); column.setSchema(schema); column.setTableName(table); String columnType = column.getColumnType() == null ? "" : column.getColumnType().toUpperCase(); if (columnType.contains("DATE") || columnType.contains("TIME")) { column.setTypeIcon("date"); } else if (columnType.contains("INT") || columnType.contains("NUMBER") || columnType.contains("FLOAT") || columnType.contains("DECIMAL")) { column.setTypeIcon("int"); } else { column.setTypeIcon("str"); } return column; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/DefaultDataSourceDriver.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/driver/jdbc/DefaultDataSourceDriver.java
package cn.crabc.core.datasource.driver.jdbc; import cn.crabc.core.datasource.config.JdbcDataSourceRouter; import cn.crabc.core.spi.DataSourceDriver; import cn.crabc.core.spi.bean.BaseDataSource; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.util.JdbcConstants; import com.zaxxer.hikari.HikariDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * 默认通用方法实现类 * * @author yuqf */ public abstract class DefaultDataSourceDriver implements DataSourceDriver { private static final Logger log = LoggerFactory.getLogger(DefaultDataSourceDriver.class); @Override public String getName() { return "jdbc"; } @Override public String test(BaseDataSource baseDataSource) { Connection connection = null; HikariDataSource dataSource = null; try { dataSource = createHikariDataSource(baseDataSource, true); connection = dataSource.getConnection(); } catch (Exception e) { Throwable cause = e.getCause(); log.error("数据库测试异常:{}", e.getMessage()); return cause == null ? e.getMessage() : cause.getLocalizedMessage(); }finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (dataSource != null) { dataSource.close(); } } return "1"; } @Override public void init(BaseDataSource ds) { String datasourceId = ds.getDatasourceId(); DataSource oldDataSource = JdbcDataSourceRouter.exist(datasourceId) ? JdbcDataSourceRouter.getDataSource(datasourceId) : null; HikariDataSource dataSource = createHikariDataSource(ds, false); JdbcDataSourceRouter.setDataSource(datasourceId, dataSource); destroyOldDataSource(oldDataSource); } @Override public void destroy(String dataSourceId) { JdbcDataSourceRouter.destroy(dataSourceId); } private HikariDataSource createHikariDataSource(BaseDataSource ds, boolean isTest) { HikariDataSource dataSource = new HikariDataSource(); dataSource.setUsername(ds.getUsername()); dataSource.setPassword(ds.getPassword()); dataSource.setJdbcUrl(ds.getJdbcUrl()); if (isTest) { dataSource.setMinimumIdle(0); dataSource.setInitializationFailTimeout(1); dataSource.setConnectionTimeout(2000); } else { dataSource.setMinimumIdle(2); dataSource.setMaximumPoolSize(10); dataSource.setMaxLifetime(900000); dataSource.setIdleTimeout(300000); dataSource.setConnectionTimeout(10000); dataSource.setKeepaliveTime(300000); } setDriverClass(dataSource, ds.getDatasourceType()); return dataSource; } private void destroyOldDataSource(DataSource oldDataSource) { if (oldDataSource == null) { return; } if (oldDataSource instanceof DruidDataSource) { ((DruidDataSource) oldDataSource).close(); } else if (oldDataSource instanceof HikariDataSource) { ((HikariDataSource) oldDataSource).close(); } } /** * 加载特殊驱动 */ private void setDriverClass(HikariDataSource dataSource, String datasourceType) { if (datasourceType == null) { return; } switch (datasourceType.toLowerCase()) { case "dm": dataSource.setDriverClassName(JdbcConstants.DM_DRIVER); break; case "xugu": dataSource.setDriverClassName(JdbcConstants.XUGU_DRIVER); break; case "oceanbase": dataSource.setDriverClassName(JdbcConstants.OCEANBASE_DRIVER2); break; case "clickhouse": dataSource.setDriverClassName(JdbcConstants.CLICKHOUSE_DRIVER_NEW); } } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/mapper/BaseSelectProvider.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/mapper/BaseSelectProvider.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.datasource.mapper; import cn.crabc.core.datasource.constant.BaseConstant; import org.apache.ibatis.annotations.Mapper; import java.util.Map; /** * mybatis SQL提供器 * * @author yuqf */ @Mapper public class BaseSelectProvider { // 标签 private static final String[] tags = {"</if>","</foreach>","</where>","</set>","</choose>","</when>","</trim>","</otherwise"}; /** * 添加脚本标签前缀 * @param sql * @return */ private String addScript(String sql){ for(String tag : tags) { if (sql.contains(tag)) { sql = "<script> " + sql + " </script>"; break; } } return sql; } /** * 查询类 * @param params * @return */ public String executeQuery(Map<String,Object> params) { String sql = params.get(BaseConstant.BASE_SQL).toString(); params.remove(BaseConstant.BASE_SQL); sql = this.addScript(sql); return sql; } /** * 新增类 * @param params * @return */ public String executeInsert(Map<String,Object> params) { String sql = params.get(BaseConstant.BASE_SQL).toString(); params.remove(BaseConstant.BASE_SQL); sql = this.addScript(sql); return sql; } /** * 修改类 * @param params * @return */ public String executeUpdate(Map<String,Object> params) { String sql = params.get(BaseConstant.BASE_SQL).toString(); params.remove(BaseConstant.BASE_SQL); sql = this.addScript(sql); return sql; } /** * 删除类 * @param params * @return */ public String executeDelete(Map<String,Object> params) { String sql = params.get(BaseConstant.BASE_SQL).toString(); params.remove(BaseConstant.BASE_SQL); sql = this.addScript(sql); return sql; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/mapper/BaseDataHandleMapper.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/mapper/BaseDataHandleMapper.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.datasource.mapper; import org.apache.ibatis.annotations.*; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * 通用数据操作 Mapper * * @author yuqf */ @Mapper public interface BaseDataHandleMapper { /** * 查询类SQL * @param params * @return */ @SelectProvider(type = BaseSelectProvider.class, method = "executeQuery") @ResultType(LinkedHashMap.class) List<LinkedHashMap<String, Object>> executeQuery(Map<String, Object> params); /** * 新增类SQL * @param params * @return */ @InsertProvider(type = BaseSelectProvider.class, method = "executeInsert") Integer executeInsert(Map<String, Object> params); /** * 修改类SQL * @param params * @return */ @UpdateProvider(type = BaseSelectProvider.class, method = "executeUpdate") Integer executeUpdate(Map<String, Object> params); /** * 删除类SQL * @param params * @return */ @UpdateProvider(type = BaseSelectProvider.class, method = "executeDelete") Integer executeDelete(Map<String, Object> params); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/enums/ErrorStatusEnum.java
crabc-boot/crabc-datasource/src/main/java/cn/crabc/core/datasource/enums/ErrorStatusEnum.java
package cn.crabc.core.datasource.enums; /** * 错误状态枚举 * * @author yuqf */ public enum ErrorStatusEnum { SYSTEM_ERROR( 50001, "系统繁忙,请稍后重试"), SYSTEM_UPGRADE( 50002, "系统升级中"), API_INVALID( 40001, "无效的接口"), API_UN_AUTH( 40002, "无访问接口权限"), API_EXPIRE( 40003, "接口授权已过期"), API_LIMIT(40004, "接口已被限流"), API_FUSING(40005, "接口已被熔断"), API_OFFLINE(40006, "接口已下线"), API_COUNT_OUT(40007, "接口调用次数已达上线"), APP_UN_AUTH(40008, "该应用没有访问权限"), IP_INVALID( 40010, "IP地址不在有效范围内"), API_SQL_ERROR( 40011, "SQL执行失败,请检查SQL是否正常"), PARAM_NOT_FOUNT( 41000, "必传参数不能为空"), JWT_UN_AUTH( 402, "用户未登录"), JWT_LOGIN_EXPIRE( 401, "登录失效,请重新登录"), SHA_PARAM_NOT_FOUNT( 41006, "认证参数(appkey/timestamp/sign)不能为空"), SHA_APPKEY_NOT_FOUNT( 41007, "认证参数appKey不能为空"), SHA_TIMESTAMP_EXPIRE( 41008, "认证参数timestamp失效"), FORBID_OPERATE(44000, "无效操作"), API_NOT_FOUNT(44001, "无效的API"), API_NOT_OPERATE(44002, "API已发布上线,请先下线后在进行编辑"), USER_REPEAT(44002, "用户名已存在"), DATASOURCE_NOT_FOUNT(44003, "无效的数据源"), APP_NOT_FOUNT(44004, "无效的应用"); private int code; private String massage; ErrorStatusEnum(Integer code, String massage) { this.code = code; this.massage = massage; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMassage() { return massage; } public void setMassage(String massage) { this.massage = massage; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-admin/src/main/java/cn/crabc/core/admin/AdminApplication.java
crabc-boot/crabc-admin/src/main/java/cn/crabc/core/admin/AdminApplication.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.admin; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.ComponentScan; /** * 基础通用开发平台-启动类 * * @author yuqf */ @MapperScan({"cn.crabc.core.*.mapper"}) @ComponentScan("cn.crabc.core") @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); System.out.println("crabc-admin start success!!!"); } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/MetaDataMapper.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/MetaDataMapper.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.spi; import cn.crabc.core.spi.bean.Column; import cn.crabc.core.spi.bean.Schema; import cn.crabc.core.spi.bean.Table; import java.util.List; /** * 元数据操作 Mapper * * @author yuqf */ public interface MetaDataMapper<T> extends Mapper<T> { /** * 获取数据源的Catalog * * @param dataSourceId * @return */ List<Object> getCatalogs(String dataSourceId); /** * 获取数据源Schema * * @param dataSourceId * @param catalog * @return */ List<Schema> getSchemas(String dataSourceId, String catalog); /** * 获取数据表列表 * * @param dataSourceId * @param catalog * @param schema * @return */ List<Table> getTables(String dataSourceId, String catalog, String schema); /** * 获取数据表字段列表 * * @param dataSourceId * @param catalog * @param schema * @param table * @return */ List<Column> getColumns(String dataSourceId, String catalog, String schema, String table); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/PluginException.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/PluginException.java
package cn.crabc.core.spi; /** * 插件异常结构 * * @author yuqf */ public class PluginException extends RuntimeException { private int code; private String msg; public PluginException(int code, String message) { this.code = code; this.msg = message; } public PluginException(String message) { this.code = 55000; this.msg = message; } public int getCode() { return code; } public String getMsg() { return msg; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/Mapper.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/Mapper.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.spi; /** * Mapper * * @author yuqf */ public interface Mapper<T> { }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/StatementMapper.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/StatementMapper.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.spi; import java.util.List; /** * 基础操作 Mapper * * @author yuqf */ public interface StatementMapper<T> extends Mapper<T> { /** * 查询单个对象 * * @param dataSourceId * @param schema * @param sql * @param params * @return */ T selectOne(String dataSourceId, String schema, String sql, Object params); /** * 查询对象列表 * * @param dataSourceId * @param schema * @param sql * @param params * @return */ List<T> selectList(String dataSourceId, String schema, String sql, Object params); /** * 查询分页对象 * * @param dataSourceId * @param schema * @param sql * @param params * @param pageNum * @param pageSize * @return */ Object selectPage(String dataSourceId, String schema, String sql, Object params, int pageNum, int pageSize); /** * 新增 * * @param dataSourceId * @param schema * @param sql * @param params * @return */ int insert(String dataSourceId, String schema, String sql, Object params); /** * 删除 * * @param dataSourceId * @param schema * @param sql * @param params * @return */ int delete(String dataSourceId, String schema, String sql, Object params); /** * 修改 * * @param dataSourceId * @param schema * @param sql * @param params * @return */ int update(String dataSourceId, String schema, String sql, Object params); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/DataSourceDriver.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/DataSourceDriver.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.spi; import cn.crabc.core.spi.bean.BaseDataSource; /** * 数据源驱动 * * @author yuqf */ public interface DataSourceDriver<T> { /** * 数据源名称 * * @return */ String getName(); /** * 测试连接 * * @param dataSource * @return */ String test(BaseDataSource dataSource); /** * 初始化 * * @param dataSource */ void init(BaseDataSource dataSource); /** * 销毁 * * @param dataSourceId */ void destroy(String dataSourceId); /** * 元数据对象 * * @return */ MetaDataMapper getMetaData(); /** * 处理对象 * * @return */ StatementMapper getStatement(); }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Table.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Table.java
package cn.crabc.core.spi.bean; import java.io.Serializable; import java.util.Date; /** * 表属性 * * @author yuqf */ public class Table implements Serializable { private static final long serialVersionUID = 1L; /** * 数据源Id */ private String datasourceId; /** * 库 */ private String catalog; /** * 模式 */ private String schema; /** * 表名 */ private String tableName; /** * 表类型。典型的类型是“TABLE”,“VIEW”,“SYSTEM TABLE”,“GLOBAL TEMPORARY”,“LOCAL TEMPORARY”,“ALIAS”,“SYNONYM”。 */ private String tableType; /** * 表备注 */ private String remarks; /** * 表状态 */ private String status; /** * 表大小(字节单位) */ private Long size; /** * 表行数 */ private Long rows; /** * 表创建时间 */ private Date createTime; /** * 表修改时间 */ private Date updateTime; public String getDatasourceId() { return datasourceId; } public void setDatasourceId(String datasourceId) { this.datasourceId = datasourceId; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getTableType() { return tableType; } public void setTableType(String tableType) { this.tableType = tableType; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public Long getRows() { return rows; } public void setRows(Long rows) { this.rows = rows; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Schema.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Schema.java
package cn.crabc.core.spi.bean; import java.io.Serializable; /** * Schema属性 * * @author yuqf */ public class Schema implements Serializable { private static final long serialVersionUID = 1L; /** 数据源Id */ private String datasourceId; /** 库 */ private String catalog; /** 模式 */ private String schema; public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getDatasourceId() { return datasourceId; } public void setDatasourceId(String datasourceId) { this.datasourceId = datasourceId; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/BaseDataSource.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/BaseDataSource.java
/* * Copyright 2023, crabc.cn (creabc@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.crabc.core.spi.bean; import java.io.Serializable; /** * 数据源属性 * * @author yuqf */ public class BaseDataSource implements Serializable { private static final long serialVersionUID = 1L; /** * 数据源ID */ private String datasourceId; /** * 数据源名称 */ private String datasourceName; /** * 数据源类型 mysql、oracle、postgres */ private String datasourceType; /** * jdbcURL */ private String jdbcUrl; /** * IP */ private String host; /** * port */ private String port; /** * 用户名 */ private String username; /** * 密码 */ private String password; /** * 描述 */ private String remarks; /** * 分类 */ private String classify; /** * 状态 */ private Integer enabled; /** * 扩展字段 */ private String extend; /** * 解密密钥 */ private String secretKey; public String getDatasourceId() { return datasourceId; } public void setDatasourceId(String datasourceId) { this.datasourceId = datasourceId; } public String getDatasourceName() { return datasourceName; } public void setDatasourceName(String datasourceName) { this.datasourceName = datasourceName; } public String getDatasourceType() { return datasourceType; } public void setDatasourceType(String datasourceType) { this.datasourceType = datasourceType; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Integer getEnabled() { return enabled; } public void setEnabled(Integer enabled) { this.enabled = enabled; } public String getExtend() { return extend; } public void setExtend(String extend) { this.extend = extend; } public String getClassify() { return classify; } public void setClassify(String classify) { this.classify = classify; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
pingapi/crabc-api
https://github.com/pingapi/crabc-api/blob/7a53390946add532c7cfa5205b839c1ea025c20d/crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Column.java
crabc-boot/crabc-spi/src/main/java/cn/crabc/core/spi/bean/Column.java
package cn.crabc.core.spi.bean; import java.io.Serializable; /** * 列属性 * * @author yuqf */ public class Column implements Serializable { private static final long serialVersionUID = 1L; /** 数据源Id */ private String datasourceId; /** 库 */ private String catalog; /** 模式 */ private String schema; /** 表名称 */ private String tableName; private String columnName; private String remarks; /** 类型 */ private String columnType; /** 长度 */ private String columnSize; /** 精度 */ private String decimalDigits; private String columnDefault; private String typeIcon; public String getDatasourceId() { return datasourceId; } public void setDatasourceId(String datasourceId) { this.datasourceId = datasourceId; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getColumnType() { return columnType; } public void setColumnType(String columnType) { this.columnType = columnType; } public String getColumnSize() { return columnSize; } public void setColumnSize(String columnSize) { this.columnSize = columnSize; } public String getColumnDefault() { return columnDefault; } public void setColumnDefault(String columnDefault) { this.columnDefault = columnDefault; } public String getDecimalDigits() { return decimalDigits; } public void setDecimalDigits(String decimalDigits) { this.decimalDigits = decimalDigits; } public String getTypeIcon() { return typeIcon; } public void setTypeIcon(String typeIcon) { this.typeIcon = typeIcon; } }
java
Apache-2.0
7a53390946add532c7cfa5205b839c1ea025c20d
2026-01-05T02:34:24.725959Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-server/src/test/java/com/robert/vesta/server/AppTest.java
vesta-server/src/test/java/com/robert/vesta/server/AppTest.java
package com.robert.vesta.server; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-server/src/main/java/com/robert/vesta/server/VestaServer.java
vesta-server/src/main/java/com/robert/vesta/server/VestaServer.java
package com.robert.vesta.server; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class VestaServer { public static void main(String[] args) throws IOException { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "spring/vesta-server-main.xml"); context.start(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (!"exit".equals(br.readLine())) try { Thread.sleep(60000); } catch (InterruptedException e) { // If error, print it to console e.printStackTrace(); } ; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-sample/vesta-sample-client/src/test/java/com/robert/sample/client/AppTest.java
vesta-sample/vesta-sample-client/src/test/java/com/robert/sample/client/AppTest.java
package com.robert.sample.client; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-sample/vesta-sample-client/src/main/java/com/robert/sample/client/ClientSample.java
vesta-sample/vesta-sample-client/src/main/java/com/robert/sample/client/ClientSample.java
package com.robert.sample.client; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ClientSample { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-client-sample.xml"); IdService idService = (IdService) ac.getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); System.out.println(id + ":" + ido); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-sample/vesta-sample-embed/src/test/java/com/robert/vesta/sample/embed/AppTest.java
vesta-sample/vesta-sample-embed/src/test/java/com/robert/vesta/sample/embed/AppTest.java
package com.robert.vesta.sample.embed; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-sample/vesta-sample-embed/src/main/java/com/robert/vesta/sample/embed/EmbedSample.java
vesta-sample/vesta-sample-embed/src/main/java/com/robert/vesta/sample/embed/EmbedSample.java
package com.robert.vesta.sample.embed; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class EmbedSample { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-service-sample.xml"); IdService idService = (IdService) ac.getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); System.out.println(id + ":" + ido); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest/src/test/java/com/robert/vesta/rest/AppTest.java
vesta-rest/src/test/java/com/robert/vesta/rest/AppTest.java
package com.robert.vesta.rest; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest/src/main/java/com/robert/vesta/rest/IdController.java
vesta-rest/src/main/java/com/robert/vesta/rest/IdController.java
package com.robert.vesta.rest; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class IdController { private final IdService idService; public IdController() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-rest-main.xml"); idService = (IdService) ac.getBean("idService"); } @RequestMapping("/genid") public long genId() { return idService.genId(); } @RequestMapping("/expid") public Id explainId(@RequestParam(value = "id", defaultValue = "0") long id) { return idService.expId(id); } @RequestMapping("/transtime") public String transTime( @RequestParam(value = "time", defaultValue = "-1") long time) { return idService.transTime(time).toString(); } @RequestMapping("/makeid") public long makeId( @RequestParam(value = "version", defaultValue = "-1") long version, @RequestParam(value = "type", defaultValue = "-1") long type, @RequestParam(value = "genMethod", defaultValue = "-1") long genMethod, @RequestParam(value = "machine", defaultValue = "-1") long machine, @RequestParam(value = "time", defaultValue = "-1") long time, @RequestParam(value = "seq", defaultValue = "-1") long seq) { long madeId = -1; if (time == -1 || seq == -1) throw new IllegalArgumentException( "Both time and seq are required."); else if (version == -1) { if (type == -1) { if (genMethod == -1) { if (machine == -1) { madeId = idService.makeId(time, seq); } else { madeId = idService.makeId(machine, time, seq); } } else { madeId = idService.makeId(genMethod, machine, time, seq); } } else { madeId = idService.makeId(type, genMethod, machine, time, seq); } } else { madeId = idService.makeId(version, type, genMethod, time, seq, machine); } return madeId; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest/src/main/java/com/robert/vesta/rest/Application.java
vesta-rest/src/main/java/com/robert/vesta/rest/Application.java
package com.robert.vesta.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-client/src/test/java/com/robert/vesta/client/PerfTest.java
vesta-client/src/test/java/com/robert/vesta/client/PerfTest.java
package com.robert.vesta.client; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class PerfTest { public static void main(String[] args) throws InterruptedException { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-client-test.xml"); final IdService idService = (IdService) ac.getBean("idService"); final long[][] times = new long[100][100]; Thread[] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) { final int ip = i; threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < 100; j++) { long t1 = System.nanoTime(); idService.genId(); long t = System.nanoTime() - t1; times[ip][j] = t; } } }; } long lastMilis = System.currentTimeMillis(); for (int i = 0; i < threads.length; i++) { threads[i].start(); } for (int i = 0; i < threads.length; i++) { threads[i].join(); } System.out .println("QPS: " + ((10000 * 1000 / (System.currentTimeMillis() - lastMilis)))); long sum = 0; long max = 0; for (int i = 0; i < times.length; i++) { for (int j = 0; j < times[i].length; j++) { sum += times[i][j]; if (times[i][j] > max) max = times[i][j]; } } System.out.println("AVG(ms): " + sum / 1000000 / 10000); System.out.println("MAX(ms): " + max / 1000000); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-client/src/test/java/com/robert/vesta/client/VestaClientTest.java
vesta-client/src/test/java/com/robert/vesta/client/VestaClientTest.java
package com.robert.vesta.client; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.service.impl.converter.IdConverter; import com.robert.vesta.service.impl.converter.IdConverterImpl; import com.robert.vesta.service.intf.IdService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; @ContextConfiguration(locations = "/spring/vesta-client-test.xml") public class VestaClientTest extends AbstractTestNGSpringContextTests { @Test(groups = {"idServiceClient"}) public void testSimple() { IdService idService = (IdService) applicationContext .getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); IdConverter idConverter = new IdConverterImpl(IdType.MAX_PEAK); long id1 = idConverter.convert(ido); AssertJUnit.assertEquals(id, id1); System.out.println(id); System.out.println(id1); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-client/src/main/java/com/robert/vesta/client/App.java
vesta-client/src/main/java/com/robert/vesta/client/App.java
package com.robert.vesta.client; /** * Hello world! */ public class App { public static void main(String[] args) { System.out.println("Hello World!"); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest-netty/src/test/java/com/robert/vesta/rest/netty/AppTest.java
vesta-rest-netty/src/test/java/com/robert/vesta/rest/netty/AppTest.java
package com.robert.vesta.rest.netty; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServerInitializer.java
vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServerInitializer.java
package com.robert.vesta.rest.netty; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpServerCodec; public class VestaRestNettyServerInitializer extends ChannelInitializer<SocketChannel> { private VestaRestNettyServerHandler handler = new VestaRestNettyServerHandler(); @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("codec", new HttpServerCodec()); p.addLast("handler", handler); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServerHandler.java
vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServerHandler.java
package com.robert.vesta.rest.netty; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringDecoder; import net.sf.json.JSONObject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.net.URI; import java.nio.charset.Charset; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaders.is100ContinueExpected; import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; @Sharable public class VestaRestNettyServerHandler extends ChannelHandlerAdapter { private static final String ID = "id"; private static final String VERSION = "version"; private static final String TYPE = "type"; private static final String GENMETHOD = "genMethod"; private static final String MACHINE = "machine"; private static final String TIME = "time"; private static final String SEQ = "seq"; private static final String ACTION_GENID = "/genid"; private static final String ACTION_EXPID = "/expid"; private static final String ACTION_TRANSTIME = "/transtime"; private static final String ACTION_MAKEID = "/makeid"; private static final Log log = LogFactory .getLog(VestaRestNettyServerHandler.class); private IdService idService; public VestaRestNettyServerHandler() { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-rest-main.xml"); idService = (IdService) ac.getBean("idService"); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof HttpRequest)) return; HttpRequest req = (HttpRequest) msg; if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } URI uri = new URI(req.getUri()); if (log.isDebugEnabled()) log.debug("request uri==" + uri.getPath()); long id = -1; long time = -1; long version = -1; long type = -1; long genmethod = -1; long machine = -1; long seq = -1; QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { if (log.isDebugEnabled()) log.debug("Request Parameter: " + attr.getKey() + '=' + attrVal); if (ID.equals(attr.getKey())) { id = Long.parseLong(attrVal); } else if (TIME.equals(attr.getKey())) { time = Long.parseLong(attrVal); } else if (VERSION.equals(attr.getKey())) { version = Long.parseLong(attrVal); } else if (TYPE.equals(attr.getKey())) { type = Long.parseLong(attrVal); } else if (GENMETHOD.equals(attr.getKey())) { genmethod = Long.parseLong(attrVal); } else if (MACHINE.equals(attr.getKey())) { machine = Long.parseLong(attrVal); } else if (SEQ.equals(attr.getKey())) { seq = Long.parseLong(attrVal); } } } StringBuffer sbContent = new StringBuffer(); if (ACTION_GENID.equals(uri.getPath())) { long idl = idService.genId(); if (log.isTraceEnabled()) log.trace("Generated id: " + idl); sbContent.append(idl); } else if (ACTION_EXPID.equals(uri.getPath())) { Id ido = idService.expId(id); if (log.isTraceEnabled()) log.trace("Explained id: " + ido); JSONObject jo = JSONObject.fromObject(ido); sbContent.append(jo); } else if (ACTION_TRANSTIME.equals(uri.getPath())) { Date date = idService.transTime(time); if (log.isTraceEnabled()) log.trace("Time: " + date); sbContent.append(date); } else if (ACTION_MAKEID.equals(uri.getPath())) { long madeId = -1; if (time == -1 || seq == -1) sbContent.append("Both time and seq are required."); else if (version == -1) { if (type == -1) { if (genmethod == -1) { if (machine == -1) { madeId = idService.makeId(time, seq); } else { madeId = idService.makeId(machine, time, seq); } } else { madeId = idService .makeId(genmethod, machine, time, seq); } } else { madeId = idService.makeId(type, genmethod, machine, time, seq); } } else { madeId = idService.makeId(version, type, genmethod, machine, time, seq); } if (log.isTraceEnabled()) log.trace("Id: " + madeId); sbContent.append(madeId); } else { sbContent.append("\r\n"); sbContent.append("Please input right URI:"); sbContent.append("\r\n"); sbContent.append(" Example 1: http://ip:port/genid"); sbContent.append("\r\n"); sbContent.append(" Example 2: http://ip:port/expid?id=?"); sbContent.append("\r\n"); sbContent.append(" Example 3: http://ip:port/transtime?time=?"); sbContent.append("\r\n"); sbContent.append(" Example 4: http://ip:port/makeid?version=?&type=?&genmethod=?&machine=?&time=?&seq=?"); } if (log.isTraceEnabled()) log.trace("Message body: " + sbContent); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(sbContent.toString().getBytes( Charset.forName("UTF-8")))); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); boolean keepAlive = isKeepAlive(req); if (log.isTraceEnabled()) log.trace("Keep Alive: " + keepAlive); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (log.isErrorEnabled()) log.error("HTTP Server Error: ", cause); ctx.close(); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServer.java
vesta-rest-netty/src/main/java/com/robert/vesta/rest/netty/VestaRestNettyServer.java
package com.robert.vesta.rest.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class VestaRestNettyServer { private static final Log log = LogFactory .getLog(VestaRestNettyServer.class); private final int port; public VestaRestNettyServer(int port) { this.port = port; } public void run() throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new VestaRestNettyServerInitializer()); Channel ch = b.bind(port).sync().channel(); if (log.isDebugEnabled()) log.debug("VestaRestNettyServer is started."); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; if (args.length > 0) { port = Integer.parseInt(args[0]); } new VestaRestNettyServer(port).run(); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-intf/src/test/java/com/robert/vesta/service/intf/AppTest.java
vesta-intf/src/test/java/com/robert/vesta/service/intf/AppTest.java
package com.robert.vesta.service.intf; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { assertTrue(true); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-intf/src/main/java/com/robert/vesta/service/bean/Id.java
vesta-intf/src/main/java/com/robert/vesta/service/bean/Id.java
package com.robert.vesta.service.bean; import java.io.Serializable; public class Id implements Serializable { private static final long serialVersionUID = 6870931236218221183L; private long machine; private long seq; private long time; private long genMethod; private long type; private long version; public Id(long machine, long seq, long time, long genMethod, long type, long version) { super(); this.machine = machine; this.seq = seq; this.time = time; this.genMethod = genMethod; this.type = type; this.version = version; } public Id() { } public long getSeq() { return seq; } public void setSeq(long seq) { this.seq = seq; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public long getMachine() { return machine; } public void setMachine(long machine) { this.machine = machine; } public long getGenMethod() { return genMethod; } public void setGenMethod(long genMethod) { this.genMethod = genMethod; } public long getType() { return type; } public void setType(long type) { this.type = type; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append("machine=").append(machine).append(","); sb.append("seq=").append(seq).append(","); sb.append("time=").append(time).append(","); sb.append("genMethod=").append(genMethod).append(","); sb.append("type=").append(type).append(","); sb.append("version=").append(version).append("]"); return sb.toString(); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-intf/src/main/java/com/robert/vesta/service/intf/IdService.java
vesta-intf/src/main/java/com/robert/vesta/service/intf/IdService.java
package com.robert.vesta.service.intf; import com.robert.vesta.service.bean.Id; import java.util.Date; public interface IdService { public long genId(); public Id expId(long id); public long makeId(long time, long seq); public long makeId(long time, long seq, long machine); public long makeId(long genMethod, long time, long seq, long machine); public long makeId(long type, long genMethod, long time, long seq, long machine); public long makeId(long version, long type, long genMethod, long time, long seq, long machine); public Date transTime(long time); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServiceTest.java
vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServiceTest.java
package com.robert.vesta.service.impl.test; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; @ContextConfiguration(locations = "/spring/vesta-service-test.xml") public class IdServiceTest extends AbstractTestNGSpringContextTests { @Test(groups = {"idService"}) public void testSimple() { IdService idService = (IdService) applicationContext .getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } @Test(groups = {"idService"}) public void testIpConfigurable() { IdService idService = (IdService) applicationContext .getBean("idServiceIpConfigurable"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } @Test(groups = {"idService"}) public void testDb() { IdService idService = (IdService) applicationContext .getBean("idServiceDb"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/test/java/com/robert/vesta/service/impl/test/CustomIdMetaTest.java
vesta-service/src/test/java/com/robert/vesta/service/impl/test/CustomIdMetaTest.java
package com.robert.vesta.service.impl.test; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; @ContextConfiguration(locations = "/spring/vesta-service-idmeta-test.xml") public class CustomIdMetaTest extends AbstractTestNGSpringContextTests { @Test(groups = {"idService"}) public void testSimple() { IdService idService = (IdService) applicationContext.getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.out.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServicePerfTest.java
vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServicePerfTest.java
package com.robert.vesta.service.impl.test; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class IdServicePerfTest { public static void main(String[] args) throws InterruptedException { ApplicationContext ac = new ClassPathXmlApplicationContext( "spring/vesta-service-test.xml"); final IdService idService = (IdService) ac.getBean("idService"); final long[][] times = new long[100][10000]; Thread[] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) { final int ip = i; threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < 10000; j++) { long t1 = System.nanoTime(); idService.genId(); long t = System.nanoTime() - t1; times[ip][j] = t; } } }; } long lastMilis = System.currentTimeMillis(); for (int i = 0; i < threads.length; i++) { threads[i].start(); } for (int i = 0; i < threads.length; i++) { threads[i].join(); } System.out .println("QPS: " + ((1000000 / (System.currentTimeMillis() - lastMilis)) * 1000)); long sum = 0; long max = 0; for (int i = 0; i < times.length; i++) { for (int j = 0; j < times[i].length; j++) { sum += times[i][j]; if (times[i][j] > max) max = times[i][j]; } } System.out.println("AVG(us): " + sum / 1000 / 1000000); System.out.println("MAX(ms): " + max / 1000000); // Result is about 400,000 per second } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/test/java/com/robert/vesta/service/impl/test/MachineIdsIdServiceTest.java
vesta-service/src/test/java/com/robert/vesta/service/impl/test/MachineIdsIdServiceTest.java
package com.robert.vesta.service.impl.test; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; @ContextConfiguration(locations = "/spring/vesta-service-machineids-test.xml") public class MachineIdsIdServiceTest extends AbstractTestNGSpringContextTests { @Test(groups = {"idService"}) public void testSimple() { IdService idService = (IdService) applicationContext .getBean("idService"); for (int i = 0; i < 2; i++) { long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.out.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); try { System.out.println("You can change the system time in 10 seconds"); Thread.sleep(10000); } catch (InterruptedException e) { } } } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServiceFactoryBeanTest.java
vesta-service/src/test/java/com/robert/vesta/service/impl/test/IdServiceFactoryBeanTest.java
package com.robert.vesta.service.impl.test; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.intf.IdService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.AssertJUnit; import org.testng.annotations.Test; // There is only one factory bean in a single spring context, so we should create spring context for each test public class IdServiceFactoryBeanTest { @Test(groups = {"idService"}) public void testSimple() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "spring/vesta-service-factory-bean-property-test.xml"); IdService idService = (IdService) applicationContext .getBean("idService"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } @Test(groups = {"idService"}) public void testIpConfigurable() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "spring/vesta-service-factory-bean-ip-configurable-test.xml"); IdService idService = (IdService) applicationContext .getBean("idServiceIpConfigurable"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } @Test(groups = {"idService"}) public void testDb() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "spring/vesta-service-factory-bean-db-test.xml"); IdService idService = (IdService) applicationContext .getBean("idServiceDb"); long id = idService.genId(); Id ido = idService.expId(id); long id1 = idService.makeId(ido.getVersion(), ido.getType(), ido.getGenMethod(), ido.getTime(), ido.getSeq(), ido.getMachine()); System.err.println(id + ":" + ido); AssertJUnit.assertEquals(id, id1); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/util/CommonUtils.java
vesta-service/src/main/java/com/robert/vesta/util/CommonUtils.java
package com.robert.vesta.util; import java.util.Arrays; public class CommonUtils { public static String[] SWITCH_ON_EXP = new String[]{"ON", "TRUE", "on", "true"}; public static String[] SWITCH_OFF_EXP = new String[]{"OFF", "FALSE", "off", "false"}; public static boolean isOn(String swtch) { if (Arrays.asList(SWITCH_ON_EXP).contains(swtch)) { return true; } return false; } public static boolean isPropKeyOn(String key) { String prop = System.getProperty(key); if (Arrays.asList(SWITCH_ON_EXP).contains(prop)) { return true; } return false; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/util/TimeUtils.java
vesta-service/src/main/java/com/robert/vesta/util/TimeUtils.java
package com.robert.vesta.util; import com.robert.vesta.service.impl.bean.IdType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TimeUtils { protected static final Logger log = LoggerFactory.getLogger(TimeUtils.class); public static final long EPOCH = 1420041600000L; public static void validateTimestamp(long lastTimestamp, long timestamp) { if (timestamp < lastTimestamp) { if (log.isErrorEnabled()) log.error(String .format("Clock moved backwards. Refusing to generate id for %d second/milisecond.", lastTimestamp - timestamp)); throw new IllegalStateException( String.format( "Clock moved backwards. Refusing to generate id for %d second/milisecond.", lastTimestamp - timestamp)); } } public static long tillNextTimeUnit(final long lastTimestamp, final IdType idType) { if (log.isInfoEnabled()) log.info(String .format("Ids are used out during %d. Waiting till next second/milisencond.", lastTimestamp)); long timestamp = TimeUtils.genTime(idType); while (timestamp <= lastTimestamp) { timestamp = TimeUtils.genTime(idType); } if (log.isInfoEnabled()) log.info(String.format("Next second/milisencond %d is up.", timestamp)); return timestamp; } public static long genTime(final IdType idType) { if (idType == IdType.MAX_PEAK) return (System.currentTimeMillis() - TimeUtils.EPOCH) / 1000; else if (idType == IdType.MIN_GRANULARITY) return (System.currentTimeMillis() - TimeUtils.EPOCH); return (System.currentTimeMillis() - TimeUtils.EPOCH) / 1000; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/util/IpUtils.java
vesta-service/src/main/java/com/robert/vesta/util/IpUtils.java
package com.robert.vesta.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class IpUtils { private static final Logger log = LoggerFactory.getLogger(IpUtils.class); public static String getHostIp() { String ip = null; try { Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface intf = (NetworkInterface) en.nextElement(); Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); while (enumIpAddr.hasMoreElements()) { InetAddress inetAddress = (InetAddress) enumIpAddr .nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) { ip = inetAddress.getHostAddress(); } } } } catch (SocketException e) { log.error("Fail to get IP address.", e); } return ip; } public static String getHostName() { String hostName = null; try { Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface intf = (NetworkInterface) en.nextElement(); Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); while (enumIpAddr.hasMoreElements()) { InetAddress inetAddress = (InetAddress) enumIpAddr .nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) { hostName = inetAddress.getHostName(); } } } } catch (SocketException e) { log.error("Fail to get host name.", e); } return hostName; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/MachineIdsIdServiceImpl.java
vesta-service/src/main/java/com/robert/vesta/service/impl/MachineIdsIdServiceImpl.java
package com.robert.vesta.service.impl; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.service.impl.populater.IdPopulator; import com.robert.vesta.service.impl.populater.ResetPopulator; import com.robert.vesta.service.impl.provider.MachineIdsProvider; import com.robert.vesta.util.TimeUtils; import java.io.*; import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MachineIdsIdServiceImpl extends IdServiceImpl { protected long lastTimestamp = -1; protected Map<Long, Long> machineIdMap = new ConcurrentHashMap<Long, Long>(); public static final String STORE_FILE_NAME = "machineIdInfo.store"; private String storeFilePath; private File storeFile; private Lock lock = new ReentrantLock(); @Override public void init() { if (!(this.machineIdProvider instanceof MachineIdsProvider)) { log.error("The machineIdProvider is not a MachineIdsProvider instance so that Vesta Service refuses to start."); throw new RuntimeException( "The machineIdProvider is not a MachineIdsProvider instance so that Vesta Service refuses to start."); } super.init(); initStoreFile(); initMachineId(); } @Override protected void populateId(Id id) { supportChangeMachineId(id); } private void supportChangeMachineId(Id id) { try { id.setMachine(this.machineId); idPopulator.populateId(id, this.idMeta); this.lastTimestamp = id.getTime(); } catch (IllegalStateException e) { log.warn("Clock moved backwards, change MachineId and reset IdPopulator"); lock.lock(); try { if (id.getMachine() == this.machineId) { changeMachineId(); resetIdPopulator(); } } finally { lock.unlock(); } supportChangeMachineId(id); } } protected void changeMachineId() { this.machineIdMap.put(this.machineId, this.lastTimestamp); storeInFile(); initMachineId(); } protected void resetIdPopulator() { if (idPopulator instanceof ResetPopulator) { ((ResetPopulator) idPopulator).reset(); } else { try { IdPopulator newIdPopulator = this.idPopulator.getClass().newInstance(); this.idPopulator = newIdPopulator; } catch (InstantiationException e1) { throw new RuntimeException("Reset IdPopulator <[" + this.idPopulator.getClass().getCanonicalName() + "]> instance error", e1); } catch (IllegalAccessException e1) { throw new RuntimeException("Reset IdPopulator <[" + this.idPopulator.getClass().getCanonicalName() + "]> instance error", e1); } } } protected void initStoreFile() { if (storeFilePath == null || storeFilePath.length() == 0) { storeFilePath = System.getProperty("user.dir") + File.separator + STORE_FILE_NAME; } try { log.info("machineId info store in <[" + storeFilePath + "]>"); storeFile = new File(storeFilePath); if (storeFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(storeFile)); String line = reader.readLine(); while (line != null && line.length() > 0) { String[] kvs = line.split(":"); if (kvs.length == 2) { this.machineIdMap.put(Long.parseLong(kvs[0]), Long.parseLong(kvs[1])); } else { throw new IllegalArgumentException(storeFile.getAbsolutePath() + " has illegal value <[" + line + "]>"); } line = reader.readLine(); } reader.close(); } } catch (FileNotFoundException e) { } catch (IOException e) { } } protected void initMachineId() { long startId = this.machineId; long newMachineId = this.machineId; while(true) { if (this.machineIdMap.containsKey(newMachineId)) { long timestamp = TimeUtils.genTime(IdType.parse(this.type)); if (this.machineIdMap.get(newMachineId) < timestamp) { this.machineId = newMachineId; break; } else { newMachineId = ((MachineIdsProvider)this.machineIdProvider).getNextMachineId(); } if(newMachineId == startId){ throw new RuntimeException("No machineId is available"); } } else { this.machineId = newMachineId; break; } } } protected void storeInFile() { Writer writer = null; try { writer = new FileWriter(storeFile, false); for (Map.Entry<Long, Long> entry : this.machineIdMap.entrySet()) { writer.write(entry.getKey() + ":" + entry.getValue() + "\n"); } } catch (IOException e) { log.error("Write machineId info to File<[" + storeFile.getAbsolutePath() + "]> error"); throw new RuntimeException("Write machineId info to File<[" + storeFile.getAbsolutePath() + "]> error"); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } public void setStoreFilePath(String storeFilePath) { this.storeFilePath = storeFilePath; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/IdServiceImpl.java
vesta-service/src/main/java/com/robert/vesta/service/impl/IdServiceImpl.java
package com.robert.vesta.service.impl; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.service.impl.populater.AtomicIdPopulator; import com.robert.vesta.service.impl.populater.IdPopulator; import com.robert.vesta.service.impl.populater.LockIdPopulator; import com.robert.vesta.service.impl.populater.SyncIdPopulator; import com.robert.vesta.util.CommonUtils; public class IdServiceImpl extends AbstractIdServiceImpl { private static final String SYNC_LOCK_IMPL_KEY = "vesta.sync.lock.impl.key"; private static final String ATOMIC_IMPL_KEY = "vesta.atomic.impl.key"; protected IdPopulator idPopulator; public IdServiceImpl() { super(); initPopulator(); } public IdServiceImpl(String type) { super(type); initPopulator(); } public IdServiceImpl(IdType type) { super(type); initPopulator(); } public void initPopulator() { if(idPopulator != null){ log.info("The " + idPopulator.getClass().getCanonicalName() + " is used."); } else if (CommonUtils.isPropKeyOn(SYNC_LOCK_IMPL_KEY)) { log.info("The SyncIdPopulator is used."); idPopulator = new SyncIdPopulator(); } else if (CommonUtils.isPropKeyOn(ATOMIC_IMPL_KEY)) { log.info("The AtomicIdPopulator is used."); idPopulator = new AtomicIdPopulator(); } else { log.info("The default LockIdPopulator is used."); idPopulator = new LockIdPopulator(); } } protected void populateId(Id id) { idPopulator.populateId(id, this.idMeta); } public void setIdPopulator(IdPopulator idPopulator) { this.idPopulator = idPopulator; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/AbstractIdServiceImpl.java
vesta-service/src/main/java/com/robert/vesta/service/impl/AbstractIdServiceImpl.java
package com.robert.vesta.service.impl; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; import com.robert.vesta.service.impl.bean.IdMetaFactory; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.service.impl.converter.IdConverter; import com.robert.vesta.service.impl.converter.IdConverterImpl; import com.robert.vesta.service.impl.provider.MachineIdProvider; import com.robert.vesta.service.intf.IdService; import com.robert.vesta.util.TimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; public abstract class AbstractIdServiceImpl implements IdService { protected final Logger log = LoggerFactory.getLogger(this.getClass()); protected long machineId = -1; protected long genMethod = 0; protected long type = 0; protected long version = 0; protected IdType idType; protected IdMeta idMeta; protected IdConverter idConverter; protected MachineIdProvider machineIdProvider; public AbstractIdServiceImpl() { idType = IdType.MAX_PEAK; } public AbstractIdServiceImpl(String type) { idType = IdType.parse(type); } public AbstractIdServiceImpl(IdType type) { idType = type; } public void init() { this.machineId = machineIdProvider.getMachineId(); if (machineId < 0) { log.error("The machine ID is not configured properly so that Vesta Service refuses to start."); throw new IllegalStateException( "The machine ID is not configured properly so that Vesta Service refuses to start."); } if(this.idMeta == null){ setIdMeta(IdMetaFactory.getIdMeta(idType)); setType(idType.value()); } else { if(this.idMeta.getTimeBits() == 30){ setType(0); } else if(this.idMeta.getTimeBits() == 40){ setType(1); } else { throw new RuntimeException("Init Error. The time bits in IdMeta should be set to 30 or 40!"); } } setIdConverter(new IdConverterImpl(this.idMeta)); } public long genId() { Id id = new Id(); id.setMachine(machineId); id.setGenMethod(genMethod); id.setType(type); id.setVersion(version); populateId(id); long ret = idConverter.convert(id); // Use trace because it cause low performance if (log.isTraceEnabled()) log.trace(String.format("Id: %s => %d", id, ret)); return ret; } protected abstract void populateId(Id id); public Date transTime(final long time) { if (idType == IdType.MAX_PEAK) { return new Date(time * 1000 + TimeUtils.EPOCH); } else if (idType == IdType.MIN_GRANULARITY) { return new Date(time + TimeUtils.EPOCH); } return null; } public Id expId(long id) { return idConverter.convert(id); } public long makeId(long time, long seq) { return makeId(time, seq, machineId); } public long makeId(long time, long seq, long machine) { return makeId(genMethod, time, seq, machine); } public long makeId(long genMethod, long time, long seq, long machine) { return makeId(type, genMethod, time, seq, machine); } public long makeId(long type, long genMethod, long time, long seq, long machine) { return makeId(version, type, genMethod, time, seq, machine); } public long makeId(long version, long type, long genMethod, long time, long seq, long machine) { IdType idType = IdType.parse(type); Id id = new Id(machine, seq, time, genMethod, type, version); IdConverter idConverter = new IdConverterImpl(idType); return idConverter.convert(id); } public void setMachineId(long machineId) { this.machineId = machineId; } public void setGenMethod(long genMethod) { this.genMethod = genMethod; } public void setType(long type) { this.type = type; } public void setVersion(long version) { this.version = version; } public void setIdConverter(IdConverter idConverter) { this.idConverter = idConverter; } public void setIdMeta(IdMeta idMeta) { this.idMeta = idMeta; } public void setMachineIdProvider(MachineIdProvider machineIdProvider) { this.machineIdProvider = machineIdProvider; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/converter/IdConverter.java
vesta-service/src/main/java/com/robert/vesta/service/impl/converter/IdConverter.java
package com.robert.vesta.service.impl.converter; import com.robert.vesta.service.bean.Id; public interface IdConverter { public long convert(Id id); public Id convert(long id); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/converter/IdConverterImpl.java
vesta-service/src/main/java/com/robert/vesta/service/impl/converter/IdConverterImpl.java
package com.robert.vesta.service.impl.converter; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; import com.robert.vesta.service.impl.bean.IdMetaFactory; import com.robert.vesta.service.impl.bean.IdType; public class IdConverterImpl implements IdConverter { private IdMeta idMeta; public IdConverterImpl() { } public IdConverterImpl(IdType idType) { this(IdMetaFactory.getIdMeta(idType)); } public IdConverterImpl(IdMeta idMeta) { this.idMeta = idMeta; } public long convert(Id id) { return doConvert(id, idMeta); } protected long doConvert(Id id, IdMeta idMeta) { long ret = 0; ret |= id.getMachine(); ret |= id.getSeq() << idMeta.getSeqBitsStartPos(); ret |= id.getTime() << idMeta.getTimeBitsStartPos(); ret |= id.getGenMethod() << idMeta.getGenMethodBitsStartPos(); ret |= id.getType() << idMeta.getTypeBitsStartPos(); ret |= id.getVersion() << idMeta.getVersionBitsStartPos(); return ret; } public Id convert(long id) { return doConvert(id, idMeta); } protected Id doConvert(long id, IdMeta idMeta) { Id ret = new Id(); ret.setMachine(id & idMeta.getMachineBitsMask()); ret.setSeq((id >>> idMeta.getSeqBitsStartPos()) & idMeta.getSeqBitsMask()); ret.setTime((id >>> idMeta.getTimeBitsStartPos()) & idMeta.getTimeBitsMask()); ret.setGenMethod((id >>> idMeta.getGenMethodBitsStartPos()) & idMeta.getGenMethodBitsMask()); ret.setType((id >>> idMeta.getTypeBitsStartPos()) & idMeta.getTypeBitsMask()); ret.setVersion((id >>> idMeta.getVersionBitsStartPos()) & idMeta.getVersionBitsMask()); return ret; } public IdMeta getIdMeta() { return idMeta; } public void setIdMeta(IdMeta idMeta) { this.idMeta = idMeta; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/MachineIdsProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/MachineIdsProvider.java
package com.robert.vesta.service.impl.provider; public interface MachineIdsProvider extends MachineIdProvider { long getNextMachineId(); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/IpConfigurableMachineIdProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/IpConfigurableMachineIdProvider.java
package com.robert.vesta.service.impl.provider; import com.robert.vesta.util.IpUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.Map; public class IpConfigurableMachineIdProvider implements MachineIdProvider { private static final Logger log = LoggerFactory .getLogger(IpConfigurableMachineIdProvider.class); private long machineId; private Map<String, Long> ipsMap = new HashMap<String, Long>(); public IpConfigurableMachineIdProvider() { log.debug("IpConfigurableMachineIdProvider constructed."); } public IpConfigurableMachineIdProvider(String ips) { setIps(ips); init(); } public void init() { String ip = IpUtils.getHostIp(); if (StringUtils.isEmpty(ip)) { String msg = "Fail to get host IP address. Stop to initialize the IpConfigurableMachineIdProvider provider."; log.error(msg); throw new IllegalStateException(msg); } if (!ipsMap.containsKey(ip)) { String msg = String .format("Fail to configure ID for host IP address %s. Stop to initialize the IpConfigurableMachineIdProvider provider.", ip); log.error(msg); throw new IllegalStateException(msg); } machineId = ipsMap.get(ip); log.info("IpConfigurableMachineIdProvider.init ip {} id {}", ip, machineId); } public void setIps(String ips) { log.debug("IpConfigurableMachineIdProvider ips {}", ips); if (!StringUtils.isEmpty(ips)) { String[] ipArray = ips.split(","); for (int i = 0; i < ipArray.length; i++) { ipsMap.put(ipArray[i], (long) i); } } } public long getMachineId() { return machineId; } public void setMachineId(long machineId) { this.machineId = machineId; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/PropertyMachineIdProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/PropertyMachineIdProvider.java
package com.robert.vesta.service.impl.provider; public class PropertyMachineIdProvider implements MachineIdProvider { private long machineId; public long getMachineId() { return machineId; } public void setMachineId(long machineId) { this.machineId = machineId; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/MachineIdProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/MachineIdProvider.java
package com.robert.vesta.service.impl.provider; public interface MachineIdProvider { public long getMachineId(); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/PropertyMachineIdsProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/PropertyMachineIdsProvider.java
package com.robert.vesta.service.impl.provider; public class PropertyMachineIdsProvider implements MachineIdsProvider { private long[] machineIds; private int currentIndex; public long getNextMachineId() { return getMachineId(); } public long getMachineId() { return machineIds[currentIndex++%machineIds.length]; } public void setMachineIds(long[] machineIds) { this.machineIds = machineIds; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/provider/DbMachineIdProvider.java
vesta-service/src/main/java/com/robert/vesta/service/impl/provider/DbMachineIdProvider.java
package com.robert.vesta.service.impl.provider; import com.robert.vesta.util.IpUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.StringUtils; public class DbMachineIdProvider implements MachineIdProvider { private static final Logger log = LoggerFactory .getLogger(DbMachineIdProvider.class); private long machineId; private JdbcTemplate jdbcTemplate; public DbMachineIdProvider() { log.debug("IpConfigurableMachineIdProvider constructed."); } public void init() { String ip = IpUtils.getHostIp(); if (StringUtils.isEmpty(ip)) { String msg = "Fail to get host IP address. Stop to initialize the DbMachineIdProvider provider."; log.error(msg); throw new IllegalStateException(msg); } Long id = null; try { id = jdbcTemplate.queryForObject( "select ID from DB_MACHINE_ID_PROVIDER where IP = ?", new Object[]{ip}, Long.class); } catch (EmptyResultDataAccessException e) { // Ignore the exception log.error("No allocation before for ip {}.", ip); } if (id != null) { machineId = id; return; } log.info( "Fail to get ID from DB for host IP address {}. Next step try to allocate one.", ip); int count = jdbcTemplate .update("update DB_MACHINE_ID_PROVIDER set IP = ? where IP is null limit 1", ip); if (count <= 0 || count > 1) { String msg = String .format("Fail to allocte ID for host IP address {}. The {} records are updated. Stop to initialize the DbMachineIdProvider provider.", ip, count); log.error(msg); throw new IllegalStateException(msg); } try { id = jdbcTemplate.queryForObject( "select ID from DB_MACHINE_ID_PROVIDER where IP = ?", new Object[]{ip}, Long.class); } catch (EmptyResultDataAccessException e) { // Ignore the exception log.error("Fail to do allocation for ip {}.", ip); } if (id == null) { String msg = String .format("Fail to get ID from DB for host IP address {} after allocation. Stop to initialize the DbMachineIdProvider provider.", ip); log.error(msg); throw new IllegalStateException(msg); } machineId = id; } public long getMachineId() { return machineId; } public void setMachineId(long machineId) { this.machineId = machineId; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdType.java
vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdType.java
package com.robert.vesta.service.impl.bean; public enum IdType { MAX_PEAK("max-peak"), MIN_GRANULARITY("min-granularity"); private String name; private IdType(String name) { this.name = name; } public long value() { switch (this) { case MAX_PEAK: return 0; case MIN_GRANULARITY: return 1; default: return 0; } } @Override public String toString() { return this.name; } public static IdType parse(String name) { if ("min-granularity".equals(name)) return MIN_GRANULARITY; else if ("max-peak".equals(name)) return MAX_PEAK; return null; } public static IdType parse(long type) { if (type == 1) return MIN_GRANULARITY; else if (type == 0) return MAX_PEAK; return null; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdMetaFactory.java
vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdMetaFactory.java
package com.robert.vesta.service.impl.bean; public class IdMetaFactory { private static IdMeta maxPeak = new IdMeta((byte) 10, (byte) 20, (byte) 30, (byte) 2, (byte) 1, (byte) 1); private static IdMeta minGranularity = new IdMeta((byte) 10, (byte) 10, (byte) 40, (byte) 2, (byte) 1, (byte) 1); public static IdMeta getIdMeta(IdType type) { if (IdType.MAX_PEAK.equals(type)) { return maxPeak; } else if (IdType.MIN_GRANULARITY.equals(type)) { return minGranularity; } return null; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdMeta.java
vesta-service/src/main/java/com/robert/vesta/service/impl/bean/IdMeta.java
package com.robert.vesta.service.impl.bean; public class IdMeta { private byte machineBits; private byte seqBits; private byte timeBits; private byte genMethodBits; private byte typeBits; private byte versionBits; public IdMeta(byte machineBits, byte seqBits, byte timeBits, byte genMethodBits, byte typeBits, byte versionBits) { super(); this.machineBits = machineBits; this.seqBits = seqBits; this.timeBits = timeBits; this.genMethodBits = genMethodBits; this.typeBits = typeBits; this.versionBits = versionBits; } public byte getMachineBits() { return machineBits; } public void setMachineBits(byte machineBits) { this.machineBits = machineBits; } public long getMachineBitsMask() { return -1L ^ -1L << machineBits; } public byte getSeqBits() { return seqBits; } public void setSeqBits(byte seqBits) { this.seqBits = seqBits; } public long getSeqBitsStartPos() { return machineBits; } public long getSeqBitsMask() { return -1L ^ -1L << seqBits; } public byte getTimeBits() { return timeBits; } public void setTimeBits(byte timeBits) { this.timeBits = timeBits; } public long getTimeBitsStartPos() { return machineBits + seqBits; } public long getTimeBitsMask() { return -1L ^ -1L << timeBits; } public byte getGenMethodBits() { return genMethodBits; } public void setGenMethodBits(byte genMethodBits) { this.genMethodBits = genMethodBits; } public long getGenMethodBitsStartPos() { return machineBits + seqBits + timeBits; } public long getGenMethodBitsMask() { return -1L ^ -1L << genMethodBits; } public byte getTypeBits() { return typeBits; } public void setTypeBits(byte typeBits) { this.typeBits = typeBits; } public long getTypeBitsStartPos() { return machineBits + seqBits + timeBits + genMethodBits; } public long getTypeBitsMask() { return -1L ^ -1L << typeBits; } public byte getVersionBits() { return versionBits; } public void setVersionBits(byte versionBits) { this.versionBits = versionBits; } public long getVersionBitsStartPos() { return machineBits + seqBits + timeBits + genMethodBits + typeBits; } public long getVersionBitsMask() { return -1L ^ -1L << versionBits; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/LockIdPopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/LockIdPopulator.java
package com.robert.vesta.service.impl.populater; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockIdPopulator extends BasePopulator { private Lock lock = new ReentrantLock(); public LockIdPopulator() { super(); } public void populateId(Id id, IdMeta idMeta) { lock.lock(); try { super.populateId(id, idMeta); } finally { lock.unlock(); } } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/ResetPopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/ResetPopulator.java
package com.robert.vesta.service.impl.populater; public interface ResetPopulator { void reset(); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/AtomicIdPopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/AtomicIdPopulator.java
package com.robert.vesta.service.impl.populater; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.util.TimeUtils; import java.util.concurrent.atomic.AtomicReference; public class AtomicIdPopulator implements IdPopulator, ResetPopulator { class Variant { private long sequence = 0; private long lastTimestamp = -1; } private AtomicReference<Variant> variant = new AtomicReference<Variant>(new Variant()); public AtomicIdPopulator() { super(); } public void populateId(Id id, IdMeta idMeta) { Variant varOld, varNew; long timestamp, sequence; while (true) { // Save the old variant varOld = variant.get(); // populate the current variant timestamp = TimeUtils.genTime(IdType.parse(id.getType())); TimeUtils.validateTimestamp(varOld.lastTimestamp, timestamp); sequence = varOld.sequence; if (timestamp == varOld.lastTimestamp) { sequence++; sequence &= idMeta.getSeqBitsMask(); if (sequence == 0) { timestamp = TimeUtils.tillNextTimeUnit(varOld.lastTimestamp, IdType.parse(id.getType())); } } else { sequence = 0; } // Assign the current variant by the atomic tools varNew = new Variant(); varNew.sequence = sequence; varNew.lastTimestamp = timestamp; if (variant.compareAndSet(varOld, varNew)) { id.setSeq(sequence); id.setTime(timestamp); break; } } } public void reset() { variant = new AtomicReference<Variant>(new Variant()); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/BasePopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/BasePopulator.java
package com.robert.vesta.service.impl.populater; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; import com.robert.vesta.service.impl.bean.IdType; import com.robert.vesta.util.TimeUtils; public abstract class BasePopulator implements IdPopulator, ResetPopulator { protected long sequence = 0; protected long lastTimestamp = -1; public BasePopulator() { super(); } public void populateId(Id id, IdMeta idMeta) { long timestamp = TimeUtils.genTime(IdType.parse(id.getType())); TimeUtils.validateTimestamp(lastTimestamp, timestamp); if (timestamp == lastTimestamp) { sequence++; sequence &= idMeta.getSeqBitsMask(); if (sequence == 0) { timestamp = TimeUtils.tillNextTimeUnit(lastTimestamp, IdType.parse(id.getType())); } } else { lastTimestamp = timestamp; sequence = 0; } id.setSeq(sequence); id.setTime(timestamp); } public void reset() { this.sequence = 0; this.lastTimestamp = -1; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/SyncIdPopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/SyncIdPopulator.java
package com.robert.vesta.service.impl.populater; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; public class SyncIdPopulator extends BasePopulator { public SyncIdPopulator() { super(); } public synchronized void populateId(Id id, IdMeta idMeta) { super.populateId(id, idMeta); } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/impl/populater/IdPopulator.java
vesta-service/src/main/java/com/robert/vesta/service/impl/populater/IdPopulator.java
package com.robert.vesta.service.impl.populater; import com.robert.vesta.service.bean.Id; import com.robert.vesta.service.impl.bean.IdMeta; public interface IdPopulator { void populateId(Id id, IdMeta idMeta); }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
iweisi/vesta-id-generator
https://github.com/iweisi/vesta-id-generator/blob/c983e7561ddb262b62b09dda0706a0be07a588ed/vesta-service/src/main/java/com/robert/vesta/service/factory/IdServiceFactoryBean.java
vesta-service/src/main/java/com/robert/vesta/service/factory/IdServiceFactoryBean.java
package com.robert.vesta.service.factory; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.robert.vesta.service.impl.IdServiceImpl; import com.robert.vesta.service.impl.provider.DbMachineIdProvider; import com.robert.vesta.service.impl.provider.IpConfigurableMachineIdProvider; import com.robert.vesta.service.impl.provider.PropertyMachineIdProvider; import com.robert.vesta.service.intf.IdService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.jdbc.core.JdbcTemplate; import java.beans.PropertyVetoException; public class IdServiceFactoryBean implements FactoryBean<IdService> { protected final Logger log = LoggerFactory .getLogger(IdServiceFactoryBean.class); public enum Type { PROPERTY, IP_CONFIGURABLE, DB } ; private Type providerType; private long machineId; private String ips; private String dbUrl; private String dbName; private String dbUser; private String dbPassword; private long genMethod = -1; private long type = -1; private long version = -1; private IdService idService; public void init() { if (providerType == null) { log.error("The type of Id service is mandatory."); throw new IllegalArgumentException( "The type of Id service is mandatory."); } switch (providerType) { case PROPERTY: idService = constructPropertyIdService(machineId); break; case IP_CONFIGURABLE: idService = constructIpConfigurableIdService(ips); break; case DB: idService = constructDbIdService(dbUrl, dbName, dbUser, dbPassword); break; } } public IdService getObject() throws Exception { return idService; } private IdService constructPropertyIdService(long machineId) { log.info("Construct Property IdService machineId {}", machineId); PropertyMachineIdProvider propertyMachineIdProvider = new PropertyMachineIdProvider(); propertyMachineIdProvider.setMachineId(machineId); IdServiceImpl idServiceImpl = new IdServiceImpl(); idServiceImpl.setMachineIdProvider(propertyMachineIdProvider); if (genMethod != -1) idServiceImpl.setGenMethod(genMethod); if (type != -1) idServiceImpl.setType(type); if (version != -1) idServiceImpl.setVersion(version); idServiceImpl.init(); return idServiceImpl; } private IdService constructIpConfigurableIdService(String ips) { log.info("Construct Ip Configurable IdService ips {}", ips); IpConfigurableMachineIdProvider ipConfigurableMachineIdProvider = new IpConfigurableMachineIdProvider( ips); IdServiceImpl idServiceImpl = new IdServiceImpl(); idServiceImpl.setMachineIdProvider(ipConfigurableMachineIdProvider); if (genMethod != -1) idServiceImpl.setGenMethod(genMethod); if (type != -1) idServiceImpl.setType(type); if (version != -1) idServiceImpl.setVersion(version); idServiceImpl.init(); return idServiceImpl; } private IdService constructDbIdService(String dbUrl, String dbName, String dbUser, String dbPassword) { log.info( "Construct Db IdService dbUrl {} dbName {} dbUser {} dbPassword {}", dbUrl, dbName, dbUser, dbPassword); ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); String jdbcDriver = "com.mysql.jdbc.Driver"; try { comboPooledDataSource.setDriverClass(jdbcDriver); } catch (PropertyVetoException e) { log.error("Wrong JDBC driver {}", jdbcDriver); log.error("Wrong JDBC driver error: ", e); throw new IllegalStateException("Wrong JDBC driver ", e); } comboPooledDataSource.setMinPoolSize(5); comboPooledDataSource.setMaxPoolSize(30); comboPooledDataSource.setIdleConnectionTestPeriod(20); comboPooledDataSource.setMaxIdleTime(25); comboPooledDataSource.setBreakAfterAcquireFailure(false); comboPooledDataSource.setCheckoutTimeout(3000); comboPooledDataSource.setAcquireRetryAttempts(50); comboPooledDataSource.setAcquireRetryDelay(1000); String url = String .format("jdbc:mysql://%s/%s?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true", dbUrl, dbName); comboPooledDataSource.setJdbcUrl(url); comboPooledDataSource.setUser(dbUser); comboPooledDataSource.setPassword(dbPassword); JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setLazyInit(false); jdbcTemplate.setDataSource(comboPooledDataSource); DbMachineIdProvider dbMachineIdProvider = new DbMachineIdProvider(); dbMachineIdProvider.setJdbcTemplate(jdbcTemplate); dbMachineIdProvider.init(); IdServiceImpl idServiceImpl = new IdServiceImpl(); idServiceImpl.setMachineIdProvider(dbMachineIdProvider); if (genMethod != -1) idServiceImpl.setGenMethod(genMethod); if (type != -1) idServiceImpl.setType(type); if (version != -1) idServiceImpl.setVersion(version); idServiceImpl.init(); return idServiceImpl; } public Class<?> getObjectType() { return IdService.class; } public boolean isSingleton() { return true; } public Type getProviderType() { return providerType; } public void setProviderType(Type providerType) { this.providerType = providerType; } public long getMachineId() { return machineId; } public void setMachineId(long machineId) { this.machineId = machineId; } public String getIps() { return ips; } public void setIps(String ips) { this.ips = ips; } public String getDbUrl() { return dbUrl; } public void setDbUrl(String dbUrl) { this.dbUrl = dbUrl; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public String getDbUser() { return dbUser; } public void setDbUser(String dbUser) { this.dbUser = dbUser; } public String getDbPassword() { return dbPassword; } public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; } public long getGenMethod() { return genMethod; } public void setGenMethod(long genMethod) { this.genMethod = genMethod; } public long getType() { return type; } public void setType(long type) { this.type = type; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } }
java
Apache-2.0
c983e7561ddb262b62b09dda0706a0be07a588ed
2026-01-05T02:41:46.873630Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2/src/test/java/rx/parse2/ParseObservableTest.java
rxparse2/src/test/java/rx/parse2/ParseObservableTest.java
/* * Copyright (C) 2015 8tory, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.parse2; import com.parse.*; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import bolts.Task; import io.reactivex.Observable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static mocker.Mocker.mocker; import java.io.File; import java.io.InputStream; public class ParseObservableTest { @Test public void testParseObservableAllNextAfterCompleted() { List<ParseUser> users = mocker(ParseUser.class).when(user -> user.getObjectId()).thenReturn(user -> String.valueOf(user.hashCode())).asList(3); rx.parse2.ParseObservable.all(mocker(ParseQuery.class) .when(query -> query.countInBackground()).thenReturn(query -> Task.forResult(users.size())) .when(query -> query.findInBackground()).thenReturn(query -> Task.forResult(users)) .when(query -> query.setSkip(any(int.class))).thenReturn(query -> null) .when(query -> query.setLimit(any(int.class))).thenReturn(query -> null).mock()) //.doOnNext(user -> System.out.println("" + ((ParseUser) user).getObjectId()))) .test() .assertNoErrors() //.assertValue(check(l -> assertThat(l).isEqualTo(users))) .assertComplete(); } @Test public void testParseObservableAllForMass() { // FIXME: how mockito to make mass mocks? List<ParseUser> users = Observable.range(1, 1001) .map(i -> mocker(ParseUser.class).when(user -> user.getObjectId()).thenReturn(user -> "" + i + user.hashCode()).mock()) .toList() .blockingGet(); rx.parse2.ParseObservable.all(mocker(ParseQuery.class) .when(query -> query.countInBackground()).thenReturn(query -> Task.forResult(users.size())) .when(query -> query.findInBackground()).thenReturn(query -> Task.forResult(users)) .when(query -> query.setSkip(any(int.class))).thenReturn(query -> null) .when(query -> query.setLimit(any(int.class))).thenReturn(query -> null).mock()) .test() .assertNoErrors() //.assertValue(check(l -> assertThat(l).isEqualTo(users))) .assertComplete(); } @Test public void testParseObservableFindNextAfterCompleted() { List<ParseUser> users = Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class)); rx.parse2.ParseObservable.find(mocker(ParseQuery.class) .when(query -> query.findInBackground()).thenReturn(query -> Task.forResult(users)) .mock()) .test() .assertNoErrors() //.assertValue(check(l -> assertThat(l).isEqualTo(users))) .assertComplete(); } @Test public void testParseObservableFirst() { List<ParseUser> users = Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class)); rx.parse2.ParseObservable.first(mocker(ParseQuery.class) .when(query -> query.getFirstInBackground()).thenReturn(query -> Task.forResult(users.get(0))) .mock()) .test() .assertNoErrors() .assertValue(users.get(0)) .assertComplete(); } @Test public void testParseObservableGet() { rx.parse2.ParseObservable.get(mocker(ParseQuery.class) .when(query -> query.getInBackground(any(String.class))).thenReturn(query -> Task.forResult(mock(ParseUser.class))) .mock(), "hello") .test() .assertNoErrors() .assertComplete(); } @Test public void testBlockingFind() throws ParseException { List<ParseUser> users = Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class)); ParseQuery<ParseUser> query = mocker(ParseQuery.class) .when(q -> q.findInBackground()).thenReturn(q -> Task.forResult(users)) .when(q -> { List<ParseUser> list = Collections.emptyList(); try { list = q.find(); } catch (Exception e) { } return list; }).thenReturn(q -> users) .mock(); assertThat(query.find()).isEqualTo(rx.parse2.ParseObservable.find(query).toList().blockingGet()); } @Test public void testParseObservablePin() { rx.parse2.ParseObservable.pin(mocker(ParseUser.class) .when(user -> user.pinInBackground()) .thenReturn(user -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservablePinName() { rx.parse2.ParseObservable.pin("hello", mocker(ParseUser.class) .when(user -> user.pinInBackground(any(String.class))) .thenReturn(user -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableUnpin() { rx.parse2.ParseObservable.unpin(mocker(ParseUser.class) .when(user -> user.unpinInBackground()) .thenReturn(user -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableUnpinName() { rx.parse2.ParseObservable.unpin("hello", mocker(ParseUser.class) .when(user -> user.unpinInBackground(any(String.class))) .thenReturn(user -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSaveEventually() { ParseUser user = mock(ParseUser.class); rx.parse2.ParseObservable.saveEventually(user) .test().assertFailure(NullPointerException.class); try { verify(user).saveEventually(); } catch (Exception e) { //e.printStackTrace(); } /* NPE rx.parse.ParseObservable.saveEventually(mocker(ParseUser.class) .when(user -> user.saveEventually()) .thenReturn(user -> Task.<Void>forResult(null)) .mock())) .test() .assertNoErrors() .assertComplete(); */ /* isDirty() ParseUser user = mock(ParseUser.class); doReturn(Task.<Void>forResult(null)).when(user).saveEventually(); rx.parse.ParseObservable.saveEventually(user)) .test() .assertNoErrors() .assertComplete(); */ } @Test public void testParseObservableFetch() { /* ParseUser user = mock(ParseUser.class); rx.parse.ParseObservable.fetch(user)) .fails(); try { verify(user).fetchInBackground(); } catch (Exception e) { //e.printStackTrace(); } */ /* NPE rx.parse.ParseObservable.fetch(mocker(ParseUser.class) .when(user -> user.fetchInBackground()) .thenReturn(user -> Task.<Void>forResult(null)) .then(user -> doThrow(new RuntimeException()).when(user)) .mock())) .test() .assertNoErrors() .assertComplete(); */ } @Test public void testParseObservableFetchIfNeeded() { ParseUser user = mock(ParseUser.class); rx.parse2.ParseObservable.fetchIfNeeded(user) .test().assertFailure(NullPointerException.class); try { verify(user).fetchIfNeededInBackground(); } catch (Exception e) { //e.printStackTrace(); } /* NPE rx.parse.ParseObservable.fetchIfNeeded(mocker(ParseUser.class) .when(user -> user.fetchIfNeededInBackground()) .thenReturn(user -> Task.<Void>forResult(null)) .mock())) .test() .assertNoErrors() .assertComplete(); */ } @Test public void testParseObservableSend() { rx.parse2.ParseObservable.send(mocker(ParsePush.class) .when(it -> it.sendInBackground()) .thenReturn(it -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSignUp() { rx.parse2.ParseObservable.signUp(mocker(ParseUser.class) .when(user -> user.signUpInBackground()) .thenReturn(user -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetData() { rx.parse2.ParseObservable.getData(mocker(ParseFile.class) .when(it -> it.getDataInBackground()) .thenReturn(it -> Task.<byte[]>forResult(new byte[1])) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetDataProgress() { rx.parse2.ParseObservable.getData(mocker(ParseFile.class) .when(it -> it.getDataInBackground(any(ProgressCallback.class))) .thenReturn(it -> Task.<byte[]>forResult(new byte[1])) .mock(), mock(ProgressCallback.class)) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetDataStream() { rx.parse2.ParseObservable.getDataStream(mocker(ParseFile.class) .when(it -> it.getDataStreamInBackground()) .thenReturn(it -> Task.forResult(mock(InputStream.class))) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetDataStreamProgress() { rx.parse2.ParseObservable.getDataStream(mocker(ParseFile.class) .when(it -> it.getDataStreamInBackground(any(ProgressCallback.class))) .thenReturn(it -> Task.forResult(mock(InputStream.class))) .mock(), mock(ProgressCallback.class)) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetFile() { rx.parse2.ParseObservable.getFile(mocker(ParseFile.class) .when(it -> it.getFileInBackground()) .thenReturn(it -> Task.forResult(new File("/"))) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableGetFileProgress() { rx.parse2.ParseObservable.getFile(mocker(ParseFile.class) .when(it -> it.getFileInBackground(any(ProgressCallback.class))) .thenReturn(it -> Task.forResult(new File("/"))) .mock(), mock(ProgressCallback.class)) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSaveFile() { rx.parse2.ParseObservable.save(mocker(ParseFile.class) .when(it -> it.saveInBackground()) .thenReturn(it -> Task.<Void>forResult(null)) .mock()) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSaveFileProgress() { rx.parse2.ParseObservable.save(mocker(ParseFile.class) .when(it -> it.saveInBackground(any(ProgressCallback.class))) .thenReturn(it -> Task.<Void>forResult(null)) .mock(), mock(ProgressCallback.class)) .test() .assertNoErrors() .assertComplete(); } @Test public void testConstructor() { assertThat(new ParseObservable()).isNotNull(); } public static <T> Predicate<T> check(Consumer<T> consumer) { return t -> { consumer.accept(t); return true; }; } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2/src/test/java/com/parse/ParseTestUtils.java
rxparse2/src/test/java/com/parse/ParseTestUtils.java
/* * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.parse; import bolts.Task; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class ParseTestUtils { /** * In our unit test, lots of controllers need to use currentParseUser. A normal * currentUserController will try to read user off disk which will throw exception since we do * not have android environment. This function register a mock currentUserController and simply * return a mock ParseUser for currentParseUser and null for currentSessionToken. It will make * ParseUser.getCurrentUserAsync() and ParseUser.getCurrentSessionTokenAsync() work. */ public static void setTestParseUser() { ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); when(currentUserController.getAsync()).thenReturn(Task.forResult(mock(ParseUser.class))); when(currentUserController.getCurrentSessionTokenAsync()) .thenReturn(Task.<String>forResult(null)); ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2/src/test/java/com/parse/ParseObservableTest.java
rxparse2/src/test/java/com/parse/ParseObservableTest.java
/* * Copyright (c) 2015-present, 8tory. Inc. * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.parse; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import bolts.Task; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static mocker.Mocker.mocker; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import rx.parse2.BuildConfig; // Avoid cannot be accessed from outside package @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class) public class ParseObservableTest { @Before public void setUp() { ParseTestUtils.setTestParseUser(); Parse.enableLocalDatastore(RuntimeEnvironment.application.getApplicationContext()); ParseObject.registerSubclass(ParseUser.class); } @After public void tearDown() { ParseObject.unregisterSubclass(ParseUser.class); ParseCorePlugins.getInstance().reset(); Parse.disableLocalDatastore(); } @Test public void testParseObservableAllNextAfterCompleted() { ParseQueryController queryController = mock(ParseQueryController.class); ParseCorePlugins.getInstance().registerQueryController(queryController); List<ParseUser> users = Arrays.asList( mocker(ParseUser.class).when(user -> user.getObjectId()).thenReturn(user -> "1_" + user.hashCode()).mock(), mocker(ParseUser.class).when(user -> user.getObjectId()).thenReturn(user -> "2_" + user.hashCode()).mock(), mocker(ParseUser.class).when(user -> user.getObjectId()).thenReturn(user -> "3_" + user.hashCode()).mock()); Task<List<ParseUser>> task = Task.forResult(users); when(queryController.findAsync( any(ParseQuery.State.class), any(ParseUser.class), any(Task.class)) ).thenReturn(task); when(queryController.countAsync( any(ParseQuery.State.class), any(ParseUser.class), any(Task.class))).thenReturn(Task.<Integer>forResult(users.size())); ParseQuery<ParseUser> query = ParseQuery.getQuery(ParseUser.class); query.setUser(new ParseUser()); rx.parse2.ParseObservable.all(query) .test() .assertNoErrors() //.assertValue(users) .assertComplete(); try { ParseTaskUtils.wait(task); } catch (Exception e) { // do nothing } } @Test public void testParseObservableFindNextAfterCompleted() { List<ParseUser> users = Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class)); ParseQueryController queryController = mock(ParseQueryController.class); ParseCorePlugins.getInstance().registerQueryController(queryController); Task<List<ParseUser>> task = Task.forResult(users); when(queryController.findAsync( any(ParseQuery.State.class), any(ParseUser.class), any(Task.class)) ).thenReturn(task); //).thenThrow(IllegalStateException.class); ParseQuery<ParseUser> query = ParseQuery.getQuery(ParseUser.class); query.setUser(new ParseUser()); rx.parse2.ParseObservable.find(query) .test() .assertNoErrors() //.assertValue(users) .assertComplete(); try { ParseTaskUtils.wait(task); } catch (Exception e) { // do nothing } } @Test public void testBlockingFind() throws ParseException { ParseQueryController queryController = mock(ParseQueryController.class); ParseCorePlugins.getInstance().registerQueryController(queryController); Task<List<ParseUser>> task = Task.forResult(Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class))); when(queryController.findAsync(any(ParseQuery.State.class), any(ParseUser.class), any(Task.class))).thenReturn(task); ParseQuery<ParseUser> query = ParseQuery.getQuery(ParseUser.class); assertThat(query.find()).isEqualTo(rx.parse2.ParseObservable.find(query).toList().blockingGet()); } //@Test //public void testParseObservablePinList() { //} @Test public void testParseObservableSave() { ParseObjectController controller = mock(ParseObjectController.class); ParseCorePlugins.getInstance().registerObjectController(controller); when(controller.saveAsync( any(ParseObject.State.class), any(ParseOperationSet.class), any(String.class), any(ParseDecoder.class)) ).thenReturn(Task.<ParseObject.State>forResult(mock(ParseObject.State.class))); rx.parse2.ParseObservable.save(mock(ParseUser.class)) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSaveAll() { List<ParseUser> users = Arrays.asList(mock(ParseUser.class), mock(ParseUser.class), mock(ParseUser.class)); ParseObjectController controller = mock(ParseObjectController.class); ParseCorePlugins.getInstance().registerObjectController(controller); when(controller.saveAllAsync( any(List.class), any(List.class), any(String.class), any(List.class))) //.thenReturn(Task.<List<ParseObject.State>>forResult(Arrays.asList(mock(ParseObject.State.class), mock(ParseObject.State.class), mock(ParseObject.State.class)))); .thenReturn(Arrays.asList(mock(ParseObject.State.class), mock(ParseObject.State.class), mock(ParseObject.State.class))); rx.parse2.ParseObservable.save(users) .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableUnsubscribe() { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); ParseCorePlugins.getInstance().registerPushChannelsController(controller); when(controller.subscribeInBackground(any(String.class))) .thenReturn(Task.forResult(null)); rx.parse2.ParseObservable.subscribe("hello") .test() .assertNoErrors() .assertComplete(); } @Test public void testParseObservableSubscribe() { ParsePushChannelsController controller = mock(ParsePushChannelsController.class); ParseCorePlugins.getInstance().registerPushChannelsController(controller); when(controller.unsubscribeInBackground(any(String.class))) .thenReturn(Task.forResult(null)); rx.parse2.ParseObservable.unsubscribe("hello") .test() .assertNoErrors() .assertComplete(); } public static <T> Predicate<T> check(Consumer<T> consumer) { return t -> { consumer.accept(t); return true; }; } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2/src/main/java/rx/parse2/ParseObservable.java
rxparse2/src/main/java/rx/parse2/ParseObservable.java
/* * Copyright (C) 2015 8tory, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.parse2; import android.content.Intent; import com.parse.ParseAnalytics; import com.parse.ParseAnonymousUtils; import com.parse.ParseCloud; import com.parse.ParseConfig; import com.parse.ParseFile; import com.parse.ParseInstallation; import com.parse.ParseObject; import com.parse.ParsePush; import com.parse.ParseQuery; import com.parse.ParseUser; import com.parse.ProgressCallback; import org.json.JSONObject; import java.io.File; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.NonNull; import io.reactivex.schedulers.Schedulers; import rx.bolts2.RxTask; public class ParseObservable { @NonNull @CheckReturnValue public static <R extends ParseObject> Observable<R> find(@NonNull final ParseQuery<R> query) { return RxTask.observable(() -> query.findInBackground()) .flatMap(l -> Observable.fromIterable(l)); } @NonNull @CheckReturnValue public static <R extends ParseObject> Single<Integer> count(@NonNull final ParseQuery<R> query) { return RxTask.single(() -> query.countInBackground()); } @NonNull public static <R extends ParseObject> Completable pin(@NonNull final R object) { return RxTask.completable(() -> object.pinInBackground()); } @NonNull public static <R extends ParseObject> Completable pin(@NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.pinAllInBackground(objects)); } @NonNull public static <R extends ParseObject> Completable pin(@NonNull final String name, @NonNull final R object) { return RxTask.completable(() -> object.pinInBackground(name)); } @NonNull public static <R extends ParseObject> Completable pin(@NonNull final String name, @NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.pinAllInBackground(name, objects)); } @NonNull public static <R extends ParseObject> Completable unpin(@NonNull final R object) { return RxTask.completable(() -> object.unpinInBackground()); } @NonNull public static <R extends ParseObject> Completable unpin(@NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.unpinAllInBackground(objects)); } @NonNull public static <R extends ParseObject> Completable unpin(@NonNull final String name, @NonNull final R object) { return RxTask.completable(() -> object.unpinInBackground(name)); } @NonNull public static <R extends ParseObject> Completable unpin(@NonNull final String name, @NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.unpinAllInBackground(name, objects)); } @NonNull @CheckReturnValue public static <R extends ParseObject> Observable<R> all(@NonNull final ParseQuery<R> query) { return count(query).flatMapObservable(c -> all(query, c)); } /** * Limit 10000 by skip */ @NonNull @CheckReturnValue public static <R extends ParseObject> Observable<R> all(@NonNull final ParseQuery<R> query, int count) { final int limit = 1000; // limit limitation query.setSkip(0); query.setLimit(limit); Observable<R> find = find(query); for (int i = limit; i < count; i+= limit) { if (i >= 10000) break; // skip limitation query.setSkip(i); query.setLimit(limit); find.concatWith(find(query)); } return find.distinct(o -> o.getObjectId()); } @NonNull @CheckReturnValue public static <R extends ParseObject> Single<R> first(@NonNull final ParseQuery<R> query) { return RxTask.single(() -> query.getFirstInBackground()); } @NonNull @CheckReturnValue public static <R extends ParseObject> Single<R> get(@NonNull final Class<R> clazz, @NonNull final String objectId) { return get(ParseQuery.getQuery(clazz), objectId); } @NonNull @CheckReturnValue public static <R extends ParseObject> Single<R> get(@NonNull final ParseQuery<R> query, @NonNull final String objectId) { return RxTask.single(() -> query.getInBackground(objectId)); } // Task<T> nullable? @NonNull @CheckReturnValue public static <R> Observable<R> callFunction(@NonNull final String name, @NonNull final Map<String, ?> params) { return RxTask.observable(() -> ParseCloud.callFunctionInBackground(name, params)); } @NonNull public static <R extends ParseObject> Completable save(@NonNull final R object) { return RxTask.completable(() -> object.saveInBackground()); } @NonNull public static <R extends ParseObject> Completable save(@NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.saveAllInBackground(objects)); } @NonNull public static <R extends ParseObject> Completable saveEventually(@NonNull final R object) { return RxTask.completable(() -> object.saveEventually()); } // Task<T> nullable? @NonNull @CheckReturnValue public static <R extends ParseObject> Single<R> fetch(@NonNull final R object) { return RxTask.single(() -> object.fetchInBackground()); } // Task<List<T>> nullable? @NonNull @CheckReturnValue public static <R extends ParseObject> Observable<R> fetch(@NonNull final List<R> objects) { return RxTask.observable(() -> ParseObject.fetchAllInBackground(objects)) .flatMap(l -> Observable.fromIterable(l)); } // Task<T> nullable? @NonNull @CheckReturnValue public static <R extends ParseObject> Single<R> fetchIfNeeded(@NonNull final R object) { return RxTask.single(() -> object.fetchIfNeededInBackground()); } // Task<List<T>> nullable? @NonNull @CheckReturnValue public static <R extends ParseObject> Observable<R> fetchIfNeeded(@NonNull final List<R> objects) { return RxTask.observable(() -> ParseObject.fetchAllIfNeededInBackground(objects)) .flatMap(l -> Observable.fromIterable(l)); } @NonNull public static <R extends ParseObject> Completable delete(@NonNull final R object) { return RxTask.completable(() -> object.deleteInBackground()); } @NonNull public static <R extends ParseObject> Completable delete(@NonNull final List<R> objects) { return RxTask.completable(() -> ParseObject.deleteAllInBackground(objects)); } /* ParsePush */ @NonNull public static Completable subscribe(@NonNull final String channel) { return RxTask.completable(() -> ParsePush.subscribeInBackground(channel)); } @NonNull public static Completable unsubscribe(@NonNull final String channel) { return RxTask.completable(() -> ParsePush.unsubscribeInBackground(channel)); } @NonNull public static Completable send(@NonNull final ParsePush push) { return RxTask.completable(() -> push.sendInBackground()); } @NonNull public static Completable send(@NonNull final JSONObject data, @NonNull final ParseQuery<ParseInstallation> query) { return RxTask.completable(() -> ParsePush.sendDataInBackground(data, query)); } @NonNull public static Completable send(@NonNull final String message, @NonNull final ParseQuery<ParseInstallation> query) { return RxTask.completable(() -> ParsePush.sendMessageInBackground(message, query)); } /* ParseObject */ // TODO refresh() // TODO fetchFromLocalDatastore() /* ParseUser */ @NonNull @CheckReturnValue public static Single<ParseUser> become(@NonNull final String sessionToken) { return RxTask.single(() -> ParseUser.becomeInBackground(sessionToken)); } // TODO enableRevocableSessionInBackground @NonNull @CheckReturnValue public static Single<ParseUser> logIn(@NonNull final String username, @NonNull final String password) { return RxTask.single(() -> ParseUser.logInInBackground(username, password)); } @NonNull public static Completable logOut() { return RxTask.completable(() -> ParseUser.logOutInBackground()); } @NonNull @CheckReturnValue public static Single<ParseUser> anonymousLogIn() { return RxTask.single(() -> ParseAnonymousUtils.logInInBackground()); } /* ParseObservable.Anonymous.logIn() public static class Anonymous { public static Observable<ParseUser> logIn() { return TaskObservable.defer(() -> ParseAnonymousUtils.logInInBackground()); } } */ @NonNull @CheckReturnValue public static Single<ParseUser> logInWith(@NonNull final String authType, @NonNull final Map<String, String> authData) { return RxTask.single(() -> ParseUser.logInWithInBackground(authType, authData)); } @NonNull public static Completable linkWith(@NonNull final ParseUser user, @NonNull final String authType, @NonNull final Map<String, String> authData) { return RxTask.completable(() -> user.linkWithInBackground(authType, authData)); } // TODO unlinkFromInBackground(String authType) @NonNull public static Completable resetPassword(@NonNull final String email) { return RxTask.completable(() -> ParseUser.requestPasswordResetInBackground(email)); } @NonNull public static Completable signUp(@NonNull final ParseUser user) { return RxTask.completable(() -> user.signUpInBackground()); } // ParseAnalytics @NonNull public static Completable trackAppOpened(@NonNull final Intent intent) { return RxTask.completable(() -> ParseAnalytics.trackAppOpenedInBackground(intent)); } @NonNull public static Completable trackEvent(@NonNull final String name) { return RxTask.completable(() -> ParseAnalytics.trackEventInBackground(name)); } @NonNull public static Completable trackEvent(@NonNull final String name, @NonNull final Map<String,String> dimensions) { return RxTask.completable(() -> ParseAnalytics.trackEventInBackground(name, dimensions)); } /* ParseFile */ @NonNull @CheckReturnValue public static Single<byte[]> getData(@NonNull final ParseFile file) { return RxTask.single(() -> file.getDataInBackground()); } @NonNull @CheckReturnValue public static Single<byte[]> getData(@NonNull final ParseFile file, @NonNull final ProgressCallback progressCallback) { return RxTask.single(() -> file.getDataInBackground(progressCallback)); } @NonNull @CheckReturnValue public static Single<InputStream> getDataStream(@NonNull final ParseFile file) { return RxTask.single(() -> file.getDataStreamInBackground()); } @NonNull @CheckReturnValue public static Single<InputStream> getDataStream(@NonNull final ParseFile file, @NonNull final ProgressCallback progressCallback) { return RxTask.single(() -> file.getDataStreamInBackground(progressCallback)); } @NonNull @CheckReturnValue public static Single<File> getFile(@NonNull final ParseFile file) { return RxTask.single(() -> file.getFileInBackground()); } @NonNull @CheckReturnValue public static Single<File> getFile(@NonNull final ParseFile file, @NonNull final ProgressCallback progressCallback) { return RxTask.single(() -> file.getFileInBackground(progressCallback)); } @NonNull public static Completable save(@NonNull final ParseFile file) { return RxTask.completable(() -> file.saveInBackground()); } @NonNull public static Completable save(@NonNull final ParseFile file, @NonNull final ProgressCallback uploadProgressCallback) { return RxTask.completable(() -> file.saveInBackground(uploadProgressCallback)); } @NonNull @CheckReturnValue public static Single<ParseConfig> getConfig() { return RxTask.single(() -> ParseConfig.getInBackground()); } /* private ParseObservable() { throw new UnsupportedOperationException(); } */ }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false