Here are the examples of the java api @org.springframework.context.annotation.Lazy taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1136 Examples
19
Source : AuthorizationServerConfig.java
with GNU Affero General Public License v3.0
from zycSummer
with GNU Affero General Public License v3.0
from zycSummer
@Primary
@Bean
@Lazy
public AuthorizationServerTokenServices yamiTokenServices() {
YamiTokenServices tokenServices = new YamiTokenServices();
tokenServices.setTokenStore(tokenStore());
// 支持刷新token
tokenServices.setSupportRefreshToken(true);
tokenServices.setReuseRefreshToken(true);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
addUserDetailsService(tokenServices);
return tokenServices;
}
19
Source : DefaultWebMvcConfig.java
with Apache License 2.0
from zlt2000
with Apache License 2.0
from zlt2000
/**
* 默认SpringMVC拦截器
*
* @author zlt
* @date 2019/8/5
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public clreplaced DefaultWebMvcConfig implements WebMvcConfigurer {
@Lazy
@Autowired
private UserService userService;
/**
* Token参数解析
*
* @param argumentResolvers 解析类
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// 注入用户信息
argumentResolvers.add(new TokenArgumentResolver(userService));
// 注入应用信息
argumentResolvers.add(new ClientArgumentResolver());
}
}
19
Source : GenTableService.java
with GNU Affero General Public License v3.0
from zhouhuan751312
with GNU Affero General Public License v3.0
from zhouhuan751312
/**
* @time 2020/1/6 15:23
* @version V1.0
*/
@Slf4j
@Service
public clreplaced GenTableService extends ServiceImpl<GenTableMapper, GenTableEnreplacedy> {
@Autowired
private GenTableColumnService genTableColumnService;
@Lazy
@Resource
private GenTableService genTableService;
@Resource
private GenTableMapper genTableMapper;
@Resource
private SysDatabaseMapper sysDatabaseMapper;
public PageUtil findPage(Map<String, Object> params) {
String tableName = (String) params.get("tableName");
String tableComment = (String) params.get("tableComment");
Page<GenTableEnreplacedy> page = this.baseMapper.selectPage(new Query<GenTableEnreplacedy>(params).getPage(), new QueryWrapper<GenTableEnreplacedy>().like(StringUtils.isNotBlank(tableName), "table_name", tableName).like(StringUtils.isNotBlank(tableComment), "table_comment", tableComment));
return new PageUtil(page);
}
public byte[] generatorCode(String[] tableNames) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
generatorCode(tableName, zip);
}
IoUtil.close(zip);
return outputStream.toByteArray();
}
public byte[] generatorCode(String tableName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IoUtil.close(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(String tableName, ZipOutputStream zip) {
// 查询表信息
GenTableEnreplacedy table = findGenTableByName(tableName);
// 查询列信息
List<GenTableColumnEnreplacedy> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTarget());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
try {
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
String temp = StrUtil.replace(sw.toString(), "<@>", "#");
temp = StrUtil.replace(temp, "<$>", "$");
IOUtils.write(temp, zip, CharsetUtil.UTF_8);
IoUtil.close(sw);
zip.closeEntry();
} catch (IOException e) {
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}
/**
* 设置主键列信息
*
* @param table 业务表信息
* @param columns 业务字段列表
*/
public void setPkColumn(GenTableEnreplacedy table, List<GenTableColumnEnreplacedy> columns) {
for (GenTableColumnEnreplacedy column : columns) {
if (column.isPk()) {
table.setPkColumn(column);
break;
}
}
if (ToolUtil.isEmpty(table.getPkColumn())) {
table.setPkColumn(columns.get(0));
}
}
public boolean genCode(Long tableId) {
// 查询表信息
GenTableEnreplacedy table = findGenTableById(tableId);
String path = table.getRunPath().equals("/") ? Global.getConifgFile() : table.getRunPath();
// 查询列信息
List<GenTableColumnEnreplacedy> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTarget());
if (table.getIsCover().equals("N")) {
for (String template : templates) {
if (!template.contains("sql.vm")) {
String p = path + VelocityUtils.getFileName(template, table);
if (FileUtil.exist(p)) {
throw new RxcException(new File(p).getName() + "文件存在", "99992");
}
}
}
}
for (String template : templates) {
if (!template.contains("sql.vm")) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
try {
String p = path + VelocityUtils.getFileName(template, table);
String temp = StrUtil.replace(sw.toString(), "<@>", "#");
temp = StrUtil.replace(temp, "<$>", "$");
FileUtil.writeString(temp, p, CharsetUtil.UTF_8);
} catch (IORuntimeException e) {
throw new RxcException("文件生成失败", "99991");
}
}
}
// 删除无用生成的文件
List<String> allTemplates = VelocityUtils.allTemplateList(table.getTarget());
allTemplates.removeAll(templates);
for (String template : allTemplates) {
String p = path + VelocityUtils.getFileName(template, table);
FileUtil.del(p);
}
return true;
}
/**
* @replacedle: findGenTableById
* @Description: 已经获取了表的 columns
* @param id
* @return GenTableEnreplacedy
* @author [email protected]
* @Date: 2020年6月2日
*/
public GenTableEnreplacedy findGenTableById(Long id) {
GenTableEnreplacedy table = genTableMapper.findByTableId(id);
if (StringUtils.isNotBlank(table.getOptions())) {
try {
table.setOption(JSONObject.parseObject(table.getOptions(), Option.clreplaced));
} catch (Exception e) {
throw new RxcException("树相关编码解析失败");
}
}
table.setColumns(genTableColumnService.findListByTableId(id));
return table;
}
public GenTableEnreplacedy findGenTableByName(String tableName) {
GenTableEnreplacedy table = genTableMapper.findByName(tableName);
if (StringUtils.isNotBlank(table.getOptions())) {
try {
table.setOption(JSONObject.parseObject(table.getOptions(), Option.clreplaced));
} catch (Exception e) {
throw new RxcException("树相关编码解析失败");
}
}
table.setColumns(genTableColumnService.findListByTableId(table.getId()));
return table;
}
public GenTableEnreplacedy findGenTableMenuById(Long id) {
return this.genTableMapper.findGenTableMenuById(id);
}
public void validateEdit(GenTableEnreplacedy genTable) {
if (genTable.isTree()) {
if (null == genTable.getOption()) {
throw new RxcException("树相关设定字段不能为空");
}
if (StringUtils.isEmpty(genTable.getOption().getTreeCode())) {
throw new RxcException("树编码字段不能为空");
} else if (StringUtils.isEmpty(genTable.getOption().getTreeParentCode())) {
throw new RxcException("树父编码字段不能为空");
} else if (StringUtils.isEmpty(genTable.getOption().getTreeName())) {
throw new RxcException("树名称字段不能为空");
}
}
}
public boolean update(GenTableEnreplacedy genTable) {
// 其它扩展设置
if (null != genTable.getOption()) {
genTable.setOptions(JSONObject.toJSONString(genTable.getOption()));
}
int row = this.genTableMapper.updateGenTable(genTable);
if (row > 0) {
for (GenTableColumnEnreplacedy cenTableColumn : genTable.getColumns()) {
genTableColumnService.updateGenTableColumn(cenTableColumn);
}
return true;
}
return false;
}
@Transactional
public void importGenTable(List<GenTableEnreplacedy> tableList, String operName, String dbName) {
for (GenTableEnreplacedy table : tableList) {
try {
String tableName = table.getTableName();
GenUtils.initTable(table, operName);
table.setDbName(dbName);
boolean row = this.save(table);
if (row) {
// 保存列信息
// List<GenTableColumnEnreplacedy> genTableColumns = genTableColumnService.selectDbTableColumnsByName(dbName,tableName);
List<GenTableColumnEnreplacedy> genTableColumns = genTableColumnService.generateDbTableColumnsByName(dbName, tableName);
for (GenTableColumnEnreplacedy column : genTableColumns) {
GenUtils.initColumnField(column, table);
// 如果comment为空 设置comment 为JavaField
if (StringUtils.isBlank(column.getColumnComment())) {
column.setColumnComment(column.getJavaField());
}
genTableColumnService.save(column);
}
}
} catch (Exception e) {
log.error("表名 " + table.getTableName() + " 导入失败:", e);
}
}
}
public void importGenTable(List<GenTableEnreplacedy> tableList, String operName, SysDatabaseEnreplacedy db) {
for (GenTableEnreplacedy table : tableList) {
try {
String tableName = table.getTableName();
GenUtils.initTable(table, operName);
boolean row = this.save(table);
if (row) {
// 保存列信息
List<GenTableColumnEnreplacedy> genTableColumns = genTableColumnService.generateDbTableColumnsByName(db.getDbType(), db.getSchema(), tableName);
for (GenTableColumnEnreplacedy column : genTableColumns) {
GenUtils.initColumnField(column, table);
// 如果comment为空 设置comment 为JavaField
if (StringUtils.isBlank(column.getColumnComment())) {
column.setColumnComment(column.getJavaField());
}
genTableColumnService.save(column);
}
}
} catch (Exception e) {
log.error("表名 " + table.getTableName() + " 导入失败:", e);
}
}
}
public boolean deleteGenTableByIds(Long[] ids) {
return this.genTableMapper.deleteGenTableByIds(ids) > 0 && genTableColumnService.deleteGenTableColumnByIds(ids) > 0;
}
public Map<String, String> previewCode(Long tableId) {
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
// GenTableEnreplacedy table = this.genTableMapper.findGenTableById(tableId);
GenTableEnreplacedy table = genTableService.findGenTableById(tableId);
// 查询列信息
// table.setColumns(columns);
List<GenTableColumnEnreplacedy> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory(), table.getTarget());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
String temp = StrUtil.replace(sw.toString(), "<@>", "#");
temp = StrUtil.replace(temp, "<$>", "$");
dataMap.put(template, temp);
}
return dataMap;
}
/**
* @replacedle: generateDbTableList
* @Description: 获取所有指定数据源的 部分表List
* @param db
* @param dbTableName
* @return List<GenTableEnreplacedy>
* @author [email protected]
* @Date: 2020年5月30日
*/
public List<GenTableEnreplacedy> generateDbTableList(SysDatabaseEnreplacedy db, String dbTableName, String dbTableComment) {
List<GenTableEnreplacedy> list = Lists.newArrayList();
String dbType = db.getDbType();
List<GenTableEnreplacedy> notList = this.list(new QueryWrapper<GenTableEnreplacedy>().eq("db_name", db.getDbName()));
List<String> names = null;
if (ToolUtil.isNotEmpty(notList)) {
names = notList.stream().map(GenTableEnreplacedy::getTableName).collect(Collectors.toList());
}
DataSourceContextHolder.setDataSourceType(db.getDbName());
try {
list = genTableMapper.generateTableList(dbType, db.getSchema(), dbTableName, dbTableComment, names);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceContextHolder.clearDataSourceType();
}
return list;
}
public List<GenTableEnreplacedy> generateDbTableList(SysDatabaseEnreplacedy db) {
List<GenTableEnreplacedy> list = Lists.newArrayList();
String dbType = db.getDbType();
List<GenTableEnreplacedy> notList = this.list(new QueryWrapper<GenTableEnreplacedy>().eq("db_name", db.getDbName()));
List<String> names = null;
if (ToolUtil.isNotEmpty(notList)) {
names = notList.stream().map(GenTableEnreplacedy::getTableName).collect(Collectors.toList());
}
if (!DataSourceContext.MASTER_DATASOURCE_NAME.equals(db.getDbName())) {
DataSourceContextHolder.setDataSourceType(db.getDbName());
list = genTableMapper.generateTableList(dbType, db.getSchema(), null, null, names);
DataSourceContextHolder.clearDataSourceType();
} else {
list = genTableMapper.generateTableList(dbType, db.getSchema(), null, null, names);
}
return list;
}
/**
* @replacedle: generateTablePage
* @Description: 根据数据源,获取表的相关信息表分页列表,
* @param params
* @return PageUtil
* @author [email protected]
* @Date: 2020年6月1日
*/
public PageUtil generateDbTablePage(Map<String, Object> params) {
String tableName = (String) params.get("tableName");
String tableComment = (String) params.get("tableComment");
String dbName = (String) params.get("dbName");
Page<GenTableEnreplacedy> page = new Query<GenTableEnreplacedy>(params).getPage();
List<GenTableEnreplacedy> list = Lists.newArrayList();
try {
SysDatabaseEnreplacedy db = sysDatabaseMapper.getByName(dbName);
String dbType = db.getDbType();
String schema = db.getSchema();
List<GenTableEnreplacedy> notList = this.list(new QueryWrapper<GenTableEnreplacedy>().eq("db_name", dbName));
List<String> names = null;
if (ToolUtil.isNotEmpty(notList)) {
names = notList.stream().map(GenTableEnreplacedy::getTableName).collect(Collectors.toList());
}
if (!DataSourceContext.MASTER_DATASOURCE_NAME.equals(dbName)) {
// 指定数据源
DataSourceContextHolder.setDataSourceType(db.getDbName());
list = genTableMapper.generateTablePage(page, dbType, schema, tableName, tableComment, names);
} else {
list = genTableMapper.generateTablePage(page, dbType, schema, tableName, tableComment, names);
}
page.setRecords(list);
} catch (Exception e) {
e.printStackTrace();
}
DataSourceContextHolder.clearDataSourceType();
return new PageUtil(page);
}
/**
* @replacedle: generateDbTableListByNames
* @Description: 根据数据源,获取表的相关信息
* @param db
* @param tableNames
* @return List<GenTableEnreplacedy>
* @author [email protected]
* @Date: 2020年6月1日
*/
public List<GenTableEnreplacedy> generateDbTableListByNames(SysDatabaseEnreplacedy db, String[] tableNames) {
List<GenTableEnreplacedy> list = Lists.newArrayList();
DataSourceContextHolder.setDataSourceType(db.getDbName());
try {
list = genTableMapper.generateTableListByNames(db.getDbType(), db.getSchema(), tableNames);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceContextHolder.clearDataSourceType();
}
return list;
}
}
19
Source : BpmOaFormService.java
with GNU Affero General Public License v3.0
from zhouhuan751312
with GNU Affero General Public License v3.0
from zhouhuan751312
/**
* OA请假单Service接口
* @author: ZhouZhou
* @date 2020-04-20 22:19
*/
@Service
public clreplaced BpmOaFormService extends ServiceImpl<BpmOaFormMapper, BpmOaFormEnreplacedy> {
@Resource
private BpmOaFormMapper bpmOaFormMapper;
@Resource
@Lazy
private BpmOaFormService bpmOaFormService;
@Autowired
private FlowableProcessInstanceService flowableProcessInstanceService;
/**
* 页面分页查询
*/
public PageUtil findPage(Map<String, Object> params) {
QueryWrapper<BpmOaFormEnreplacedy> r = new QueryWrapper<BpmOaFormEnreplacedy>();
String userName = (String) params.get("userName");
r.like(ToolUtil.isNotEmpty(userName), "user_name", userName);
String roleName = (String) params.get("roleName");
r.like(ToolUtil.isNotEmpty(roleName), "role_name", roleName);
String leaveDays = (String) params.get("leaveDays");
r.eq(ToolUtil.isNotEmpty(leaveDays), "leave_days", leaveDays);
String leaveType = (String) params.get("leaveType");
r.eq(ToolUtil.isNotEmpty(leaveType), "leave_type", leaveType);
String status = (String) params.get("status");
r.eq(ToolUtil.isNotEmpty(status), "status", status);
Page<BpmOaFormEnreplacedy> page = this.baseMapper.selectPage(new Query<BpmOaFormEnreplacedy>(params).getPage(), r);
return new PageUtil(page);
}
/**
* 批量删除
*/
@Transactional(rollbackFor = Exception.clreplaced)
public boolean deleteBpmOaFormByIds(Long[] ids) {
return this.removeByIds(Arrays.asList(ids));
}
public boolean add(BpmOaFormEnreplacedy bpmOaForm) {
return this.save(bpmOaForm);
}
/**
* 单个删除
*/
public boolean deleteBpmOaFormById(Long id) {
return this.removeById(id);
}
/**
* 保存
*/
@Transactional(rollbackFor = Exception.clreplaced)
public ResponseData saveBpmOaForm(BpmOaFormEnreplacedy bpmOaForm) {
bpmOaForm.setId(IdUtil.fastSimpleUUID());
StartProcessInstanceEnreplacedy startProcessInstanceVo = new StartProcessInstanceEnreplacedy();
startProcessInstanceVo.setBusinessKey(bpmOaForm.getId());
startProcessInstanceVo.setCreator(String.valueOf(UserUtils.getUserId()));
startProcessInstanceVo.setCurrentUserCode(String.valueOf(UserUtils.getUserId()));
startProcessInstanceVo.setFormName(bpmOaForm.getFromName());
startProcessInstanceVo.setSystemSn("system");
startProcessInstanceVo.setProcessDefinitionKey(bpmOaForm.getModelKey());
Map<String, Object> variables = new HashMap<>();
variables.put("leaveDays", bpmOaForm.getLeaveDays());
startProcessInstanceVo.setVariables(variables);
ResponseData returnStart = flowableProcessInstanceService.startProcessInstanceByKey(startProcessInstanceVo);
if (returnStart.get("code").equals("00000")) {
bpmOaForm.setProcessInstanceId(((ProcessInstance) returnStart.get("data")).getProcessInstanceId());
return bpmOaFormService.add(bpmOaForm) ? ResponseData.success() : ResponseData.error("数据插入失败!");
} else {
return returnStart;
}
}
/**
* 修改根居ID
*/
public boolean updateBpmOaFormById(BpmOaFormEnreplacedy bpmOaForm) {
return this.updateById(bpmOaForm);
}
/**
* 根居ID获取对象
*/
public BpmOaFormEnreplacedy getBpmOaFormById(String id) {
return this.getById(id);
}
}
19
Source : MicrosoftDriveServiceBase.java
with MIT License
from zhaojun1998
with MIT License
from zhaojun1998
@Slf4j
public abstract clreplaced MicrosoftDriveServiceBase extends AbstractBaseFileService {
/**
* https://graph.microsoft.com/v1.0/drives/6e4cf6d2f7e15197/root:%2FData%2F%E5%B8%A6%E6%9C%89%E7%AC%A6%E5%8F%B7%E6%96%87%E4%BB%B6%E5%A4%B9%E6%B5%8B%E8%AF%95%2F%25100+%2520:/children
* https://graph.microsoft.com/v1.0/me/drive/root:%2FData%2F%E5%B8%A6%E6%9C%89%E7%AC%A6%E5%8F%B7%E6%96%87%E4%BB%B6%E5%A4%B9%E6%B5%8B%E8%AF%95%2F%25100+%2520:/children
*/
/**
* 获取根文件 API URI
*/
protected static final String DRIVER_ROOT_URL = "https://{graphEndPoint}/v1.0/{type}/drive/root/children";
/**
* 获取非根文件 API URI
*/
protected static final String DRIVER_ITEMS_URL = "https://{graphEndPoint}/v1.0/{type}/drive/root:{path}:/children";
/**
* 获取单文件 API URI
*/
protected static final String DRIVER_ITEM_URL = "https://{graphEndPoint}/v1.0/{type}/drive/root:{path}";
/**
* 根据 RefreshToken 获取 AccessToken API URI
*/
protected static final String AUTHENTICATE_URL = "https://{authenticateEndPoint}/common/oauth2/v2.0/token";
/**
* OneDrive 文件类型
*/
private static final String ONE_DRIVE_FILE_FLAG = "file";
@Resource
@Lazy
private RestTemplate oneDriveRestTemplate;
@Resource
private StorageConfigRepository storageConfigRepository;
@Resource
private StorageConfigService storageConfigService;
/**
* 根据 RefreshToken 刷新 AccessToken, 返回刷新后的 Token.
*
* @return 刷新后的 Token
*/
public OneDriveToken getRefreshToken() {
StorageConfig refreshStorageConfig = storageConfigRepository.findByDriveIdAndKey(driveId, StorageConfigConstant.REFRESH_TOKEN_KEY);
String param = "client_id=" + getClientId() + "&redirect_uri=" + getRedirectUri() + "&client_secret=" + getClientSecret() + "&refresh_token=" + refreshStorageConfig.getValue() + "&grant_type=refresh_token";
String fullAuthenticateUrl = AUTHENTICATE_URL.replace("{authenticateEndPoint}", getAuthenticateEndPoint());
HttpRequest post = HttpUtil.createPost(fullAuthenticateUrl);
post.body(param, "application/x-www-form-urlencoded");
HttpResponse response = post.execute();
return JSONObject.parseObject(response.body(), OneDriveToken.clreplaced);
}
/**
* OAuth2 协议中, 根据 code 换取 access_token 和 refresh_token.
*
* @param code
* 代码
*
* @return 获取的 Token 信息.
*/
public OneDriveToken getToken(String code) {
String param = "client_id=" + getClientId() + "&redirect_uri=" + getRedirectUri() + "&client_secret=" + getClientSecret() + "&code=" + code + "&scope=" + getScope() + "&grant_type=authorization_code";
String fullAuthenticateUrl = AUTHENTICATE_URL.replace("{authenticateEndPoint}", getAuthenticateEndPoint());
HttpRequest post = HttpUtil.createPost(fullAuthenticateUrl);
post.body(param, "application/x-www-form-urlencoded");
HttpResponse response = post.execute();
return JSONObject.parseObject(response.body(), OneDriveToken.clreplaced);
}
@Override
public List<FileItemDTO> fileList(String path) {
path = StringUtils.removeFirstSeparator(path);
String fullPath = StringUtils.getFullPath(basePath, path);
List<FileItemDTO> result = new ArrayList<>();
String nextLink = null;
do {
String requestUrl;
if (nextLink != null) {
nextLink = nextLink.replace("+", "%2B");
requestUrl = URLUtil.decode(nextLink);
} else if (ZFileConstant.PATH_SEPARATOR.equalsIgnoreCase(fullPath) || "".equalsIgnoreCase(fullPath)) {
requestUrl = DRIVER_ROOT_URL;
} else {
requestUrl = DRIVER_ITEMS_URL;
}
fullPath = StringUtils.removeLastSeparator(fullPath);
JSONObject root;
HttpHeaders headers = new HttpHeaders();
headers.set("driveId", driveId.toString());
HttpEnreplacedy<Object> enreplacedy = new HttpEnreplacedy<>(headers);
try {
root = oneDriveRestTemplate.exchange(requestUrl, HttpMethod.GET, enreplacedy, JSONObject.clreplaced, getGraphEndPoint(), getType(), fullPath).getBody();
} catch (HttpClientErrorException e) {
log.debug("调用 OneDrive 时出现了网络异常, 已尝试重新刷新 token 后再试.");
refreshOneDriveToken();
root = oneDriveRestTemplate.exchange(requestUrl, HttpMethod.GET, enreplacedy, JSONObject.clreplaced, getGraphEndPoint(), getType(), fullPath).getBody();
}
if (root == null) {
return Collections.emptyList();
}
nextLink = root.getString("@odata.nextLink");
JSONArray fileList = root.getJSONArray("value");
for (int i = 0; i < fileList.size(); i++) {
FileItemDTO fileItemDTO = new FileItemDTO();
JSONObject fileItem = fileList.getJSONObject(i);
fileItemDTO.setName(fileItem.getString("name"));
fileItemDTO.setSize(fileItem.getLong("size"));
fileItemDTO.setTime(fileItem.getDate("lastModifiedDateTime"));
if (fileItem.containsKey("file")) {
fileItemDTO.setUrl(fileItem.getString("@microsoft.graph.downloadUrl"));
fileItemDTO.setType(FileTypeEnum.FILE);
} else {
fileItemDTO.setType(FileTypeEnum.FOLDER);
}
fileItemDTO.setPath(path);
result.add(fileItemDTO);
}
} while (nextLink != null);
return result;
}
@Override
public FileItemDTO getFileItem(String path) {
String fullPath = StringUtils.getFullPath(basePath, path);
HttpHeaders headers = new HttpHeaders();
headers.set("driveId", driveId.toString());
HttpEnreplacedy<Object> enreplacedy = new HttpEnreplacedy<>(headers);
JSONObject fileItem;
try {
fileItem = oneDriveRestTemplate.exchange(DRIVER_ITEM_URL, HttpMethod.GET, enreplacedy, JSONObject.clreplaced, getGraphEndPoint(), getType(), fullPath).getBody();
} catch (HttpClientErrorException e) {
log.debug("调用 OneDrive 时出现了网络异常, 已尝试重新刷新 token 后再试.");
refreshOneDriveToken();
fileItem = oneDriveRestTemplate.exchange(DRIVER_ITEM_URL, HttpMethod.GET, enreplacedy, JSONObject.clreplaced, getGraphEndPoint(), getType(), fullPath).getBody();
}
if (fileItem == null) {
return null;
}
FileItemDTO fileItemDTO = new FileItemDTO();
fileItemDTO.setName(fileItem.getString("name"));
fileItemDTO.setSize(fileItem.getLong("size"));
fileItemDTO.setTime(fileItem.getDate("lastModifiedDateTime"));
if (fileItem.containsKey(ONE_DRIVE_FILE_FLAG)) {
fileItemDTO.setUrl(fileItem.getString("@microsoft.graph.downloadUrl"));
fileItemDTO.setType(FileTypeEnum.FILE);
} else {
fileItemDTO.setType(FileTypeEnum.FOLDER);
}
fileItemDTO.setPath(path);
return fileItemDTO;
}
/**
* 获取存储类型, 对于 OneDrive 或 SharePoint, 此地址会不同.
* @return Graph 连接点
*/
public abstract String getType();
/**
* 获取 GraphEndPoint, 对于不同版本的 OneDrive, 此地址会不同.
* @return Graph 连接点
*/
public abstract String getGraphEndPoint();
/**
* 获取 AuthenticateEndPoint, 对于不同版本的 OneDrive, 此地址会不同.
* @return Authenticate 连接点
*/
public abstract String getAuthenticateEndPoint();
/**
* 获取 Client ID.
* @return Client Id
*/
public abstract String getClientId();
/**
* 获取重定向地址.
* @return 重定向地址
*/
public abstract String getRedirectUri();
/**
* 获取 Client Secret 密钥.
* @return Client Secret 密钥.
*/
public abstract String getClientSecret();
/**
* 获取 API Scope.
* @return Scope
*/
public abstract String getScope();
/**
* 刷新当前存储器 AccessToken
*/
public void refreshOneDriveToken() {
OneDriveToken refreshToken = getRefreshToken();
if (refreshToken.getAccessToken() == null || refreshToken.getRefreshToken() == null) {
return;
}
StorageConfig accessTokenConfig = storageConfigService.findByDriveIdAndKey(driveId, StorageConfigConstant.ACCESS_TOKEN_KEY);
StorageConfig refreshTokenConfig = storageConfigService.findByDriveIdAndKey(driveId, StorageConfigConstant.REFRESH_TOKEN_KEY);
accessTokenConfig.setValue(refreshToken.getAccessToken());
refreshTokenConfig.setValue(refreshToken.getRefreshToken());
storageConfigService.updateStorageConfig(Arrays.asList(accessTokenConfig, refreshTokenConfig));
}
}
19
Source : AutoPoiDictConfig.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* 描述:AutoPoi Excel注解支持字典参数设置
* 举例: @Excel(name = "性别", width = 15, dicCode = "sex")
* 1、导出的时候会根据字典配置,把值1,2翻译成:男、女;
* 2、导入的时候,会把男、女翻译成1,2存进数据库;
*
* @Author:scott
* @since:2019-04-09
* @Version:1.0
*/
@Slf4j
@Service
public clreplaced AutoPoiDictConfig implements AutoPoiDictServiceI {
@Lazy
@Resource
private CommonAPI commonAPI;
/**
* 通过字典查询easypoi,所需字典文本
*
* @Author:scott
* @since:2019-04-09
* @return
*/
@Override
public String[] queryDict(String dicTable, String dicCode, String dicText) {
List<String> dictReplaces = new ArrayList<String>();
List<DictModel> dictList = null;
// step.1 如果没有字典表则使用系统字典表
if (oConvertUtils.isEmpty(dicTable)) {
dictList = commonAPI.queryDicreplacedemsByCode(dicCode);
} else {
try {
dicText = oConvertUtils.getString(dicText, dicCode);
dictList = commonAPI.queryTableDicreplacedemsByCode(dicTable, dicText, dicCode);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
for (DictModel t : dictList) {
if (t != null) {
dictReplaces.add(t.getText() + "_" + t.getValue());
}
}
if (dictReplaces != null && dictReplaces.size() != 0) {
log.info("---AutoPoi--Get_DB_Dict------" + dictReplaces.toString());
return dictReplaces.toArray(new String[dictReplaces.size()]);
}
return null;
}
}
19
Source : JdbcRepository.java
with Apache License 2.0
from yuanweiquan-007
with Apache License 2.0
from yuanweiquan-007
/**
* @author yuanweiquan
*/
public clreplaced JdbcRepository<E extends Enreplacedy> extends AbstractDefaultRepository<E, JdbcCommandParser> {
@Lazy
@Autowired
protected JdbcTemplate jdbcTemplate;
public JdbcRepository() {
this.commandParser = new JdbcCommandParser();
}
/**
* 如果要指定JdbcTemplate,可以通过此方法修改
*
* @param jdbcTemplate
*/
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
protected List<E> select(Select<E> select) {
ExecuteCommandMeta command = commandParser.parser(select);
if (StringUtils.isEmpty(command.getCommand())) {
throw new IllegalArgumentException("select语句解析异常");
}
try {
List<Map<String, Object>> data = this.jdbcTemplate.queryForList(command.getCommand(), command.getParames().toArray());
appendMappingIfNecessary(data, select.getMeta().getColumnMapping());
return EnreplacedyMapper.toEnreplacedyList(data, select.getMeta().getEnreplacedyClreplaced());
} catch (Exception ex) {
logger.info("查询异常", ex);
return new ArrayList<>();
}
}
@Override
protected Integer update(Update<E> update) {
ExecuteCommandMeta command = commandParser.parser(update);
if (StringUtils.isEmpty(command.getCommand())) {
throw new IllegalArgumentException("update语句解析异常");
}
return this.jdbcTemplate.update(command.getCommand(), command.getParames().toArray());
}
@Override
protected Integer insert(Insert<E> insert) {
ExecuteCommandMeta command = commandParser.parser(insert);
if (StringUtils.isEmpty(command.getCommand())) {
throw new IllegalArgumentException("insert语句解析异常");
}
if (CollectionUtils.isEmpty(insert.getValues())) {
throw new IllegalArgumentException("插入参数值为空");
}
if (insert.getValues().size() == 1) {
return singleInsert(command, insert.getValues().get(0));
} else {
return multipleInsert(command, insert.getValues());
}
}
/**
* 批量插入
*
* @param command
* @param values
* @return
*/
private Integer multipleInsert(ExecuteCommandMeta command, List<E> values) {
final List<Object> fields = command.getParames();
List<Map<String, Object>> attributes = values.stream().map(this::parserAttribute).collect(Collectors.toList());
return this.jdbcTemplate.batchUpdate(command.getCommand(), new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
Map<String, Object> attrbute = attributes.get(i);
for (int j = 0; j < fields.size(); j++) {
preparedStatement.setObject(j + 1, attrbute.get(String.valueOf(fields.get(j))));
}
}
@Override
public int getBatchSize() {
return attributes.size();
}
}).length;
}
/**
* 单个插入
*
* @param command
* @param enreplacedy
* @return
*/
private Integer singleInsert(ExecuteCommandMeta command, E enreplacedy) {
Map<String, Object> attribute = parserAttribute(enreplacedy);
final List<Object> fields = command.getParames();
return this.jdbcTemplate.update(command.getCommand(), new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement) throws SQLException {
for (int i = 0; i < fields.size(); i++) {
preparedStatement.setObject(i + 1, attribute.get(String.valueOf(fields.get(i))));
}
}
});
}
private Map<String, Object> parserAttribute(E enreplacedy) {
Map<String, Object> map = new HashMap<>(16);
if (!ObjectUtils.isEmpty(enreplacedy)) {
Field[] fields = enreplacedy.getClreplaced().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
map.put(FieldUtils.getFieldName(enreplacedy.getClreplaced(), field), field.get(enreplacedy));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return map;
}
@Override
protected Integer delete(Delete<E> delete) {
ExecuteCommandMeta command = commandParser.parser(delete);
if (StringUtils.isEmpty(command.getCommand())) {
throw new IllegalArgumentException("delete语句解析异常");
}
return this.jdbcTemplate.update(command.getCommand(), command.getParames().toArray());
}
@Override
protected Integer count(Count<E> count) {
ExecuteCommandMeta command = commandParser.parser(count);
if (StringUtils.isEmpty(command.getCommand())) {
throw new IllegalArgumentException("count语句解析异常");
}
return this.jdbcTemplate.queryForObject(command.getCommand(), command.getParames().toArray(), Integer.clreplaced);
}
}
19
Source : SundialInterceptor.java
with MIT License
from yizzuide
with MIT License
from yizzuide
/**
* SundialInterceptor
*
* @author yizzuide
* @since 3.8.0
* @version 3.9.0
* Create at 2020/06/16 11:18
*/
@Slf4j
@Intercepts({ @Signature(type = Executor.clreplaced, method = "update", args = { MappedStatement.clreplaced, Object.clreplaced }), @Signature(type = Executor.clreplaced, method = "query", args = { MappedStatement.clreplaced, Object.clreplaced, RowBounds.clreplaced, ResultHandler.clreplaced }), @Signature(type = Executor.clreplaced, method = "query", args = { MappedStatement.clreplaced, Object.clreplaced, RowBounds.clreplaced, ResultHandler.clreplaced, CacheKey.clreplaced, BoundSql.clreplaced }) })
public clreplaced SundialInterceptor implements Interceptor {
@Autowired
private SundialProperties props;
@Lazy
@Resource
private ShardingFunction shardingFunction;
private final Map<String, Map<String, Method>> cacheMap = new HashMap<>();
private static final Pattern WHITE_SPACE_BLOCK_PATTERN = Pattern.compile("([\\s]{2,}|[\\t\\r\\n])");
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
String methodId = ms.getId();
// 是否使用了分库分表策略
Sundial sundial = getMethod(methodId).getAnnotation(Sundial.clreplaced);
if (sundial == null || sundial.shardingType() == ShardingType.NONE) {
return invocation.proceed();
}
String nodeExp = sundial.nodeExp();
String partExp = sundial.partExp();
// 未设置节点拆分和表拆分,直接返回
if (StringUtils.isEmpty(nodeExp) && StringUtils.isEmpty(partExp)) {
return invocation.proceed();
}
// 没有可拆分的ShardingKey,直接返回
Object params = args.length > 1 ? args[1] : null;
if (params == null) {
return invocation.proceed();
}
BoundSql boundSql = ms.getSqlSource().getBoundSql(params);
String sql = WHITE_SPACE_BLOCK_PATTERN.matcher(boundSql.getSql()).replaceAll(" ");
String tableName = MybatisUtil.getFirstTableName(sql);
replacedert tableName != null;
ShardingRoot root = new ShardingRoot();
root.setTable(tableName);
root.setP(params);
root.setFn(shardingFunction);
String schema = null;
// 分库、分库分表
if (sundial.shardingType() != ShardingType.TABLE && !StringUtils.isEmpty(nodeExp)) {
String node = SimpleElParser.parse(nodeExp, root, String.clreplaced);
SundialProperties.DataNode dataNode = props.getSharding().getNodes().get(node);
if (dataNode == null) {
int separatorIndex = node.lastIndexOf(props.getSharding().getIndexSeparator());
String index = node.substring(separatorIndex + 1);
node = node.substring(0, separatorIndex) + props.getSharding().getIndexSeparator() + Integer.parseInt(index);
dataNode = props.getSharding().getNodes().get(node);
}
// 是否使用主连接
if (sundial.key().equals(DynamicRouteDataSource.MASTER_KEY)) {
SundialHolder.setDataSourceType(dataNode.getLeader());
} else {
// 暂时使用第一个从连接
SundialHolder.setDataSourceType(dataNode.getFollows().get(0));
}
// 需要添加的数据库名
if (!StringUtils.isEmpty(dataNode.getSchema())) {
schema = dataNode.getSchema();
}
// 如果仅为分库类型
if (sundial.shardingType() == ShardingType.SCHEMA) {
// sql不需要修改,直接返回
if (schema == null) {
return invocation.proceed();
}
// 加入数据库名
sql = sql.replace(tableName, schema + "." + tableName);
updateSql(sql, invocation, ms, args, boundSql);
return invocation.proceed();
}
}
// 分库分表 or 分表
if (!StringUtils.isEmpty(partExp)) {
String part = SimpleElParser.parse(partExp, root, String.clreplaced);
// 如果保留原表名,去掉0索引后缀
if (props.getSharding().isOriginalNameAsIndexZero()) {
int separatorIndex = part.lastIndexOf(props.getSharding().getIndexSeparator());
String index = part.substring(separatorIndex + 1);
if (Integer.parseInt(index) == 0) {
part = part.substring(0, separatorIndex);
}
}
// 如果sql不需要修改,直接返回
if (tableName.equals(part) && schema == null) {
return invocation.proceed();
}
sql = sql.replace(tableName, schema == null ? part : schema + "." + part);
updateSql(sql, invocation, ms, args, boundSql);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
// 为当前target创建动态代理
return Plugin.wrap(target, this);
}
return target;
}
private Method getMethod(String methodId) throws ClreplacedNotFoundException {
int partIndex = methodId.lastIndexOf('.');
String clreplacedName = methodId.substring(0, partIndex);
String methodName = methodId.substring(partIndex + 1);
cacheMap.computeIfAbsent(clreplacedName, k -> new HashMap<>());
Map<String, Method> methodMap = cacheMap.get(clreplacedName);
Method foundMethod = methodMap.get(methodName);
if (foundMethod != null) {
return foundMethod;
}
Clreplaced<?> clazz = Clreplaced.forName(clreplacedName);
Method method = null;
for (Method declaredMethod : clazz.getDeclaredMethods()) {
if (declaredMethod.getName().equals(methodName)) {
method = declaredMethod;
}
}
replacedert method != null;
methodMap.put(methodName, method);
return method;
}
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
// 替换映射的语句
args[0] = mappedStatement;
// 针对查询方式的参数替换
if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
Executor executor = (Executor) invocation.getTarget();
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
// 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
if (args.length == 6) {
args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
args[5] = boundSqlNew;
}
}
}
private MappedStatement copyFrom(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(org.apache.commons.lang3.StringUtils.join(ms.getKeyProperties(), ','));
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultOrdered(ms.isResultOrdered());
builder.resultSetType(ms.getResultSetType());
if (ms.getKeyColumns() != null && ms.getKeyColumns().length > 0) {
builder.keyColumn(org.apache.commons.lang3.StringUtils.join(ms.getKeyColumns(), ','));
}
builder.databaseId(ms.getDatabaseId());
builder.lang(ms.getLang());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
public static clreplaced BoundSqlSqlSource implements SqlSource {
private final BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
19
Source : GrpcServerAutoConfiguration.java
with MIT License
from yidongnan
with MIT License
from yidongnan
@Bean
@Lazy
AnnotationGlobalServerInterceptorConfigurer annotationGlobalServerInterceptorConfigurer(final ApplicationContext applicationContext) {
return new AnnotationGlobalServerInterceptorConfigurer(applicationContext);
}
19
Source : GrpcClientAutoConfiguration.java
with MIT License
from yidongnan
with MIT License
from yidongnan
/**
* Creates a new NameResolverRegistration. This ensures that the NameResolverProvider's get unregistered when spring
* shuts down. This is mostly required for tests/when running multiple application contexts within the same JVM.
*
* @param nameResolverProviders The spring managed providers to manage.
* @return The newly created NameResolverRegistration bean.
*/
@ConditionalOnMissingBean
@Lazy
@Bean
NameResolverRegistration grpcNameResolverRegistration(@Autowired(required = false) final List<NameResolverProvider> nameResolverProviders) {
final NameResolverRegistration nameResolverRegistration = new NameResolverRegistration(nameResolverProviders);
nameResolverRegistration.register(NameResolverRegistry.getDefaultRegistry());
return nameResolverRegistration;
}
19
Source : GrpcClientAutoConfiguration.java
with MIT License
from yidongnan
with MIT License
from yidongnan
@Bean
@Lazy
AnnotationGlobalClientInterceptorConfigurer annotationGlobalClientInterceptorConfigurer(final ApplicationContext applicationContext) {
return new AnnotationGlobalClientInterceptorConfigurer(applicationContext);
}
19
Source : ProxyFilter.java
with Apache License 2.0
from xm-online
with Apache License 2.0
from xm-online
@Lazy
@Autowired
public void setTokenStore(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
19
Source : InternalTransactionService.java
with Apache License 2.0
from xm-online
with Apache License 2.0
from xm-online
@Service
public clreplaced InternalTransactionService {
@Autowired
@Lazy
private InternalTransactionService self;
@SneakyThrows
public <T> T inNestedTransaction(Task<T> task, Runnable setupMethod) {
FutureTask<T> futureTask = new FutureTask<T>(() -> {
setupMethod.run();
return self.inTransaction(task);
});
Thread t = new Thread(futureTask);
t.start();
t.join();
return futureTask.get();
}
@Transactional
@SneakyThrows
public <T> T inTransaction(Task<T> task) {
return task.doWork();
}
public interface Task<T> {
T doWork() throws Exception;
}
}
19
Source : ElasticsearchIndexService.java
with Apache License 2.0
from xm-online
with Apache License 2.0
from xm-online
@Slf4j
@Service
public clreplaced ElasticsearchIndexService {
private static final Lock reindexLock = new ReentrantLock();
private static final int PAGE_SIZE = 100;
private static final String XM_ENreplacedY_FIELD_TYPEKEY = "typeKey";
private static final String XM_ENreplacedY_FIELD_ID = "id";
private final XmEnreplacedyRepositoryInternal xmEnreplacedyRepositoryInternal;
private final XmEnreplacedySearchRepository xmEnreplacedySearchRepository;
private final ElasticsearchTemplate elasticsearchTemplate;
private final TenantContextHolder tenantContextHolder;
private final MappingConfiguration mappingConfiguration;
private final IndexConfiguration indexConfiguration;
private final Executor executor;
@Setter(AccessLevel.PACKAGE)
@Resource
@Lazy
private ElasticsearchIndexService selfReference;
public ElasticsearchIndexService(XmEnreplacedyRepositoryInternal xmEnreplacedyRepositoryInternal, XmEnreplacedySearchRepository xmEnreplacedySearchRepository, ElasticsearchTemplate elasticsearchTemplate, TenantContextHolder tenantContextHolder, MappingConfiguration mappingConfiguration, IndexConfiguration indexConfiguration, @Qualifier("taskExecutor") Executor executor) {
this.xmEnreplacedyRepositoryInternal = xmEnreplacedyRepositoryInternal;
this.xmEnreplacedySearchRepository = xmEnreplacedySearchRepository;
this.elasticsearchTemplate = elasticsearchTemplate;
this.tenantContextHolder = tenantContextHolder;
this.mappingConfiguration = mappingConfiguration;
this.indexConfiguration = indexConfiguration;
this.executor = executor;
}
/**
* Recreates index and then reindexes ALL enreplacedies from database asynchronously.
* @return @{@link CompletableFuture<Long>} with a number of reindexed enreplacedies.
*/
@Timed
public CompletableFuture<Long> reindexAllAsync() {
TenantKey tenantKey = TenantContextUtils.getRequiredTenantKey(tenantContextHolder);
String rid = MdcUtils.getRid();
return CompletableFuture.supplyAsync(() -> execForCustomContext(tenantKey, rid, selfReference::reindexAll), executor);
}
/**
* Refreshes enreplacedies in elasticsearch index filtered by typeKey asynchronously.
*
* Does not recreate index.
* @param typeKey typeKey to filter source enreplacedies.
* @return @{@link CompletableFuture<Long>} with a number of reindexed enreplacedies.
*/
@Timed
public CompletableFuture<Long> reindexByTypeKeyAsync(@Nonnull String typeKey) {
Objects.requireNonNull(typeKey, "typeKey should not be null");
TenantKey tenantKey = TenantContextUtils.getRequiredTenantKey(tenantContextHolder);
String rid = MdcUtils.getRid();
return CompletableFuture.supplyAsync(() -> execForCustomContext(tenantKey, rid, () -> selfReference.reindexByTypeKey(typeKey)), executor);
}
/**
* Refreshes enreplacedies in elasticsearch index filtered by collection of IDs asynchronously.
*
* Does not recreate index.
* @param ids - collection of IDs of enreplacedies to be reindexed.
* @return @{@link CompletableFuture<Long>} with a number of reindexed enreplacedies.
*/
@Timed
public CompletableFuture<Long> reindexByIdsAsync(@Nonnull Iterable<Long> ids) {
Objects.requireNonNull(ids, "ids should not be null");
TenantKey tenantKey = TenantContextUtils.getRequiredTenantKey(tenantContextHolder);
String rid = MdcUtils.getRid();
return CompletableFuture.supplyAsync(() -> execForCustomContext(tenantKey, rid, () -> selfReference.reindexByIds(ids)), executor);
}
/**
* Recreates index and then reindexes ALL enreplacedies from database.
* @return number of reindexed enreplacedies.
*/
@Timed
@Transactional(readOnly = true)
public long reindexAll() {
long reindexed = 0L;
if (reindexLock.tryLock()) {
try {
recreateIndex();
reindexed = reindexXmEnreplacedy();
log.info("Elasticsearch: Successfully performed full reindexing");
} finally {
reindexLock.unlock();
}
} else {
log.info("Elasticsearch: concurrent reindexing attempt");
}
return reindexed;
}
/**
* Refreshes enreplacedies in elasticsearch index filtered by typeKey.
*
* Does not recreate index.
* @param typeKey typeKey to filter source enreplacedies.
* @return number of reindexed enreplacedies.
*/
@Timed
@Transactional(readOnly = true)
public long reindexByTypeKey(@Nonnull String typeKey) {
Objects.requireNonNull(typeKey, "typeKey should not be null");
Specification<XmEnreplacedy> spec = Specification.where((root, query, cb) -> cb.equal(root.get(XM_ENreplacedY_FIELD_TYPEKEY), typeKey));
return reindexXmEnreplacedy(spec);
}
@Timed
@Transactional(readOnly = true)
public long reindexByTypeKey(@Nonnull String typeKey, Integer startFrom) {
Objects.requireNonNull(typeKey, "typeKey should not be null");
Specification spec = (Specification) (root, query, criteriaBuilder) -> {
query.orderBy(criteriaBuilder.desc(root.get("id")));
return criteriaBuilder.equal(root.get(XM_ENreplacedY_FIELD_TYPEKEY), typeKey);
};
return reindexXmEnreplacedy(spec, startFrom);
}
/**
* Refreshes enreplacedies in elasticsearch index filtered by collection of IDs.
*
* Does not recreate index.
* @param ids - collection of IDs of enreplacedies to be reindexed.
* @return number of reindexed enreplacedies.
*/
@Timed
@Transactional(readOnly = true)
public long reindexByIds(@Nonnull Iterable<Long> ids) {
Objects.requireNonNull(ids, "ids should not be null");
Specification<XmEnreplacedy> spec = Specification.where((root, query, cb) -> {
CriteriaBuilder.In<Long> in = cb.in(root.get(XM_ENreplacedY_FIELD_ID));
ids.forEach(in::value);
return in;
});
return reindexXmEnreplacedy(spec);
}
private Long reindexXmEnreplacedy() {
return reindexXmEnreplacedy(null);
}
private long reindexXmEnreplacedy(@Nullable Specification<XmEnreplacedy> spec) {
return reindexXmEnreplacedy(spec, null);
}
private long reindexXmEnreplacedy(@Nullable Specification<XmEnreplacedy> spec, Integer startFrom) {
StopWatch stopWatch = StopWatch.createStarted();
startFrom = defaultIfNull(startFrom, 0);
final Clreplaced<XmEnreplacedy> clazz = XmEnreplacedy.clreplaced;
long reindexed = 0L;
if (xmEnreplacedyRepositoryInternal.count(spec) > 0) {
List<Method> relationshipGetters = Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.getType().equals(Set.clreplaced)).filter(field -> field.getAnnotation(OneToMany.clreplaced) != null).filter(field -> field.getAnnotation(JsonIgnore.clreplaced) == null).map(field -> extractFieldGetter(clazz, field)).filter(Objects::nonNull).collect(Collectors.toList());
for (int i = startFrom; i <= xmEnreplacedyRepositoryInternal.count(spec) / PAGE_SIZE; i++) {
Pageable page = PageRequest.of(i, PAGE_SIZE);
log.info("Indexing page {} of {}, pageSize {}", i, xmEnreplacedyRepositoryInternal.count(spec) / PAGE_SIZE, PAGE_SIZE);
Page<XmEnreplacedy> results = xmEnreplacedyRepositoryInternal.findAll(spec, page);
results.map(enreplacedy -> loadEnreplacedyRelationships(relationshipGetters, enreplacedy));
xmEnreplacedySearchRepository.saveAll(results.getContent());
reindexed += results.getContent().size();
}
}
log.info("Elasticsearch: Indexed [{}] rows for {} in {} ms", reindexed, clazz.getSimpleName(), stopWatch.getTime());
return reindexed;
}
private void recreateIndex() {
final Clreplaced<XmEnreplacedy> clazz = XmEnreplacedy.clreplaced;
StopWatch stopWatch = StopWatch.createStarted();
elasticsearchTemplate.deleteIndex(clazz);
try {
if (indexConfiguration.isConfigExists()) {
elasticsearchTemplate.createIndex(clazz, indexConfiguration.getConfiguration());
} else {
elasticsearchTemplate.createIndex(clazz);
}
} catch (ResourceAlreadyExistsException e) {
log.info("Do nothing. Index was already concurrently recreated by some other service");
}
if (mappingConfiguration.isMappingExists()) {
elasticsearchTemplate.putMapping(clazz, mappingConfiguration.getMapping());
} else {
elasticsearchTemplate.putMapping(clazz);
}
log.info("elasticsearch index was recreated for {} in {} ms", XmEnreplacedy.clreplaced.getSimpleName(), stopWatch.getTime());
}
private Method extractFieldGetter(final Clreplaced<XmEnreplacedy> clazz, final Field field) {
try {
return new PropertyDescriptor(field.getName(), clazz).getReadMethod();
} catch (IntrospectionException e) {
log.error("Error retrieving getter for clreplaced {}, field {}. Field will NOT be indexed", clazz.getSimpleName(), field.getName(), e);
return null;
}
}
private XmEnreplacedy loadEnreplacedyRelationships(final List<Method> relationshipGetters, final XmEnreplacedy enreplacedy) {
// if there are any relationships to load, do it now
relationshipGetters.forEach(method -> {
try {
// eagerly load the relationship set
((Set) method.invoke(enreplacedy)).size();
} catch (Exception ex) {
log.error("Error loading relationships for enreplacedy: {}, error: {}", enreplacedy, ex.getMessage());
}
});
return enreplacedy;
}
private Long execForCustomContext(TenantKey tenantKey, String rid, Supplier<Long> runnable) {
try {
MdcUtils.putRid(rid);
return tenantContextHolder.getPrivilegedContext().execute(TenantContextUtils.buildTenant(tenantKey), runnable);
} finally {
MdcUtils.removeRid();
}
}
}
19
Source : WechatRealm.java
with GNU General Public License v3.0
from xiaomujiayou
with GNU General Public License v3.0
from xiaomujiayou
/**
* 前台登录realm
*/
@Component
public clreplaced WechatRealm extends AuthorizingRealm {
@Autowired
@Lazy
private UserFeignClient userFeignClient;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授权");
// 从 principals获取主身份信息
// 将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),
SuUserEnreplacedy userEnreplacedy = (SuUserEnreplacedy) principals.getPrimaryPrincipal();
// 根据身份信息获取权限信息
List<RolePermissionEx> rolePermissionExMsg = userFeignClient.role(userEnreplacedy.getId());
List<RolePermissionEx> rolePermissionExs = rolePermissionExMsg;
List<String> permissions = new ArrayList<>();
for (RolePermissionEx rolePermissionEx : rolePermissionExs) {
for (SuPermissionEnreplacedy suPermissionEnreplacedy : rolePermissionEx.getSuPermissionEnreplacedies()) {
permissions.add(rolePermissionEx.getName() + ":" + suPermissionEnreplacedy.getName());
}
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addStringPermissions(permissions);
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("身份验证");
// 获取用户的输入的账号.
String openId = (String) token.getPrincipal();
GetUserInfoForm form = new GetUserInfoForm();
form.setOpenId(openId);
SuUserEnreplacedy userInfoMsg = userFeignClient.getUserInfo(form);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfoMsg, "", getName());
return authenticationInfo;
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof WeChatToken;
}
}
19
Source : ManageRealm.java
with GNU General Public License v3.0
from xiaomujiayou
with GNU General Public License v3.0
from xiaomujiayou
@Component
public clreplaced ManageRealm extends AuthorizingRealm {
@Autowired
@Lazy
private UserFeignClient userFeignClient;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
ManageToken manageToken = (ManageToken) token;
AdminLoginForm adminLoginForm = new AdminLoginForm();
adminLoginForm.setUserName(manageToken.getUsername());
adminLoginForm.setPreplacedword(String.valueOf(manageToken.getPreplacedword()));
SuAdminVo suAdminVo = userFeignClient.adminInfo(adminLoginForm);
manageToken.setSuAdminVo(suAdminVo);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(manageToken, suAdminVo.getId() != null ? manageToken.getPreplacedword() : "", getName());
return authenticationInfo;
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof ManageToken;
}
}
19
Source : MgjSdkComponent.java
with GNU General Public License v3.0
from xiaomujiayou
with GNU General Public License v3.0
from xiaomujiayou
@Slf4j
@Component
public clreplaced MgjSdkComponent {
@Autowired
private MyMogujieClient myMogujieClient;
@Autowired
private MgreplacediConfig mgreplacediConfig;
@Lazy
@Autowired
private MgjSdkComponent mgjSdkComponent;
@Autowired
private ProfitService profitService;
public PageBean<SmProductEnreplacedy> getProductByCriteria(ProductCriteriaBo criteria) throws Exception {
PromInfoQueryBean promInfoQueryBean = new PromInfoQueryBean();
promInfoQueryBean.setKeyword(criteria.getKeyword());
promInfoQueryBean.setPageNo(criteria.getPageNum());
promInfoQueryBean.setPageSize(criteria.getPageSize());
promInfoQueryBean.setSortType(criteria.getOrderBy(PlatformTypeConstant.MGJ) == null ? null : Integer.valueOf(criteria.getOrderBy(PlatformTypeConstant.MGJ).toString()));
promInfoQueryBean.setHasCoupon(criteria.getHasCoupon());
MgjResponse<String> res = myMogujieClient.execute(new XiaoDianCpsdataPromItemGetRequest(promInfoQueryBean));
JSONObject json = JSON.parseObject(res.getResult().getData());
JSONArray goodsArrJson = json.getJSONArray("items");
return packageToPageBean(goodsArrJson.stream().map(o -> convertGoodsList(o)).collect(Collectors.toList()), json.getInteger("total"), json.getInteger("page"), json.getInteger("pageSize"));
}
private PageBean<SmProductEnreplacedy> packageToPageBean(List<SmProductEnreplacedy> list, Integer total, Integer pageNum, Integer pageSize) {
PageBean<SmProductEnreplacedy> pageBean = new PageBean<>(list);
pageBean.setTotal(total);
pageBean.setPageNum(pageNum);
pageBean.setPageSize(pageSize);
return pageBean;
}
private SmProductEnreplacedy convertGoodsList(Object goodsObj) {
JSONObject goodsJson = (JSONObject) goodsObj;
SmProductEnreplacedy smProductEnreplacedy = new SmProductEnreplacedy();
smProductEnreplacedy.setType(PlatformTypeConstant.MGJ);
smProductEnreplacedy.setGoodsId(goodsJson.getString("itemId"));
smProductEnreplacedy.setGoodsThumbnailUrl(goodsJson.getString("pictUrlForH5"));
smProductEnreplacedy.setName(goodsJson.getString("replacedle"));
smProductEnreplacedy.setOriginalPrice((int) (goodsJson.getFloat("zkPrice") * 100));
smProductEnreplacedy.setCouponPrice((int) (goodsJson.getFloat("couponAmount") * 100));
smProductEnreplacedy.setMallName(goodsJson.getJSONObject("shopInfo").getString("name"));
smProductEnreplacedy.setSalesTip(goodsJson.getString("biz30day"));
smProductEnreplacedy.setMallCps(0);
smProductEnreplacedy.setPromotionRate((int) (Float.valueOf(goodsJson.getString("commissionRate").replace("%", "")) * 100));
smProductEnreplacedy.setHasCoupon(goodsJson.getInteger("couponLeftCount") > 0 ? 1 : 0);
smProductEnreplacedy.setCashPrice(GoodsPriceUtil.type(PlatformTypeConstant.MGJ).calcProfit(smProductEnreplacedy).intValue());
smProductEnreplacedy.setCreateTime(new Date());
return smProductEnreplacedy;
}
public List<SmProductEnreplacedy> details(List<String> goodsIds) throws Exception {
List<SmProductEnreplacedy> list = goodsIds.stream().map(o -> {
try {
return mgjSdkComponent.detail(o, null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}).collect(Collectors.toList());
return CollUtil.removeNull(list);
}
// @Cacheable(value = "share.goods.detail.mgj",key = "#goodsId")
public SmProductEnreplacedy detail(String goodsId, String pid) throws Exception {
XiaoDianCpsdataItemGetRequest request = new XiaoDianCpsdataItemGetRequest("https://shop.mogujie.com/detail/" + goodsId);
MgjResponse<String> res = myMogujieClient.execute(request);
return convertDetail(JSON.parseObject(res.getResult().getData()));
}
private SmProductEnreplacedy convertDetail(JSONObject goodsJson) {
SmProductEnreplacedy smProductEnreplacedy = new SmProductEnreplacedy();
smProductEnreplacedy.setType(PlatformTypeConstant.MGJ);
smProductEnreplacedy.setGoodsId(goodsJson.getString("itemId"));
smProductEnreplacedy.setGoodsThumbnailUrl(goodsJson.getString("pictUrl"));
smProductEnreplacedy.setGoodsGalleryUrls(String.join(",", goodsJson.getString("pictUrl")));
smProductEnreplacedy.setName(goodsJson.getString("replacedle"));
smProductEnreplacedy.setDes(goodsJson.getString("extendDesc"));
smProductEnreplacedy.setOriginalPrice((int) (goodsJson.getFloat("zkPrice") * 100));
smProductEnreplacedy.setCouponPrice((int) (goodsJson.getFloat("couponAmount") * 100));
smProductEnreplacedy.setMallName(goodsJson.getJSONObject("shopInfo").getString("name"));
smProductEnreplacedy.setSalesTip(goodsJson.getString("biz30day"));
smProductEnreplacedy.setMallCps(0);
smProductEnreplacedy.setPromotionRate((int) (Float.valueOf(goodsJson.getString("commissionRate").replace("%", "")) * 100));
smProductEnreplacedy.setHasCoupon(goodsJson.getInteger("couponLeftCount") > 0 ? 1 : 0);
smProductEnreplacedy.setCashPrice(GoodsPriceUtil.type(PlatformTypeConstant.MGJ).calcProfit(smProductEnreplacedy).intValue());
smProductEnreplacedy.setServiceTags(String.join(",", goodsJson.getString("tag")));
smProductEnreplacedy.setCouponId(goodsJson.getString("promid"));
smProductEnreplacedy.setCreateTime(new Date());
return smProductEnreplacedy;
}
public SmProductSimpleVo basicDetail(Long goodsId) throws Exception {
return null;
}
public ShareLinkBo getShareLink(String customParams, String pId, String goodsId, String couponId) throws Exception {
WxCodeParamBean wxCodeParamBean = new WxCodeParamBean();
wxCodeParamBean.setUid(mgreplacediConfig.getUid());
wxCodeParamBean.sereplacedemId(goodsId);
wxCodeParamBean.setPromId(couponId);
wxCodeParamBean.setGenWxcode(false);
wxCodeParamBean.setGid(pId);
MgjRequest<XiaoDianCpsdataWxcodeGetResponse> mgjRequest = new XiaoDianCpsdataWxcodeGetRequest(wxCodeParamBean);
JSONObject shareBean = JSON.parseObject(myMogujieClient.execute(mgjRequest).getResult().getData());
ShareLinkBo shareLinkBo = new ShareLinkBo();
// shareLinkBo.setWePagePath(shareBean.getString("path") + "&feedback=" + customParams);
shareLinkBo.setWePagePath(shareBean.getString("path"));
shareLinkBo.setWeAppId(mgreplacediConfig.getWeAppId());
// 生成短链接
String url = "https://union.mogujie.com/jump?userid=" + mgreplacediConfig.getUid() + "&itemid=" + goodsId + "&promid=" + couponId + "&feedback=" + Base64.encode(customParams);
MgjRequest<XiaodianCpsdataUrlShortenResponse> shotReq = new XiaodianCpsdataUrlShortenRequest(url);
String shotUrl = myMogujieClient.execute(shotReq).getResult().getData();
shareLinkBo.setShotUrl(shotUrl);
return shareLinkBo;
}
public PageBean<SmProductEnreplacedyEx> convertSmProductEnreplacedyEx(Integer userId, PageBean<SmProductEnreplacedy> pageBean) {
List<SmProductEnreplacedyEx> list = profitService.calcProfit(pageBean.getList(), userId);
PageBean<SmProductEnreplacedyEx> productEnreplacedyExPageBean = new PageBean<>();
productEnreplacedyExPageBean.setList(list);
productEnreplacedyExPageBean.setPageNum(pageBean.getPageNum());
productEnreplacedyExPageBean.setPageSize(pageBean.getPageSize());
productEnreplacedyExPageBean.setTotal(pageBean.getTotal());
return productEnreplacedyExPageBean;
}
}
19
Source : BillPayServiceImpl.java
with GNU General Public License v3.0
from xiaomujiayou
with GNU General Public License v3.0
from xiaomujiayou
@Slf4j
@Service("billPayService")
public clreplaced BillPayServiceImpl implements BillPayService {
@Autowired
private ScBillPayMapper scBillPayMapper;
@Autowired
private ScBillPayMapperEx scBillPayMapperEx;
@Autowired
private ScWaitPayBillMapper scWaitPayBillMapper;
@Autowired
private RabbitTemplate rabbitTemplate;
@Lazy
@Autowired
private BillPayService billPayService;
@Autowired
private ProfitProperty profitProperty;
@Transactional(rollbackFor = Exception.clreplaced)
@Override
public void onEntPayResult(SpWxEntPayOrderInEnreplacedy spWxEntPayOrderInEnreplacedy) {
ScBillPayEnreplacedy scBillPayEnreplacedy = scBillPayMapper.selectByPrimaryKey(spWxEntPayOrderInEnreplacedy.getBillPayId());
if (scBillPayEnreplacedy == null || scBillPayEnreplacedy.getState() != 1)
return;
if (spWxEntPayOrderInEnreplacedy.getState() == 1) {
billPayService.onEntPaySucess(scBillPayEnreplacedy, spWxEntPayOrderInEnreplacedy);
} else {
billPayService.onEntPayFail(scBillPayEnreplacedy, spWxEntPayOrderInEnreplacedy);
}
}
/**
* 支付失败
* @param scBillPayEnreplacedy
* @param spWxEntPayOrderInEnreplacedy
*/
public void onEntPayFail(ScBillPayEnreplacedy scBillPayEnreplacedy, SpWxEntPayOrderInEnreplacedy spWxEntPayOrderInEnreplacedy) {
scBillPayEnreplacedy.setState(3);
scBillPayEnreplacedy.setFailReason(spWxEntPayOrderInEnreplacedy.getErrCodeDes());
updateScBillPay(scBillPayEnreplacedy, spWxEntPayOrderInEnreplacedy, 4);
}
/**
* 支付成功
* @param scBillPayEnreplacedy
* @param spWxEntPayOrderInEnreplacedy
*/
public void onEntPaySucess(ScBillPayEnreplacedy scBillPayEnreplacedy, SpWxEntPayOrderInEnreplacedy spWxEntPayOrderInEnreplacedy) {
scBillPayEnreplacedy.setState(2);
updateScBillPay(scBillPayEnreplacedy, spWxEntPayOrderInEnreplacedy, 3);
}
private void updateScBillPay(ScBillPayEnreplacedy scBillPayEnreplacedy, SpWxEntPayOrderInEnreplacedy spWxEntPayOrderInEnreplacedy, Integer waitPayBillState) {
scBillPayEnreplacedy.setUpdateTime(new Date());
scBillPayEnreplacedy.setProcessId(spWxEntPayOrderInEnreplacedy.getId());
scBillPayEnreplacedy.setProcessSn(spWxEntPayOrderInEnreplacedy.getPartnerTradeNo());
scBillPayEnreplacedy.setPaySysSn(spWxEntPayOrderInEnreplacedy.getPaymentNo());
scBillPayMapper.updateByPrimaryKeySelective(scBillPayEnreplacedy);
Example example = new Example(ScWaitPayBillEnreplacedy.clreplaced);
example.createCriteria().andIn("billId", CollUtil.newArrayList(scBillPayEnreplacedy.getBillIds().split(",")));
ScWaitPayBillEnreplacedy record = new ScWaitPayBillEnreplacedy();
record.setState(waitPayBillState);
scWaitPayBillMapper.updateByExampleSelective(record, example);
}
@Transactional(rollbackFor = Exception.clreplaced)
@Override
public List<ScBillPayEnreplacedy> genPayBill(String billPayName, Integer minMoney, Integer pageNum, Integer pageSize, Date timeline) {
List<ScBillPayEnreplacedy> scBillPayEnreplacedies = scBillPayMapperEx.genPayBill(minMoney, PageUtil.getStart(pageNum, pageSize), pageSize, timeline);
scBillPayEnreplacedies.stream().forEach(o -> {
List<String> billIds = CollUtil.newArrayList(o.getBillIds().split(","));
Example example = new Example(ScWaitPayBillEnreplacedy.clreplaced);
example.createCriteria().andIn("billId", billIds);
ScWaitPayBillEnreplacedy record = new ScWaitPayBillEnreplacedy();
record.setState(2);
scWaitPayBillMapper.updateByExampleSelective(record, example);
o.setState(1);
o.setName(billPayName);
o.setUpdateTime(new Date());
o.setCreateTime(o.getUpdateTime());
scBillPayMapper.insertUseGeneratedKeys(o);
});
return scBillPayEnreplacedies;
}
@Override
public void commission() {
// 发放截至日期
Date timeline = new Date();
// Date timeline = DateUtil.parse(DateUtil.today());
// 支付简介,会出现在微信支付页面上
String payDesc = profitProperty.getPayDesc().replace("{time}", DateUtil.format(timeline, "yyyy-MM-dd hh:mm"));
int total = scBillPayMapperEx.totalGenPayBill(profitProperty.getMinMoney(), timeline);
double count = Math.ceil(NumberUtil.div(total, profitProperty.getPageSize().intValue()));
for (int i = 0; i < count; i++) {
try {
billPayService.genPayBill(payDesc, profitProperty.getMinMoney(), i + 1, profitProperty.getPageSize(), timeline).stream().forEach(o -> {
EntPayMessage entPayMessage = new EntPayMessage();
entPayMessage.setDesc(payDesc);
entPayMessage.setIp(profitProperty.getIp());
entPayMessage.setScBillPayEnreplacedy(o);
rabbitTemplate.convertAndSend(PayMqConfig.EXCHANGE, PayMqConfig.KEY_WX_ENT_PAY, entPayMessage);
});
} catch (Exception e) {
log.error("返佣失败 {}", e);
}
}
}
@Override
public PageBean<ScBillPayVo> list(Integer userId, Integer pageNum, Integer pageSize) {
ScBillPayEnreplacedy record = new ScBillPayEnreplacedy();
record.setUserId(userId);
PageHelper.startPage(pageNum, pageSize);
OrderByHelper.orderBy("create_time desc");
List<ScBillPayEnreplacedy> scBillPayEnreplacedies = scBillPayMapper.select(record);
if (scBillPayEnreplacedies == null)
return null;
PageBean<ScBillPayEnreplacedy> scBillPayEnreplacedyPageBean = new PageBean<>(scBillPayEnreplacedies);
List<ScBillPayVo> scBillPayVos = scBillPayEnreplacedies.stream().map(o -> {
ScBillPayVo scBillPayVo = new ScBillPayVo();
BeanUtil.copyProperties(o, scBillPayVo);
// scBillPayVo.setName("发放佣金");
if (o.getState() == 3)
return null;
// scBillPayVo.setFailReason("系统出错,请稍后。。");
return scBillPayVo;
}).collect(Collectors.toList());
scBillPayVos = CollUtil.removeNull(scBillPayVos);
PageBean<ScBillPayVo> payVoPageBean = new PageBean<>(scBillPayVos);
payVoPageBean.setPageNum(scBillPayEnreplacedyPageBean.getPageNum());
payVoPageBean.setPageSize(scBillPayEnreplacedyPageBean.getPageSize());
payVoPageBean.setTotal(scBillPayEnreplacedyPageBean.getTotal());
return payVoPageBean;
}
}
19
Source : WechatRealm.java
with GNU General Public License v3.0
from xiaomujiayou
with GNU General Public License v3.0
from xiaomujiayou
/**
* 微信登录
*/
@Component
public clreplaced WechatRealm extends AuthorizingRealm {
@Autowired
@Lazy
private UserController userController;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授权");
// 从 principals获取主身份信息
// 将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),
SuUserEnreplacedy userEnreplacedy = (SuUserEnreplacedy) principals.getPrimaryPrincipal();
// 根据身份信息获取权限信息
List<RolePermissionEx> rolePermissionExMsg = userController.role(userEnreplacedy.getId());
List<RolePermissionEx> rolePermissionExs = rolePermissionExMsg;
List<String> permissions = new ArrayList<>();
for (RolePermissionEx rolePermissionEx : rolePermissionExs) {
for (SuPermissionEnreplacedy suPermissionEnreplacedy : rolePermissionEx.getSuPermissionEnreplacedies()) {
permissions.add(rolePermissionEx.getName() + ":" + suPermissionEnreplacedy.getName());
}
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addStringPermissions(permissions);
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("身份验证");
// 获取用户的输入的账号.
String openId = (String) token.getPrincipal();
GetUserInfoForm form = new GetUserInfoForm();
form.setOpenId(openId);
SuUserEnreplacedy userInfoMsg = userController.info(form);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfoMsg, "", getName());
return authenticationInfo;
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof WeChatToken;
}
}
19
Source : MvcConfig.java
with Apache License 2.0
from xiangxik
with Apache License 2.0
from xiangxik
@Lazy
@Bean
public QuerydslBindingsFactory querydslBindingsFactory() {
QuerydslBindingsFactory querydslBindingsFactory = new QuerydslBindingsFactory(SimpleEnreplacedyPathResolver.INSTANCE);
querydslBindingsFactory.setApplicationContext(applicationContext);
return querydslBindingsFactory;
}
19
Source : DataSourceConfig.java
with Apache License 2.0
from x-ream
with Apache License 2.0
from x-ream
@Lazy
@Bean("dataSource")
@ConfigurationProperties("spring.datasource")
public DataSource dataSource() {
DataSource dataSource = DataSourceBuilder.create().build();
// return new io.seata.rm.datasource.DataSourceProxy(dataSource);
return dataSource;
}
19
Source : DataSourceConfig.java
with Apache License 2.0
from x-ream
with Apache License 2.0
from x-ream
@Lazy
@Bean("routingDataSource")
@Primary
public AbstractRoutingDataSource routingDataSource(@Qualifier("dataSource") DataSource dataSource, @Qualifier("readDataSource") DataSource readDataSource) {
AbstractRoutingDataSource proxy = new AbstractRoutingDataSource() {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.get();
}
};
Map<Object, Object> map = new HashMap<>();
map.put(DataSourceType.READ, readDataSource);
map.put(DataSourceType.WRITE, dataSource);
proxy.setTargetDataSources(map);
proxy.setDefaultTargetDataSource(dataSource);
return proxy;
}
19
Source : CustomAuthorizationServerConfigurer.java
with MIT License
from wells2333
with MIT License
from wells2333
@Bean
@Lazy
public WebResponseExceptionTranslator<OAuth2Exception> webResponseExceptionTranslator() {
return new DefaultWebResponseExceptionTranslator() {
@Override
public ResponseEnreplacedy<OAuth2Exception> translate(Exception e) throws Exception {
if (e instanceof OAuth2Exception) {
OAuth2Exception exception = (OAuth2Exception) e;
// 转换返回结果
return ResponseEnreplacedy.status(exception.getHttpErrorCode()).body(new CustomOauthException(e.getMessage()));
} else {
throw e;
}
}
};
}
19
Source : UserService.java
with Apache License 2.0
from WeBankFinTech
with Apache License 2.0
from WeBankFinTech
/**
* services for user data.
*/
@Log4j2
@Service
public clreplaced UserService {
@Autowired
private AccountService accountService;
@Autowired
private UserMapper userMapper;
@Autowired
private GroupService groupService;
@Autowired
private FrontRestTools frontRestTools;
@Lazy
@Autowired
private MonitorService monitorService;
/**
* add new user data.
*/
@Transactional
public Integer addUserInfo(Integer groupId, String userName, String account, String description, Integer userType, String privateKeyEncoded) throws NodeMgrException {
log.debug("start addUserInfo groupId:{},userName:{},description:{},userType:{},", groupId, userName, description, userType);
// check group id
groupService.checkGroupId(groupId);
// check userName
TbAccountInfo accountRow = accountService.queryByAccount(account);
TbUser userRow = new TbUser();
if (RoleType.ADMIN.getValue().equals(accountRow.getRoleId())) {
userRow = queryByName(groupId, userName, null);
} else {
userName = account + "_" + userName;
userRow = queryByName(groupId, userName, account);
}
// check username
if (userRow != null) {
log.warn("fail addUserInfo. user info already exists");
throw new NodeMgrException(ConstantCode.USER_EXISTS);
}
// add user by webase-front->webase-sign
String signUserId = UUID.randomUUID().toString().replaceAll("-", "");
// group id as appId
String appId = groupId.toString();
// request sign or not
KeyPair keyPair;
if (StringUtils.isNotBlank(privateKeyEncoded)) {
Map<String, Object> param = new HashMap<>();
param.put("signUserId", signUserId);
param.put("appId", appId);
// already encoded privateKey
param.put("privateKey", privateKeyEncoded);
keyPair = frontRestTools.postForEnreplacedy(groupId, FrontRestTools.URI_KEY_PAIR_IMPORT_WITH_SIGN, param, KeyPair.clreplaced);
} else {
String keyUri = String.format(FrontRestTools.URI_KEY_PAIR, userName, signUserId, appId);
keyPair = frontRestTools.getForEnreplacedy(groupId, keyUri, KeyPair.clreplaced);
}
String publicKey = Optional.ofNullable(keyPair).map(KeyPair::getPublicKey).orElse(null);
String address = Optional.ofNullable(keyPair).map(KeyPair::getAddress).orElse(null);
if (StringUtils.isAnyBlank(publicKey, address)) {
log.warn("get key pair fail. publicKey:{} address:{}", publicKey, address);
throw new NodeMgrException(ConstantCode.SYSTEM_EXCEPTION_GET_PRIVATE_KEY_FAIL);
}
// check address
TbUser addressRow = queryUser(null, groupId, null, address, account);
if (Objects.nonNull(addressRow)) {
log.warn("fail bindUserInfo. address is already exists");
throw new NodeMgrException(ConstantCode.USER_EXISTS);
}
// add row
TbUser newUserRow = new TbUser(HasPk.HAS.getValue(), userType, userName, account, groupId, address, publicKey, description);
newUserRow.setSignUserId(signUserId);
newUserRow.setAppId(appId);
Integer affectRow = userMapper.addUserRow(newUserRow);
if (affectRow == 0) {
log.warn("affect 0 rows of tb_user");
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
// update monitor unusual user's info
monitorService.updateUnusualUser(groupId, userName, address);
Integer userId = newUserRow.getUserId();
log.debug("end addNodeInfo userId:{}", userId);
return userId;
}
/**
* bind user info.
*/
@Transactional
public Integer bindUserInfo(BindUserInputParam user) throws NodeMgrException {
log.debug("start bindUserInfo User:{}", JsonTools.toJSONString(user));
String publicKey = user.getPublicKey();
if (StringUtils.isBlank(publicKey)) {
log.info("fail bindUserInfo. publicKey cannot be empty");
throw new NodeMgrException(ConstantCode.PUBLICKEY_NULL);
}
if (publicKey.length() != ConstantProperties.PUBLICKEY_LENGTH && publicKey.length() != ConstantProperties.ADDRESS_LENGTH) {
log.info("fail bindUserInfo. publicKey length error");
throw new NodeMgrException(ConstantCode.PUBLICKEY_LENGTH_ERROR);
}
// check group id
groupService.checkGroupId(user.getGroupId());
// check userName
TbUser userRow = queryByName(user.getGroupId(), user.getUserName(), user.getAccount());
if (Objects.nonNull(userRow)) {
log.warn("fail bindUserInfo. userName is already exists");
throw new NodeMgrException(ConstantCode.USER_EXISTS);
}
String address = publicKey;
if (publicKey.length() == ConstantProperties.PUBLICKEY_LENGTH) {
address = Web3Tools.getAddressByPublicKey(publicKey);
}
// check address
TbUser addressRow = queryUser(null, user.getGroupId(), null, address, user.getAccount());
if (Objects.nonNull(addressRow)) {
log.warn("fail bindUserInfo. address is already exists");
throw new NodeMgrException(ConstantCode.USER_EXISTS);
}
// add row
TbUser newUserRow = new TbUser(HasPk.NONE.getValue(), user.getUserType(), user.getUserName(), user.getAccount(), user.getGroupId(), address, publicKey, user.getDescription());
Integer affectRow = userMapper.addUserRow(newUserRow);
if (affectRow == 0) {
log.warn("bindUserInfo affect 0 rows of tb_user");
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
Integer userId = newUserRow.getUserId();
// update monitor unusual user's info
monitorService.updateUnusualUser(user.getGroupId(), user.getUserName(), address);
log.debug("end bindUserInfo userId:{}", userId);
return userId;
}
/**
* query count of user.
*/
public Integer countOfUser(UserParam userParam) throws NodeMgrException {
log.debug("start countOfUser. userParam:{}", JsonTools.toJSONString(userParam));
try {
Integer count = userMapper.countOfUser(userParam);
log.debug("end countOfUser userParam:{} count:{}", JsonTools.toJSONString(userParam), count);
return count;
} catch (RuntimeException ex) {
log.error("fail countOfUser userParam:{}", JsonTools.toJSONString(userParam), ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
}
/**
* query user list by page.
*/
public List<TbUser> qureyUserList(UserParam userParam) throws NodeMgrException {
log.debug("start qureyUserList userParam:{}", JsonTools.toJSONString(userParam));
// query user list
List<TbUser> listOfUser = userMapper.listOfUser(userParam);
log.debug("end qureyUserList listOfUser:{}", JsonTools.toJSONString(listOfUser));
return listOfUser;
}
/**
* query user row.
*/
public TbUser queryUser(Integer userId, Integer groupId, String userName, String address, String account) throws NodeMgrException {
log.debug("start queryUser userId:{} groupId:{} userName:{} address:{}", userId, groupId, userName, address);
try {
TbUser userRow = userMapper.queryUser(userId, groupId, userName, address, account);
log.debug("end queryUser userId:{} groupId:{} userName:{} address:{} TbUser:{}", userId, groupId, userName, address, JsonTools.toJSONString(userRow));
return userRow;
} catch (RuntimeException ex) {
log.error("fail queryUser userId:{} groupId:{} userName:{} address:{}", userId, groupId, userName, address, ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
}
/**
* query by groupId、userName.
*/
public TbUser queryUser(Integer groupId, String userName) throws NodeMgrException {
return queryUser(null, groupId, userName, null, null);
}
/**
* query by userName.
*/
public TbUser queryByName(int groupId, String userName, String account) throws NodeMgrException {
return queryUser(null, groupId, userName, null, account);
}
/**
* query by userId.
*/
public TbUser queryByUserId(Integer userId) throws NodeMgrException {
return queryUser(userId, null, null, null, null);
}
/**
* query by group id and address.
*/
public String getSignUserIdByAddress(int groupId, String address) throws NodeMgrException {
TbUser user = queryUser(null, groupId, null, address, null);
if (user == null) {
throw new NodeMgrException(ConstantCode.USER_NOT_EXIST);
}
return user.getSignUserId();
}
public String getUserNameByAddress(int groupId, String address) throws NodeMgrException {
TbUser user = queryUser(null, groupId, null, address, null);
if (user == null) {
throw new NodeMgrException(ConstantCode.USER_NOT_EXIST);
}
return user.getUserName();
}
/**
* update user info.
*/
public void updateUser(UpdateUserInputParam user) throws NodeMgrException {
TbUser tbUser = queryByUserId(user.getUserId());
tbUser.setDescription(user.getDescription());
updateUser(tbUser);
}
/**
* update user info.
*/
public void updateUser(TbUser user) throws NodeMgrException {
log.debug("start updateUser user", JsonTools.toJSONString(user));
Integer userId = Optional.ofNullable(user).map(u -> u.getUserId()).orElse(null);
String description = Optional.ofNullable(user).map(u -> u.getDescription()).orElse(null);
if (userId == null) {
log.warn("fail updateUser. user id is null");
throw new NodeMgrException(ConstantCode.USER_ID_NULL);
}
TbUser tbUser = queryByUserId(userId);
tbUser.setDescription(description);
try {
Integer affectRow = userMapper.updateUser(tbUser);
if (affectRow == 0) {
log.warn("affect 0 rows of tb_user");
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
} catch (RuntimeException ex) {
log.error("fail updateUser userId:{} description:{}", userId, description, ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
log.debug("end updateOrtanization");
}
/**
* get user name by address.
*/
public String queryUserNameByAddress(Integer groupId, String address) throws NodeMgrException {
log.debug("queryUserNameByAddress address:{} ", address);
String userName = userMapper.queryUserNameByAddress(groupId, address);
log.debug("end queryUserNameByAddress");
return userName;
}
public void deleteByAddress(String address) throws NodeMgrException {
log.debug("deleteByAddress address:{} ", address);
userMapper.deleteByAddress(address);
log.debug("end deleteByAddress");
}
/**
* import pem file to import privateKey
*
* @param reqImportPem
* @return userId
*/
public Integer importPem(ReqImportPem reqImportPem) {
PEMManager pemManager = new PEMManager();
String privateKey;
try {
String pemContent = reqImportPem.getPemContent();
pemManager.load(new ByteArrayInputStream(pemContent.getBytes()));
privateKey = Numeric.toHexStringNoPrefix(pemManager.getECKeyPair().getPrivateKey());
} catch (Exception e) {
log.error("importKeyStoreFromPem error:[]", e);
throw new NodeMgrException(ConstantCode.PEM_CONTENT_ERROR);
}
// pem's privateKey encoded here
String privateKeyEncoded = NodeMgrTools.encodedBase64Str(privateKey);
// store local and save in sign
Integer userId = addUserInfo(reqImportPem.getGroupId(), reqImportPem.getUserName(), reqImportPem.getAccount(), reqImportPem.getDescription(), reqImportPem.getUserType(), privateKeyEncoded);
return userId;
}
/**
* import keystore info from p12 file input stream and its preplacedword
*
* @param p12File
* @param p12PreplacedwordEncoded
* @param userName
* @return KeyStoreInfo
*/
public Integer importKeyStoreFromP12(MultipartFile p12File, String p12PreplacedwordEncoded, Integer groupId, String userName, String account, String description) {
// decode p12 preplacedword
String p12Preplacedword;
try {
p12Preplacedword = new String(Base64.getDecoder().decode(p12PreplacedwordEncoded));
} catch (Exception e) {
log.error("decode preplacedword error:[]", e);
throw new NodeMgrException(ConstantCode.PRIVATE_KEY_DECODE_FAIL);
}
P12Manager p12Manager = new P12Manager();
String privateKey;
try {
p12Manager.setPreplacedword(p12Preplacedword);
p12Manager.load(p12File.getInputStream(), p12Preplacedword);
privateKey = Numeric.toHexStringNoPrefix(p12Manager.getECKeyPair().getPrivateKey());
} catch (IOException e) {
log.error("importKeyStoreFromP12 error:[]", e);
if (e.getMessage().contains("preplacedword")) {
throw new NodeMgrException(ConstantCode.P12_PreplacedWORD_ERROR);
}
throw new NodeMgrException(ConstantCode.P12_FILE_ERROR);
} catch (Exception e) {
log.error("importKeyStoreFromP12 error:[]", e);
throw new NodeMgrException(ConstantCode.P12_FILE_ERROR.getCode(), e.getMessage());
}
// pem's privateKey encoded here
String privateKeyEncoded = NodeMgrTools.encodedBase64Str(privateKey);
// store local and save in sign
Integer userId = addUserInfo(groupId, userName, account, description, UserType.GENERALUSER.getValue(), privateKeyEncoded);
return userId;
}
}
19
Source : ContractService.java
with Apache License 2.0
from WeBankFinTech
with Apache License 2.0
from WeBankFinTech
/**
* services for contract data.
*/
@Log4j2
@Service
public clreplaced ContractService {
private static final int CONTRACT_ADDRESS_LENGTH = 42;
private static final String PERMISSION_TYPE_DEPLOY_AND_CREATE = "deployAndCreate";
public static final String STATE_MUTABILITY_VIEW = "view";
public static final String STATE_MUTABILITY_PURE = "pure";
@Autowired
private ContractMapper contractMapper;
@Autowired
private FrontRestTools frontRestTools;
@Autowired
@Lazy
private MonitorService monitorService;
@Autowired
private FrontInterfaceService frontInterface;
@Autowired
private UserService userService;
@Autowired
private AbiService abiService;
@Autowired
private PermissionManageService permissionManageService;
@Autowired
private ContractPathService contractPathService;
/**
* add new contract data.
*/
public TbContract saveContract(Contract contract) throws NodeMgrException {
log.debug("start addContractInfo Contract:{}", JsonTools.toJSONString(contract));
TbContract tbContract;
if (contract.getContractId() == null) {
// new
tbContract = newContract(contract);
} else {
// update
tbContract = updateContract(contract);
}
if (StringUtils.isNotBlank(tbContract.getContractBin())) {
// update monitor unusual deployInputParam's info
monitorService.updateUnusualContract(tbContract.getGroupId(), tbContract.getContractName(), tbContract.getContractBin());
}
return tbContract;
}
/**
* save new contract.
*/
private TbContract newContract(Contract contract) {
if (contract.getAccount() == null) {
throw new NodeMgrException(ConstantCode.ACCOUNT_CANNOT_BE_EMPTY);
}
// check contract not exist.
verifyContractNotExist(contract.getGroupId(), contract.getContractName(), contract.getContractPath(), contract.getAccount());
// add to database.
TbContract tbContract = new TbContract();
BeanUtils.copyProperties(contract, tbContract);
log.debug("newContract save contract");
contractMapper.add(tbContract);
// save contract path
log.debug("newContract save contract path");
// if exist, auto not save (ignor)
contractPathService.save(contract.getGroupId(), contract.getContractPath(), true);
return tbContract;
}
/**
* update contract.
*/
private TbContract updateContract(Contract contract) {
// check not deploy
TbContract tbContract = verifyContractNotDeploy(contract.getContractId(), contract.getGroupId());
// check contractName
verifyContractNameNotExist(contract.getGroupId(), contract.getContractPath(), contract.getContractName(), contract.getAccount(), contract.getContractId());
BeanUtils.copyProperties(contract, tbContract);
contractMapper.update(tbContract);
return tbContract;
}
/**
* delete contract by contractId.
*/
public void deleteContract(Integer contractId, int groupId) throws NodeMgrException {
log.debug("start deleteContract contractId:{} groupId:{}", contractId, groupId);
// check contract id
verifyContractNotDeploy(contractId, groupId);
// remove
contractMapper.remove(contractId);
log.debug("end deleteContract");
}
/**
* query contract list.
*/
public List<TbContract> qureyContractList(ContractParam param) throws NodeMgrException {
log.debug("start qureyContractList ContractListParam:{}", JsonTools.toJSONString(param));
// query contract list
List<TbContract> listOfContract = contractMapper.listOfContract(param);
log.debug("end qureyContractList listOfContract:{}", JsonTools.toJSONString(listOfContract));
return listOfContract;
}
/**
* query contract list.
*/
public List<RspContractNoAbi> qureyContractListNoAbi(ContractParam param) throws NodeMgrException {
log.debug("start qureyContractList ContractListParam:{}", JsonTools.toJSONString(param));
// query contract list
List<TbContract> listOfContract = contractMapper.listOfContract(param);
List<RspContractNoAbi> resultList = new ArrayList<>();
listOfContract.forEach(c -> {
RspContractNoAbi rsp = new RspContractNoAbi();
BeanUtils.copyProperties(c, rsp);
resultList.add(rsp);
});
log.debug("end qureyContractList listOfContract:{}", JsonTools.toJSONString(listOfContract));
return resultList;
}
/**
* query count of contract.
*/
public int countOfContract(ContractParam param) throws NodeMgrException {
log.debug("start countOfContract ContractListParam:{}", JsonTools.toJSONString(param));
try {
return contractMapper.countOfContract(param);
} catch (RuntimeException ex) {
log.error("fail countOfContract", ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
}
/**
* query contract by contract id.
*/
public TbContract queryByContractId(Integer contractId) throws NodeMgrException {
log.debug("start queryContract contractId:{}", contractId);
try {
TbContract contractRow = contractMapper.queryByContractId(contractId);
log.debug("start queryContract contractId:{} contractRow:{}", contractId, JsonTools.toJSONString(contractRow));
return contractRow;
} catch (RuntimeException ex) {
log.error("fail countOfContract", ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
}
/**
* query DeployInputParam By Address.
*/
public List<TbContract> queryContractByBin(Integer groupId, String contractBin) throws NodeMgrException {
try {
if (StringUtils.isEmpty(contractBin)) {
return null;
}
List<TbContract> contractRow = contractMapper.queryContractByBin(groupId, contractBin);
log.debug("start queryContractByBin:{}", contractBin, JsonTools.toJSONString(contractRow));
return contractRow;
} catch (RuntimeException ex) {
log.error("fail queryContractByBin", ex);
throw new NodeMgrException(ConstantCode.DB_EXCEPTION);
}
}
/**
* deploy contract.
*/
public TbContract deployContract(DeployInputParam inputParam) throws NodeMgrException {
log.info("start deployContract. inputParam:{}", JsonTools.toJSONString(inputParam));
int groupId = inputParam.getGroupId();
// check deploy permission
checkDeployPermission(groupId, inputParam.getUser());
String contractName = inputParam.getContractName();
// check contract
verifyContractNotDeploy(inputParam.getContractId(), inputParam.getGroupId());
// check contractName
verifyContractNameNotExist(inputParam.getGroupId(), inputParam.getContractPath(), inputParam.getContractName(), inputParam.getAccount(), inputParam.getContractId());
List<AbiDefinition> abiArray = JsonTools.toJavaObjectList(inputParam.getContractAbi(), AbiDefinition.clreplaced);
if (abiArray == null || abiArray.isEmpty()) {
log.info("fail deployContract. abi is empty");
throw new NodeMgrException(ConstantCode.CONTRACT_ABI_EMPTY);
}
// deploy param
// get signUserId
String signUserId = userService.getSignUserIdByAddress(groupId, inputParam.getUser());
Map<String, Object> params = new HashMap<>();
params.put("groupId", groupId);
params.put("signUserId", signUserId);
params.put("contractName", contractName);
// params.put("version", version);
params.put("abiInfo", abiArray);
params.put("bytecodeBin", inputParam.getBytecodeBin());
params.put("funcParam", inputParam.getConstructorParams());
// deploy
String contractAddress = frontRestTools.postForEnreplacedy(groupId, FrontRestTools.URI_CONTRACT_DEPLOY_WITH_SIGN, params, String.clreplaced);
if (StringUtils.isBlank(contractAddress) || Address.DEFAULT.getValue().equals(contractAddress)) {
log.error("fail deploy, contractAddress is empty");
throw new NodeMgrException(ConstantCode.CONTRACT_DEPLOY_FAIL);
}
// get deploy user name
String userName = userService.getUserNameByAddress(groupId, inputParam.getUser());
// save contract
TbContract tbContract = new TbContract();
BeanUtils.copyProperties(inputParam, tbContract);
tbContract.setDeployAddress(inputParam.getUser());
tbContract.setDeployUserName(userName);
tbContract.setContractAddress(contractAddress);
tbContract.setContractStatus(ContractStatus.DEPLOYED.getValue());
// tbContract.setContractVersion(version);
tbContract.setDeployTime(LocalDateTime.now());
contractMapper.update(tbContract);
log.debug("end deployContract. contractId:{} groupId:{} contractAddress:{}", tbContract.getContractId(), groupId, contractAddress);
return tbContract;
}
/**
* query contract info.
*/
public TbContract queryContract(ContractParam queryParam) {
log.debug("start queryContract. queryParam:{}", JsonTools.toJSONString(queryParam));
TbContract tbContract = contractMapper.queryContract(queryParam);
log.debug("end queryContract. queryParam:{} tbContract:{}", JsonTools.toJSONString(queryParam), JsonTools.toJSONString(tbContract));
return tbContract;
}
/**
* send transaction.
*/
public Object sendTransaction(TransactionInputParam param) throws NodeMgrException {
log.debug("start sendTransaction. param:{}", JsonTools.toJSONString(param));
if (Objects.isNull(param)) {
log.info("fail sendTransaction. request param is null");
throw new NodeMgrException(ConstantCode.INVALID_PARAM_INFO);
}
// check contractId
String contractAbiStr = "";
if (param.getContractId() != null) {
// get abi by contract
TbContract contract = verifyContractIdExist(param.getContractId(), param.getGroupId());
contractAbiStr = contract.getContractAbi();
// send abi to front
sendAbi(param.getGroupId(), param.getContractId(), param.getContractAddress());
// check contract deploy
verifyContractDeploy(param.getContractId(), param.getGroupId());
} else {
// send tx by TABLE abi
// get from db and it's deployed
AbiInfo abiInfo = abiService.getAbiByGroupIdAndAddress(param.getGroupId(), param.getContractAddress());
contractAbiStr = abiInfo.getContractAbi();
}
// if constant, signUserId is useless
AbiDefinition funcAbi = Web3Tools.getAbiDefinition(param.getFuncName(), contractAbiStr);
String signUserId = "empty";
// func is not constant or stateMutability is not equal to 'view' or 'pure'
// fit in solidity 0.6
boolean isConstant = (STATE_MUTABILITY_VIEW.equals(funcAbi.getStateMutability()) || STATE_MUTABILITY_PURE.equals(funcAbi.getStateMutability()));
if (!isConstant) {
// !funcAbi.isConstant()
signUserId = userService.getSignUserIdByAddress(param.getGroupId(), param.getUser());
}
// send transaction
TransactionParam transParam = new TransactionParam();
BeanUtils.copyProperties(param, transParam);
transParam.setSignUserId(signUserId);
Object frontRsp = frontRestTools.postForEnreplacedy(param.getGroupId(), FrontRestTools.URI_SEND_TRANSACTION_WITH_SIGN, transParam, Object.clreplaced);
log.debug("end sendTransaction. frontRsp:{}", JsonTools.toJSONString(frontRsp));
return frontRsp;
}
/**
* verify that the contract does not exist.
*/
private void verifyContractNotExist(int groupId, String name, String path, String account) {
ContractParam param = new ContractParam(groupId, path, name, account);
TbContract contract = queryContract(param);
if (Objects.nonNull(contract)) {
log.warn("contract is exist. groupId:{} name:{} path:{}", groupId, name, path);
throw new NodeMgrException(ConstantCode.CONTRACT_EXISTS);
}
}
/**
* verify that the contract had not deployed.
*/
private TbContract verifyContractNotDeploy(int contractId, int groupId) {
TbContract contract = verifyContractIdExist(contractId, groupId);
if (ContractStatus.DEPLOYED.getValue() == contract.getContractStatus()) {
log.info("contract had bean deployed contractId:{}", contractId);
throw new NodeMgrException(ConstantCode.CONTRACT_HAS_BEAN_DEPLOYED);
}
return contract;
}
/**
* verify that the contract had bean deployed.
*/
private TbContract verifyContractDeploy(int contractId, int groupId) {
TbContract contract = verifyContractIdExist(contractId, groupId);
if (ContractStatus.DEPLOYED.getValue() != contract.getContractStatus()) {
log.info("contract had bean deployed contractId:{}", contractId);
throw new NodeMgrException(ConstantCode.CONTRACT_NOT_DEPLOY);
}
return contract;
}
/**
* verify that the contractId is exist.
*/
private TbContract verifyContractIdExist(int contractId, int groupId) {
ContractParam param = new ContractParam(contractId, groupId);
TbContract contract = queryContract(param);
if (Objects.isNull(contract)) {
log.info("contractId is invalid. contractId:{}", contractId);
throw new NodeMgrException(ConstantCode.INVALID_CONTRACT_ID);
}
return contract;
}
/**
* contract name can not be repeated.
*/
private void verifyContractNameNotExist(int groupId, String path, String name, String account, int contractId) {
ContractParam param = new ContractParam(groupId, path, name, account);
TbContract localContract = queryContract(param);
if (Objects.isNull(localContract)) {
return;
}
if (contractId != localContract.getContractId()) {
throw new NodeMgrException(ConstantCode.CONTRACT_NAME_REPEAT);
}
}
/**
* delete by groupId
*/
public void deleteByGroupId(int groupId) {
if (groupId == 0) {
return;
}
log.info("delete contract by groupId");
contractMapper.removeByGroupId(groupId);
log.info("delete contract path by groupId");
contractPathService.removeByGroupId(groupId);
}
/**
* send abi.
*/
public void sendAbi(int groupId, int contractId, String address) {
log.info("start sendAbi, groupId:{} contractId:{} address:{}", groupId, contractId, address);
TbContract contract = verifyContractIdExist(contractId, groupId);
String localAddress = contract.getContractAddress();
String abiInfo = contract.getContractAbi();
if (StringUtils.isBlank(address)) {
log.warn("ignore sendAbi. inputAddress is empty");
return;
}
if (StringUtils.isBlank(abiInfo)) {
log.warn("ignore sendAbi. abiInfo is empty");
return;
}
if (address.equals(localAddress)) {
log.info("ignore sendAbi. inputAddress:{} localAddress:{}", address, localAddress);
return;
}
if (address.length() != CONTRACT_ADDRESS_LENGTH) {
log.warn("fail sendAbi. inputAddress:{}", address);
throw new NodeMgrException(ConstantCode.CONTRACT_ADDRESS_INVALID);
}
// send abi
PostAbiInfo param = new PostAbiInfo();
param.setGroupId(groupId);
param.setContractName(contract.getContractName());
param.setAddress(address);
param.setAbiInfo(JsonTools.toJavaObjectList(abiInfo, AbiDefinition.clreplaced));
param.setContractBin(contract.getContractBin());
frontInterface.sendAbi(groupId, param);
// save address
if (StringUtils.isBlank(contract.getContractAddress())) {
contract.setContractAddress(address);
contract.setContractStatus(ContractStatus.DEPLOYED.getValue());
}
contract.setDeployTime(LocalDateTime.now());
contract.setDescription("address add by sendAbi");
contractMapper.update(contract);
}
/**
* check user deploy permission
*/
private void checkDeployPermission(int groupId, String userAddress) {
// get deploy permission list
List<PermissionInfo> deployUserList = new ArrayList<>();
BasePageResponse response = permissionManageService.listPermissionFull(groupId, PERMISSION_TYPE_DEPLOY_AND_CREATE, null);
if (response.getCode() != 0) {
log.error("checkDeployPermission get permission list error");
return;
} else {
List listData = (List) response.getData();
deployUserList = JsonTools.toJavaObjectList(JsonTools.toJSONString(listData), PermissionInfo.clreplaced);
}
// check user in the list
if (deployUserList == null || deployUserList.isEmpty()) {
return;
} else {
long count = 0;
count = deployUserList.stream().filter(admin -> userAddress.equals(admin.getAddress())).count();
// if not in the list, permission denied
if (count == 0) {
log.error("checkDeployPermission permission denied for user:{}", userAddress);
throw new NodeMgrException(ConstantCode.PERMISSION_DENIED_ON_CHAIN);
}
}
}
/**
* get contract path list
*/
public List<TbContractPath> queryContractPathList(Integer groupId) {
List<TbContractPath> pathList = contractPathService.listContractPath(groupId);
// not return null, but return empty list
List<TbContractPath> resultList = new ArrayList<>();
if (pathList != null) {
resultList.addAll(pathList);
}
return resultList;
}
public void deleteByContractPath(ContractPathParam param) {
log.debug("start deleteByContractPath ContractPathParam:{}", JsonTools.toJSONString(param));
ContractParam listParam = new ContractParam();
BeanUtils.copyProperties(param, listParam);
List<TbContract> contractList = contractMapper.listOfContract(listParam);
if (contractList == null || contractList.isEmpty()) {
log.debug("deleteByContractPath contract list empty, direct delete path");
contractPathService.removeByPathName(param);
return;
}
// batch delete contract by path that not deployed
Collection<TbContract> unDeployedList = contractList.stream().filter(contract -> ContractStatus.DEPLOYED.getValue() != contract.getContractStatus()).collect(Collectors.toList());
// unDeployed's size == list's size, list is all unDeployed
if (unDeployedList.size() == contractList.size()) {
log.debug("deleteByContractPath delete contract in path");
unDeployedList.forEach(c -> deleteContract(c.getContractId(), c.getGroupId()));
} else {
log.error("end deleteByContractPath for contain deployed contract");
throw new NodeMgrException(ConstantCode.CONTRACT_PATH_CONTAIN_DEPLOYED);
}
log.debug("deleteByContractPath delete path");
contractPathService.removeByPathName(param);
log.debug("end deleteByContractPath. ");
}
/**
* query contract list by multi path
*/
public List<TbContract> qureyContractListMultiPath(ReqListContract param) throws NodeMgrException {
log.debug("start qureyContractListMultiPath ReqListContract:{}", JsonTools.toJSONString(param));
int groupId = param.getGroupId();
String account = param.getAccount();
List<String> pathList = param.getContractPathList();
List<TbContract> resultList = new ArrayList<>();
for (String path : pathList) {
// query contract list
ContractParam listParam = new ContractParam(groupId, account, path);
List<TbContract> listOfContract = contractMapper.listOfContract(listParam);
resultList.addAll(listOfContract);
}
log.debug("end qureyContractListMultiPath listOfContract size:{}", resultList.size());
return resultList;
}
}
19
Source : WebMvcConfigurationSupport.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Bean
@Lazy
public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
return new HandlerMappingIntrospector();
}
19
Source : BeanAnnotationAttributePropagationTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Lazy
@Configuration
clreplaced Config {
@Bean
Object foo() {
return null;
}
}
19
Source : BeanAnnotationAttributePropagationTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Lazy
@Configuration
clreplaced Config {
@Lazy(false)
@Bean
Object foo() {
return null;
}
}
19
Source : BeanAnnotationAttributePropagationTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Lazy
@Bean
Object foo() {
return null;
}
19
Source : AutowiredQualifierFooService.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* @author Mark Fisher
* @author Juergen Hoeller
*/
@Lazy
public clreplaced AutowiredQualifierFooService implements FooService {
@Autowired
@Qualifier("testing")
private FooDao fooDao;
private boolean initCalled = false;
@PostConstruct
private void init() {
if (this.initCalled) {
throw new IllegalStateException("Init already called");
}
this.initCalled = true;
}
@Override
public String foo(int id) {
return this.fooDao.findFoo(id);
}
@Override
public Future<String> asyncFoo(int id) {
return new AsyncResult<>(this.fooDao.findFoo(id));
}
@Override
public boolean isInitCalled() {
return this.initCalled;
}
}
19
Source : GatewayConfiguration.java
with MIT License
from uhonliu
with MIT License
from uhonliu
/**
* 动态路由加载
*
* @return
*/
@Bean
@Lazy
public ResourceLocator resourceLocator(RouteDefinitionLocator routeDefinitionLocator, BaseAuthorityServiceClient baseAuthorityServiceClient, GatewayServiceClient gatewayServiceClient) {
ResourceLocator resourceLocator = new ResourceLocator(routeDefinitionLocator, baseAuthorityServiceClient, gatewayServiceClient);
log.info("ResourceLocator [{}]", resourceLocator);
return resourceLocator;
}
19
Source : Twitter4JComponents.java
with GNU General Public License v3.0
from Tristan971
with GNU General Public License v3.0
from Tristan971
/**
* Configuration clreplaced for Twitter4J related components.
*/
@Lazy
@Configuration
public clreplaced Twitter4JComponents {
/**
* @param environment The Spring environment to fetch authentication keys
* @return this application's configuration for connecting to the Twitter API
*/
@Bean
public twitter4j.conf.Configuration configuration(final Environment environment) {
final ConfigurationBuilder cb = new ConfigurationBuilder();
final String consumerKey = environment.getProperty("twitter.consumerKey");
final String consumerSecret = environment.getProperty("twitter.consumerSecret");
cb.setOAuthConsumerSecret(consumerSecret);
cb.setOAuthConsumerKey(consumerKey);
cb.setTweetModeExtended(true);
return cb.build();
}
/**
* @param configuration this application's configuration
* @return a configured TwitterFactory to generate twitter instances
*/
@Bean
public TwitterFactory twitterFactory(final twitter4j.conf.Configuration configuration) {
return new TwitterFactory(configuration);
}
/**
* @param factory the TwitterFactory to use for configuration
* @return an instance of the {@link Twitter} clreplaced that is configured with Lyrebird's credentials.
*/
@Bean
@Scope(value = SCOPE_PROTOTYPE)
public Twitter twitter(final TwitterFactory factory) {
return factory.getInstance();
}
}
19
Source : CreditsService.java
with GNU General Public License v3.0
from Tristan971
with GNU General Public License v3.0
from Tristan971
/**
* This service aims at exposing credited works disclaimers in src/main/resources/replacedets/credits/third-parties
*
* @see CreditedWork
*/
@Lazy
@Component
public clreplaced CreditsService {
private static final String CREDITS_RESOURCES_PATH = "clreplacedpath:replacedets/credits/third-parties/*.json";
private final ObservableList<CreditedWork> creditedWorks;
@Autowired
public CreditsService(final ObjectMapper objectMapper) {
this.creditedWorks = unmodifiableObservableList(observableList(loadCreditsFiles(objectMapper, new PathMatchingResourcePatternResolver())));
}
/**
* Deserializes the credited works matching the {@link #CREDITS_RESOURCES_PATH} location pattern.
*
* @param objectMapper The object mapper used for deserialization
* @param pmpr The {@link PathMatchingResourcePatternResolver} used for location pattern matching
*
* @return The list of deserialized credits files
*/
private static List<CreditedWork> loadCreditsFiles(final ObjectMapper objectMapper, final PathMatchingResourcePatternResolver pmpr) {
return Try.of(() -> pmpr.getResources(CREDITS_RESOURCES_PATH)).toStream().flatMap(Stream::of).map(unchecked(Resource::getInputStream)).map(unchecked(cis -> objectMapper.readValue(cis, CreditedWork.clreplaced))).toJavaList();
}
/**
* @return the observable list of loaded {@link CreditedWork}s.
*/
public ObservableList<CreditedWork> creditedWorks() {
return creditedWorks;
}
}
19
Source : BackendComponents.java
with GNU General Public License v3.0
from Tristan971
with GNU General Public License v3.0
from Tristan971
@Bean
@Lazy
@Scope(scopeName = SCOPE_PROTOTYPE)
public TwitterHandler twitterHandler(final Twitter twitter) {
return new TwitterHandler(twitter);
}
19
Source : MyConfiguration.java
with MIT License
from TrainingByPackt
with MIT License
from TrainingByPackt
/**
* Every Bean that has a dependency on "theLazyDate" will get this one
* instance. The timestamp will be the time of the first method access
* on the instance.
*/
@Bean
@Lazy
public Date theLazyDate() {
return new Date();
}
19
Source : VerifyCodeServiceImpl.java
with Apache License 2.0
from thousmile
with Apache License 2.0
from thousmile
/**
* <p>
*
* </p>
*
* @author Wang Chen Chen<[email protected]>
* @version 1.0
* @createTime 2020/3/5 0005 11:32
*/
@Slf4j
@Service
public clreplaced VerifyCodeServiceImpl implements VerifyCodeService {
@Autowired
@Lazy
private RedisTemplate<String, String> redisTemplate;
@Override
public BufferedImage randomImageVerifyCode(String codeKey) {
ImageVerifyCode image = VerifyCodeUtils.getImage();
// 将验证码的 codeKey 和 codeText , 保存在 redis 中,有效时间为 10 分钟
redisTemplate.opsForValue().set(codeKey, image.getCodeText().toUpperCase(), 10, TimeUnit.MINUTES);
return image.getImage();
}
@Override
public void deleteImageVerifyCode(String codeKey) {
redisTemplate.delete(codeKey);
}
@Override
public boolean checkVerifyCode(String codeKey, String userCodeText) {
// 获取服务器的 CodeText
String serverCodeText = redisTemplate.opsForValue().get(codeKey);
// 将 serverCodeText 和 user.codeText 都转换成小写,然后比较
if (StringUtils.isEmpty(userCodeText) || !serverCodeText.equals(userCodeText.toUpperCase())) {
return false;
} else {
return true;
}
}
}
19
Source : JaegerActivityTrackingConfiguration.java
with Apache License 2.0
from syndesisio
with Apache License 2.0
from syndesisio
@Lazy
@Bean
public JaegerQueryAPI api() {
return new JaegerQueryAPI(jaegerQueryAPIURL);
}
19
Source : InnerFilterController.java
with Apache License 2.0
from sum1re
with Apache License 2.0
from sum1re
@Controller
@Slf4j
@Lazy
public clreplaced InnerFilterController {
@FXML
public Spinner<Integer> spinner_mpc;
@FXML
public Spinner<Double> spinner_ssim;
@FXML
public Spinner<Double> spinner_psnr;
@FXML
public ChoiceBox<String> choice_similarity_type;
@FXML
public ChoiceBox<String> choice_storage_policy;
private final PreferencesService preferencesService;
protected InnerFilterController(PreferencesService preferencesService) {
this.preferencesService = preferencesService;
}
protected void init() {
spinner_mpc.getValueFactory().setValue(MIN_PIXEL_COUNT.intValue());
spinner_ssim.getValueFactory().setValue(MIN_SSIM_THRESHOLD.doubleValue());
spinner_psnr.getValueFactory().setValue(MIN_PSNR_THRESHOLD.doubleValue());
choice_similarity_type.getSelectionModel().select(SIMILARITY_TYPE.intValue());
choice_storage_policy.getSelectionModel().select(STORAGE_POLICY.intValue());
}
protected void bindListener() {
spinner_mpc.valueProperty().addListener((ov, a, b) -> preferencesService.put(MIN_PIXEL_COUNT, b));
spinner_ssim.valueProperty().addListener((ov, a, b) -> preferencesService.put(MIN_SSIM_THRESHOLD, b));
spinner_psnr.valueProperty().addListener((ov, a, b) -> preferencesService.put(MIN_PSNR_THRESHOLD, b));
choice_similarity_type.getSelectionModel().selectedItemProperty().addListener((ov, a, b) -> preferencesService.put(SIMILARITY_TYPE, getChoiceSelected(choice_similarity_type)));
choice_storage_policy.getSelectionModel().selectedItemProperty().addListener((ov, a, b) -> preferencesService.put(STORAGE_POLICY, getChoiceSelected(choice_storage_policy)));
}
private int getChoiceSelected(ChoiceBox<String> choiceBox) {
return choiceBox.getSelectionModel().getSelectedIndex();
}
}
19
Source : InnerAppController.java
with Apache License 2.0
from sum1re
with Apache License 2.0
from sum1re
@Controller
@Slf4j
@Lazy
public clreplaced InnerAppController {
@FXML
public TextArea text_cds;
@FXML
public Spinner<Integer> spinner_efs;
@FXML
public Spinner<Integer> spinner_fi;
@FXML
public Spinner<Integer> spinner_cpp;
@FXML
public CheckBox check_sim;
@FXML
public CheckBox check_tra;
@FXML
public CheckBox check_jpn;
@FXML
public CheckBox check_eng;
@FXML
public CheckBox check_compress;
@FXML
public CheckBox check_ocr_eop;
@FXML
public Spinner<Integer> spinner_ocr_epp;
@FXML
public TextArea text_video_ext;
@FXML
public Hyperlink hyper_ffmpeg_fill_format;
private final Joiner joiner;
private final Splitter splitter;
private final StageBroadcast stageBroadcast;
private final PreferencesService preferencesService;
private final ResourceBundle resourceBundle;
private final SettingsController settingsController;
private final AppHolder appHolder;
protected InnerAppController(@Qualifier("plus") Joiner joiner, @Qualifier("plusSplitter") Splitter splitter, StageBroadcast stageBroadcast, PreferencesService preferencesService, ResourceBundle resourceBundle, SettingsController settingsController, AppHolder appHolder) {
this.joiner = joiner;
this.splitter = splitter;
this.stageBroadcast = stageBroadcast;
this.preferencesService = preferencesService;
this.resourceBundle = resourceBundle;
this.settingsController = settingsController;
this.appHolder = appHolder;
}
protected void init() {
text_cds.setText(DEFAULT_STYLE.stringValue());
spinner_efs.getValueFactory().setValue(EDITOR_FONT_SIZE.intValue());
spinner_fi.getValueFactory().setValue(FRAME_INTERVAL.intValue());
spinner_cpp.getValueFactory().setValue(COUNT_PRE_PAGE.intValue());
check_compress.setSelected(COMPRESS_IMAGE.booleanValue());
check_ocr_eop.setSelected(EXPORT_ON_ONE_PAGE.booleanValue());
spinner_ocr_epp.getValueFactory().setValue(EXPORT_PER_PAGE.intValue());
text_video_ext.setText(Arrays.toString(FileType.VIDEO.getExtensions()));
settingsController.getFxUtil().modifyToggleText(check_compress);
settingsController.getFxUtil().modifyToggleText(check_ocr_eop);
settingsController.setLanguageList(new ArrayList<>(splitter.splitToList(TESS_LANG.stringValue())));
for (String s : settingsController.getLanguageList()) {
switch(s) {
case "chi_sim":
check_sim.setSelected(true);
break;
case "chi_tra":
check_tra.setSelected(true);
break;
case "jpn":
check_jpn.setSelected(true);
break;
case "eng":
check_eng.setSelected(true);
}
}
}
protected void destroy() {
saveTextArea(text_cds, DEFAULT_STYLE.stringValue(), PrefKey.DEFAULT_STYLE);
if (!settingsController.getLanguageList().isEmpty()) {
String lang = joiner.join(settingsController.getLanguageList());
if (lang.equals(TESS_LANG.stringValue())) {
return;
}
preferencesService.put(TESS_LANG, lang);
stageBroadcast.sendTessLangBroadcast();
}
}
protected void bindListener() {
spinner_efs.valueProperty().addListener(this::onEditorSizeModify);
spinner_fi.valueProperty().addListener((ov, a, b) -> preferencesService.put(FRAME_INTERVAL, b));
spinner_cpp.valueProperty().addListener((ov, a, b) -> preferencesService.put(COUNT_PRE_PAGE, b));
spinner_ocr_epp.valueProperty().addListener((ov, a, b) -> preferencesService.put(EXPORT_PER_PAGE, b));
check_compress.selectedProperty().addListener(this::onCompressModify);
check_sim.selectedProperty().addListener((ov, a, b) -> onCheckBoxClick(b, "chi_sim"));
check_tra.selectedProperty().addListener((ov, a, b) -> onCheckBoxClick(b, "chi_tra"));
check_jpn.selectedProperty().addListener((ov, a, b) -> onCheckBoxClick(b, "jpn"));
check_eng.selectedProperty().addListener((ov, a, b) -> onCheckBoxClick(b, "eng"));
check_ocr_eop.selectedProperty().addListener(this::onExportModify);
hyper_ffmpeg_fill_format.setOnAction(e -> appHolder.getHostServices().showDoreplacedent("https://www.ffmpeg.org/general.html#Supported-File-Formats_002c-Codecs-or-Features"));
}
private void onEditorSizeModify(ObservableValue<?> ov, Integer a, Integer b) {
preferencesService.put(EDITOR_FONT_SIZE, b);
stageBroadcast.sendEditorBroadcast(b);
}
private void onCompressModify(ObservableValue<?> ov, Boolean a, Boolean b) {
preferencesService.put(COMPRESS_IMAGE, b);
Toast.makeToast(settingsController.getStage(), resourceBundle.getString("snackbar.modify.compress"));
settingsController.getFxUtil().modifyToggleText(check_compress);
}
private void onExportModify(ObservableValue<?> ov, Boolean a, Boolean b) {
preferencesService.put(EXPORT_ON_ONE_PAGE, b);
settingsController.getFxUtil().modifyToggleText(check_ocr_eop);
}
private void onCheckBoxClick(boolean isSelected, String value) {
if (isSelected) {
if (!settingsController.getLanguageList().contains(value)) {
settingsController.getLanguageList().add(value);
}
return;
}
settingsController.getLanguageList().remove(value);
}
private void saveTextArea(TextArea textArea, String ori, PrefKey prefKey) {
String result = textArea.getText();
if (!ori.equals(result)) {
if (isNullOrEmpty(result)) {
preferencesService.remove(prefKey);
} else if (prefKey == PrefKey.DEFAULT_STYLE) {
preferencesService.put(DEFAULT_STYLE, result);
}
}
}
}
19
Source : InnerAdvancedController.java
with Apache License 2.0
from sum1re
with Apache License 2.0
from sum1re
@Controller
@Slf4j
@Lazy
public clreplaced InnerAdvancedController {
@FXML
public ChoiceBox<Level> choice_log_level;
private final LogService logService;
protected InnerAdvancedController(LogService logService) {
this.logService = logService;
}
protected void bindListener() {
choice_log_level.getSelectionModel().selectedItemProperty().addListener(this::onLogLevelModify);
}
private void onLogLevelModify(ObservableValue<?> ov, Level a, Level b) {
logService.modifyLogLevel(b);
}
}
19
Source : MainController.java
with Apache License 2.0
from sum1re
with Apache License 2.0
from sum1re
@Controller
@Slf4j
@Lazy
public clreplaced MainController implements BaseController {
@FXML
public VBox root;
@FXML
public MenuBar menu_bar;
@FXML
public VBox mask;
@FXML
public TextArea text_area;
@FXML
public ScrollPane scroll_pane;
@FXML
public FlowPane flow_pane;
@FXML
public Button btn_start;
@FXML
public ProgressBar progress_bar;
@FXML
public Slider slider_zoom;
@FXML
public CheckMenuItem check_manager;
@FXML
public Label file_name;
@FXML
public Label frame_time;
private final MatNodeService matNodeService;
private final FileService fileService;
private final OpenCVService openCVService;
private final VideoService videoService;
private final OCRService ocrService;
private final StageService stageService;
private final StageBroadcast stageBroadcast;
private final FxUtil fxUtil;
private final ResourceBundle resourceBundle;
private final AppHolder appHolder;
private final PreferencesService preferencesService;
private final ExecutorService service;
private final static String MASK_LIGHT_STYLE = "-fx-background-color: rgba(255,255,255,%1$f)";
private final static String MASK_DARK_STYLE = "-fx-background-color: rgba(37,37,37,%1$f)";
private Stage stage;
private ToggleGroup group;
private AsyncTask commonAsyncTask;
private AsyncTask videoAsyncTask;
private File cocrFile;
private File replacedFile;
private int scrollPaneVolume;
private double scrollPaneWidth;
private double matNodeHeight;
private int oldLine;
public MainController(OCRService ocrService, MatNodeService matNodeService, PreferencesService preferencesService, FileService fileService, OpenCVService openCVService, VideoService videoService, StageService stageService, StageBroadcast stageBroadcast, FxUtil fxUtil, ExecutorService service, ResourceBundle resourceBundle, AppHolder appHolder) {
this.ocrService = ocrService;
this.matNodeService = matNodeService;
this.fileService = fileService;
this.openCVService = openCVService;
this.videoService = videoService;
this.stageService = stageService;
this.stageBroadcast = stageBroadcast;
this.fxUtil = fxUtil;
this.service = service;
this.resourceBundle = resourceBundle;
this.appHolder = appHolder;
this.preferencesService = preferencesService;
}
@Override
public void init() {
this.group = new ToggleGroup();
this.scrollPaneVolume = 0;
this.matNodeHeight = 0;
this.oldLine = 0;
this.commonAsyncTask = new AsyncTask();
this.videoAsyncTask = new AsyncTask();
}
@Override
public void destroy() {
stage.setOnHiding(windowEvent -> {
stageService.remove(stage);
// do nothing
});
}
@Override
public void delay() {
this.stage = stageService.add(root);
fxUtil.setFontSize(text_area, EDITOR_FONT_SIZE.intValue());
this.scrollPaneWidth = scroll_pane.getWidth();
onBackgroundModify();
}
@Override
public void bindListener() {
text_area.caretPositionProperty().addListener(this::onTextAreaPositionModify);
scroll_pane.heightProperty().addListener((ov, a, b) -> scrollPaneVolume = 0);
scroll_pane.vvalueProperty().addListener(this::onScrollPaneVModify);
group.selectedToggleProperty().addListener(this::onGroupItemSelected);
slider_zoom.valueProperty().addListener(this::onSliderModify);
check_manager.selectedProperty().addListener(this::onManagerModify);
stageBroadcast.tessLangBroadcast().addListener(this::onTessLanguageModify);
stageBroadcast.dataEmptyBroadcast().addListener((ov, a, b) -> clearMatNodeAndOCR());
stageBroadcast.editorBroadcast().addListener((ov, a, b) -> fxUtil.setFontSize(text_area, b.intValue()));
stageBroadcast.backgroundImageBroadcast().addListener((ov, a, b) -> onBackgroundModify());
root.setOnDragOver(e -> e.acceptTransferModes(TransferMode.ANY));
}
@Override
public void bindHotKey() {
Scene scene = stage.getScene();
scene.getAccelerators().put(new KeyCodeCombination(KeyCode.D), this::onDelMergeClick);
scene.getAccelerators().put(new KeyCodeCombination(KeyCode.C), this::removeBeginTag);
}
@FXML
public void onOpenClick() {
if (isOtherTaskRunning()) {
return;
}
cocrFile = fileService.openFileDialog(stage, resourceBundle.getString("file.choose.cocr"), appHolder.getExtFilter(COCR));
if (cocrFile == null) {
return;
}
openCOCR();
}
@FXML
public void onVideoClick() {
if (isOtherTaskRunning()) {
return;
}
File videoFile = fileService.openFileDialog(stage, resourceBundle.getString("file.choose.video"), appHolder.getExtFilter(VIDEO, ALL));
if (videoFile == null || !videoFile.exists()) {
return;
}
openVideo(videoFile);
}
@FXML
public void onSaveClick() {
if (isOtherTaskRunning()) {
return;
}
if (cocrFile == null) {
cocrFile = fileService.saveFileDialog(stage, resourceBundle.getString("file.choose.save"), appHolder.getExtFilter(COCR));
if (cocrFile == null) {
return;
}
}
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
appHolder.setOcr(text_area.getText());
try {
return fileService.saveCOCR(cocrFile);
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
}
});
service.submit(commonAsyncTask);
}
@FXML
public void onSaveAsClick() {
if (isOtherTaskRunning()) {
return;
}
if (replacedFile == null) {
replacedFile = fileService.saveFileDialog(stage, resourceBundle.getString("file.choose.save"), appHolder.getExtFilter(replaced, SRT));
if (replacedFile == null) {
return;
}
}
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
appHolder.setOcr(text_area.getText());
try {
return replacedFile.getName().endsWith(".srt") ? fileService.saveSrt(replacedFile) : fileService.savereplaced(replacedFile);
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
}
});
service.submit(commonAsyncTask);
}
@FXML
public void onExportClick() {
if (isOtherTaskRunning()) {
return;
}
File export = fileService.saveFileDialog(stage, resourceBundle.getString("file.choose.export"), appHolder.getExtFilter(BMP, JPEG, PNG, ALL));
if (export == null) {
return;
}
if (appHolder.getMatNodeList().isEmpty()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.empty.mat.nodes"));
return;
}
Optional<Integer> result = fxUtil.ocrExportAlert(stage);
if (result.isEmpty()) {
return;
}
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
try {
return fileService.saveOCRImage(export, result.get());
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
}
});
service.submit(commonAsyncTask);
}
@FXML
public void onDelMergeClick() {
if (!check_manager.isSelected()) {
return;
}
service.execute(() -> matNodeService.handleDeleteAndMergeTag(flow_pane));
}
@FXML
public void onOCRClick() {
if (isOtherTaskRunning()) {
return;
}
if (!isNullOrEmpty(text_area.getText())) {
Optional<ButtonType> result = fxUtil.alertWithCancel(stage, resourceBundle.getString("alert.replacedle.user.warning"), null, resourceBundle.getString("alert.content.ocr.warn"));
if (result.isEmpty() || result.get() == ButtonType.CANCEL) {
return;
}
}
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
try {
if (!ocrService.isReady()) {
ocrService.apiInit();
}
return ocrService.doOCR(progress_bar);
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
if (result == 1) {
text_area.setText(appHolder.getOcr());
}
}
});
service.submit(commonAsyncTask);
}
@FXML
public void onAboutClick() throws IOException {
try (InputStream ips = getClreplaced().getResourcereplacedtream("/ThirdLicense");
InputStreamReader reader = new InputStreamReader(ips, Charsets.UTF_8)) {
fxUtil.alert(stage, Build.Info.NAME.value(), Build.Info.VERSION.value(), Build.Info.DESCRIPTION.value(), Collections.singletonList(CharStreams.toString(reader)));
}
}
@FXML
public void onStartClick() {
if (commonAsyncTask.isRunning()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.wait"));
return;
}
if (!videoService.isVideoLoaded()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.empty.video"));
return;
}
if (videoService.isVideoFinish()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.completed.video"));
return;
}
if (videoAsyncTask.isRunning()) {
videoAsyncTask.cancel(true);
} else {
videoAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
Platform.runLater(() -> btn_start.setText(resourceBundle.getString("main.pause")));
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
try {
videoService.videoToCOCR(progress_bar);
return 1;
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void cancelled() {
fxUtil.onFXThread(btn_start.textProperty(), resourceBundle.getString(videoService.isVideoFinish() ? "main.done" : "main.resume"));
if (appHolder.getCount() != 0 && flow_pane.getChildren().size() <= scrollPaneVolume) {
nextPage();
}
}
@Override
public void onResult(Integer result) {
if (result == 1) {
if (appHolder.getCount() != 0 && flow_pane.getChildren().size() <= scrollPaneVolume) {
nextPage();
}
btn_start.setText(resourceBundle.getString(videoService.isVideoFinish() ? "main.done" : "main.resume"));
} else {
btn_start.setText(resourceBundle.getString("main.start"));
}
}
});
service.submit(videoAsyncTask);
}
}
@FXML
public void onDragDropped(DragEvent dragEvent) {
if (isOtherTaskRunning()) {
return;
}
Dragboard dragboard = dragEvent.getDragboard();
if (dragboard.hasFiles()) {
File file = dragboard.getFiles().get(0);
if (!fileService.verifyBatFile(file)) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.invalid.file"));
return;
}
if (file.getName().endsWith(".cocr")) {
cocrFile = file;
openCOCR();
} else {
openVideo(file);
}
preferencesService.put(FILE_CHOOSE_DIR, file.getParent());
}
}
@FXML
public void onClick(ActionEvent event) {
if (isOtherTaskRunning()) {
return;
}
switch(((MenuItem) event.getSource()).getId()) {
case "menu_filter":
if (!videoService.isVideoLoaded()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.empty.video"));
return;
}
fxUtil.openBlockStage(LayoutName.LAYOUT_FILTER, "main.caption.filter");
break;
case "menu_bat":
if (appHolder.getCount() != 0 || !isNullOrEmpty(text_area.getText())) {
Optional<ButtonType> result = fxUtil.alertWithCancel(stage, resourceBundle.getString("alert.replacedle.user.warning"), null, resourceBundle.getString("alert.content.bat"));
if (result.isEmpty() || result.get() == ButtonType.CANCEL) {
return;
}
}
fxUtil.openBlockStage(LayoutName.LAYOUT_BAT, "main.file.bat");
break;
case "menu_settings":
fxUtil.openBlockStage(LayoutName.LAYOUT_SETTINGS, "main.file.settings");
break;
}
}
private void openCOCR() {
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
try {
return fileService.readCOCR(cocrFile);
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
if (result == null || result != 1) {
return;
}
replacedFile = null;
clearMatNodeAndOCR();
if (appHolder.getCount() != 0) {
nextPage();
}
text_area.setText(appHolder.getOcr());
file_name.setText(cocrFile.getName());
if (videoAsyncTask.isCancelled()) {
btn_start.setText(resourceBundle.getString("main.start"));
}
videoService.closeVideo();
}
});
service.submit(commonAsyncTask);
}
private void openVideo(File videoFile) {
commonAsyncTask = new AsyncTask().setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
return videoService.loadVideo(videoFile);
}
@Override
public void onResult(Integer result) {
if (result == 1) {
appHolder.setOcr("");
clearMatNodeAndOCR();
cocrFile = null;
replacedFile = null;
btn_start.setText(resourceBundle.getString("main.start"));
file_name.setText(videoFile.getName());
}
}
});
service.submit(commonAsyncTask);
}
private void onBackgroundModify() {
BigDecimal opacity = divide(BACKGROUND_OPACITY.intValue(), 100);
mask.setStyle(String.format(DARK_THEME.booleanValue() ? MASK_DARK_STYLE : MASK_LIGHT_STYLE, opacity));
menu_bar.setStyle(String.format(DARK_THEME.booleanValue() ? MASK_DARK_STYLE : MASK_LIGHT_STYLE, opacity));
if (isNullOrEmpty(BACKGROUND_IMAGE.stringValue())) {
root.setBackground(Background.EMPTY);
return;
}
File file = new File(BACKGROUND_IMAGE.stringValue());
try (FileInputStream fis = new FileInputStream(file)) {
Image image = new Image(fis, 1920, 0, true, true);
BackgroundImage backgroundImage = new BackgroundImage(image, NO_REPEAT, NO_REPEAT, CENTER, new BackgroundSize(100, 100, true, true, true, true));
root.setBackground(new Background(backgroundImage));
} catch (Throwable e) {
e.printStackTrace();
}
}
private void onTextAreaPositionModify(ObservableValue<?> ov, Number a, Number b) {
if (a.equals(b)) {
return;
}
int line = matNodeService.getCaretPosition(text_area.getText(), text_area.getCaretPosition());
if (line == oldLine) {
return;
}
oldLine = line;
selecreplacedem(line - 1);
}
private void onTessLanguageModify(ObservableValue<?> ov, Number a, Number b) {
service.submit(commonAsyncTask.setTaskListen(new AsyncTask.TaskListen() {
@Override
public void onPreExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), -1D);
}
@Override
public void onPostExecute() {
fxUtil.onFXThread(progress_bar.progressProperty(), 0D);
}
@Override
public Integer call() {
try {
ocrService.apiInit();
return 1;
} catch (Throwable ignored) {
return 0;
}
}
@Override
public void onResult(Integer result) {
}
}));
}
private void onGroupItemSelected(ObservableValue<?> ov, Toggle a, Toggle b) {
if (b == null) {
a.setSelected(true);
return;
}
MatNode matNode = (MatNode) b;
int index = appHolder.getMatNodeList().indexOf(matNode);
appHolder.setMatNodeSelectedIndex(index);
frame_time.setText(matNodeService.getMatNodeFormatterTime(matNode));
log.debug("Selected MatNode id: {}", matNode.getNid());
}
private void onScrollPaneVModify(ObservableValue<?> ov, Number a, Number b) {
if (b.doubleValue() > 0.9 && flow_pane.getChildren().size() < appHolder.getCount()) {
nextPage();
}
}
private void onSliderModify(ObservableValue<?> ov, Number a, Number b) {
scrollPaneVolume = 0;
scrollPaneWidth = b.doubleValue() * 2;
for (MatNode matNode : appHolder.getMatNodeList()) {
matNode.zoom(scrollPaneWidth);
}
}
private void onManagerModify(ObservableValue<?> ov, Boolean a, Boolean b) {
if (appHolder.getMatNodeList().isEmpty()) {
return;
}
for (MatNode matNode : appHolder.getMatNodeList()) {
matNode.switchModel(!b);
}
}
private void onMatNodeClick(MouseEvent mouseEvent, MatNode matNode) {
if (!check_manager.isSelected()) {
return;
}
switch(mouseEvent.getButton()) {
case PRIMARY:
if (matNode.isMerge()) {
matNodeService.markSaveTag(matNode);
} else {
matNodeService.markDeleteTag(matNode);
}
break;
case SECONDARY:
group.selectToggle(matNode);
matNodeService.markMergeTag(matNode);
break;
}
}
private void removeBeginTag() {
if (!check_manager.isSelected()) {
return;
}
matNodeService.removeMergeBeginTag();
}
private void clearMatNodeAndOCR() {
flow_pane.getChildren().clear();
text_area.setText("");
System.gc();
}
private void nextPage() {
if (scrollPaneVolume == 0 || matNodeHeight == 0) {
matNodeHeight = appHolder.getMatNodeList().get(0).getHeight();
scrollPaneVolume = (int) (scroll_pane.getHeight() / matNodeHeight);
}
List<MatNode> matNodeList = appHolder.getMatNodeList().stream().skip(flow_pane.getChildren().size()).limit(COUNT_PRE_PAGE.intValue()).collect(Collectors.toList());
for (MatNode matNode : matNodeList) {
matNode.setOnMouseClicked(mouseEvent -> onMatNodeClick(mouseEvent, matNode));
matNode.loadImage(openCVService.mat2Image(matNode.getMat(), COMPRESS_IMAGE.booleanValue()), scrollPaneWidth);
matNode.setToggleGroup(group);
}
flow_pane.getChildren().addAll(matNodeList);
}
private void selecreplacedem(int index) {
if (flow_pane.getChildren().size() == 0) {
return;
}
if (index >= appHolder.getCount()) {
return;
}
while (index > (flow_pane.getChildren().size() - 1)) {
nextPage();
}
Node node = flow_pane.getChildren().get(index);
group.selectToggle((MatNode) node);
ensureVisible(node);
}
private void ensureVisible(Node node) {
double h = scroll_pane.getContent().getBoundsInLocal().getHeight();
double y = (node.getBoundsInParent().getMaxY() + node.getBoundsInParent().getMinY()) / 2.0;
double v = scroll_pane.getViewportBounds().getHeight();
scroll_pane.setVvalue((y - 0.2 * v) / (h - v));
}
private boolean isOtherTaskRunning() {
if (commonAsyncTask.isRunning() || videoAsyncTask.isRunning()) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.wait"));
return true;
}
return false;
}
}
19
Source : FilterController.java
with Apache License 2.0
from sum1re
with Apache License 2.0
from sum1re
@Controller
@Slf4j
@Lazy
public clreplaced FilterController implements BaseController {
private final StageService stageService;
private final VideoService videoService;
private final OpenCVService openCVService;
private final ModuleService moduleService;
private final ResourceBundle resourceBundle;
private final StageBroadcast stageBroadcast;
private final VideoHolder videoHolder;
private final FxUtil fxUtil;
private final FieldUtil fieldUtil;
private final PreferencesService preferencesService;
private final Joiner joiner;
private final FileService fileService;
private final AppHolder appHolder;
@FXML
public SplitPane split_main;
@FXML
public Slider slider_zoom;
@FXML
public Slider slider_video;
@FXML
public CheckBox check_filter;
@FXML
public ChoiceBox<String> choice_profile;
@FXML
public VBox module_type_list;
@FXML
public VBox module_node_list;
@FXML
public ImageView image_view;
private Stage stage;
private Mat mat;
private double frameCount;
private boolean reorder;
private boolean skipSave;
public FilterController(PreferencesService preferencesService, StageService stageService, VideoService videoService, OpenCVService openCVService, ModuleService moduleService, StageBroadcast stageBroadcast, VideoHolder videoHolder, FxUtil fxUtil, FieldUtil fieldUtil, FileService fileService, ResourceBundle resourceBundle, @Qualifier("dot") Joiner joiner, AppHolder appHolder) {
this.resourceBundle = resourceBundle;
this.stageService = stageService;
this.videoService = videoService;
this.openCVService = openCVService;
this.moduleService = moduleService;
this.stageBroadcast = stageBroadcast;
this.videoHolder = videoHolder;
this.fxUtil = fxUtil;
this.fieldUtil = fieldUtil;
this.preferencesService = preferencesService;
this.joiner = joiner;
this.fileService = fileService;
this.appHolder = appHolder;
}
@Override
public void init() {
mat = new Mat();
readVideo(0);
}
@Override
public void destroy() {
stage.setOnHiding(windowEvent -> {
stageService.remove(stage);
System.gc();
});
}
@Override
public void delay() {
this.stage = stageService.add(split_main);
setChoiceList();
reorder = false;
skipSave = false;
// add all module
module_type_list.getChildren().addAll(Arrays.stream(ModuleType.values()).parallel().map(moduleType -> {
Button button = new Button();
button.setFocusTraversable(false);
button.setId(moduleType.name());
button.setOnAction(FilterController.this::onModuleTypeClick);
button.setText(resourceBundle.getString(joiner.join("module", moduleType.toLowerCase())));
return button;
}).collect(Collectors.toList()));
loadModuleStatus();
}
@Override
public void bindListener() {
slider_video.valueProperty().addListener((ov, a, b) -> readVideo(b.doubleValue()));
slider_zoom.valueProperty().addListener((ov, a, b) -> image_view.setFitWidth(b.doubleValue() * 2));
check_filter.selectedProperty().addListener((ov, a, b) -> readVideo(frameCount));
choice_profile.getSelectionModel().selectedItemProperty().addListener(this::onProfileBoxModify);
module_node_list.getChildren().addListener(this::onModuleNodeListModify);
stageBroadcast.moduleBroadcast().addListener((ov, a, b) -> updateFilter());
stageBroadcast.profileListBroadcast().addListener((ov, a, b) -> setChoiceList());
}
@FXML
public void onCreate() throws IOException {
String str = askInput(resourceBundle.getString("alert.content.module.profile.new"));
if (str == null) {
return;
}
fileService.saveModuleProfile(str, MODULE_PROFILE_DEFAULT.value());
choice_profile.getSelectionModel().select(str);
}
@FXML
public void onCopy() throws IOException {
String str = askInput(resourceBundle.getString("alert.content.module.profile.copy"));
if (str == null) {
return;
}
fileService.saveModuleProfile(str, MODULE_PROFILE_STATUS_LIST.value());
choice_profile.getSelectionModel().select(str);
}
@FXML
public void onDelete() throws IOException {
if (isNegative(resourceBundle.getString("alert.content.module.profile.delete"))) {
return;
}
fileService.deleteModuleProfile(MODULE_PROFILE_NAME.stringValue());
choice_profile.getSelectionModel().select(MODULE_PROFILE_NAME.stringValue());
}
@FXML
public void onSliderScroll(ScrollEvent scrollEvent) {
Slider slider = (Slider) scrollEvent.getSource();
if (scrollEvent.getDeltaY() > 0 && slider.getValue() < slider.getMax()) {
slider.valueProperty().set(slider.getValue() + slider.getBlockIncrement());
} else if (scrollEvent.getDeltaY() < 0 && slider.getValue() > slider.getMin()) {
slider.valueProperty().set(slider.getValue() - slider.getBlockIncrement());
}
}
@FXML
public void onMouseMovedOnImage(MouseEvent mouseEvent) {
int x = (int) mouseEvent.getX();
int y = (int) mouseEvent.getY();
double axisX = (videoHolder.getWidth() * x) / (image_view.getFitWidth());
double axisY = (videoHolder.getHeight() * y) / (image_view.getFitWidth() * videoHolder.getRatio());
Scene scene = split_main.getScene();
for (Map.Entry<String, Integer> entry : openCVService.getPixelColor((int) axisX, (int) axisY).entrySet()) {
Label label = (Label) scene.lookup(entry.getKey());
label.setText(v2s(entry.getValue()));
}
}
private void onProfileBoxModify(ObservableValue<?> ov, String a, String b) {
if (a == null || b == null || a.equals(b)) {
return;
}
preferencesService.put(MODULE_PROFILE_NAME, b);
try {
fileService.loadModuleProfileStatusList();
} catch (IOException ignored) {
}
skipSave = true;
loadModuleStatus();
}
private void onModuleNodeListModify(ListChangeListener.Change<?> change) {
// Reorder if necessary.
if (reorder) {
int i = 0;
for (Node node : module_node_list.getChildren()) {
ModuleNode moduleNode = (ModuleNode) node;
if (moduleNode.getIndex() != i) {
moduleNode.setIndex(i);
}
i++;
}
reorder = false;
}
updateFilter();
}
private void onModuleTypeClick(ActionEvent actionEvent) {
String nodeFxId = ((Node) actionEvent.getSource()).getId();
int index = module_node_list.getChildren().size();
ModuleType type = fieldUtil.reflectFxId(nodeFxId);
if (type != null) {
ModuleNode moduleNode = moduleService.generate(index, type, true);
setModuleNodeListener(moduleNode);
module_node_list.getChildren().add(moduleNode);
}
}
/**
* Read one frame from the video.
*
* @param value frame count
*/
private void readVideo(double value) {
frameCount = value;
if (!videoService.readFrame(mat, value / 100 * videoHolder.getTotalFrame())) {
return;
}
openCVService.setVideoOriMat(mat);
if (check_filter.isSelected()) {
try {
mat = openCVService.replaceRoiImage(mat);
} catch (Throwable ignored) {
}
}
Image toShow = openCVService.mat2Image(mat, false);
fxUtil.onFXThread(image_view.imageProperty(), toShow);
}
private void updateFilter() {
MODULE_PROFILE_STATUS_LIST.setValue(module_node_list.getChildren().stream().map(node -> ((ModuleNode) node).getModuleStatus()).collect(Collectors.toList()));
if (skipSave) {
skipSave = false;
return;
}
try {
fileService.saveModuleProfile(MODULE_PROFILE_NAME.stringValue(), MODULE_PROFILE_STATUS_LIST.value());
} catch (IOException ignored) {
}
readVideo(frameCount);
}
@SuppressWarnings("unchecked")
private void loadModuleStatus() {
// reset all ModuleNode, do not use 'getChildren().clear()'
module_node_list.getChildren().setAll(((List<ModuleStatus>) MODULE_PROFILE_STATUS_LIST.value()).stream().map(moduleStatus -> {
ModuleNode moduleNode = moduleService.generate(moduleStatus);
// 'CROP' must be the first module, and can not modify.
if (moduleNode.getIndex() == 0 && moduleNode.getModuleStatus().getModuleType() == CROP) {
moduleNode.getCheck_enable().setDisable(true);
moduleNode.getBtn_del().setDisable(true);
return moduleNode;
}
setModuleNodeListener(moduleNode);
return moduleNode;
}).collect(Collectors.toList()));
}
private void setModuleNodeListener(ModuleNode moduleNode) {
moduleNode.setDelAction(actionEvent -> {
reorder = true;
module_node_list.getChildren().remove(moduleNode);
}).setCacheListener((ov, a, b) -> {
moduleNode.getModuleStatus().setCache(b);
updateFilter();
}).setEnableListener((ov, a, b) -> {
moduleNode.getModuleStatus().setEnable(b);
if (b) {
moduleNode.setOpacity(1.0);
} else {
moduleNode.setOpacity(0.5);
}
updateFilter();
}).setDragDetected(mouseEvent -> {
Dragboard dragboard = moduleNode.startDragAndDrop(MOVE);
ClipboardContent content = new ClipboardContent();
content.putString(UUID.randomUUID().toString());
dragboard.setContent(content);
dragboard.setDragView(moduleNode.snapshot(null, null));
mouseEvent.consume();
}).setDragOver(dragEvent -> {
if (dragEvent.getDragboard().hreplacedtring() && dragEvent.getGestureSource() != moduleNode) {
dragEvent.acceptTransferModes(MOVE);
}
dragEvent.consume();
}).setDragDropped(dragEvent -> {
Dragboard dragboard = dragEvent.getDragboard();
boolean success = false;
if (dragboard.hreplacedtring()) {
ModuleNode node = (ModuleNode) dragEvent.getGestureSource();
module_node_list.getChildren().remove(node);
int index = module_node_list.getChildren().indexOf(moduleNode);
reorder = true;
module_node_list.getChildren().add(index + 1, node);
success = true;
}
dragEvent.setDropCompleted(success);
dragEvent.consume();
});
}
private void setChoiceList() {
choice_profile.gereplacedems().setAll(appHolder.getModuleProfileList());
choice_profile.getSelectionModel().select(MODULE_PROFILE_NAME.stringValue());
}
private boolean isNegative(String context) {
Optional<ButtonType> result = fxUtil.alertWithCancel(stage, resourceBundle.getString("alert.replacedle.user.warning"), null, context);
return result.isEmpty() || result.get() == ButtonType.CANCEL;
}
private String askInput(String contextText) {
Optional<String> result = fxUtil.textInputAlert(stage, contextText);
if (result.isEmpty()) {
return null;
}
String str = result.get();
if (Strings.isNullOrEmpty(str)) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.module.profile.invalid"));
return null;
}
if (appHolder.getModuleProfileList().contains(str)) {
Toast.makeToast(stage, resourceBundle.getString("snackbar.module.profile.exists"));
return null;
}
return str;
}
}
19
Source : MagicSwaggerConfiguration.java
with MIT License
from ssssssss-team
with MIT License
from ssssssss-team
/**
* Swagger配置类
*/
@Configuration
@AutoConfigureAfter({ MagicAPIAutoConfiguration.clreplaced })
@EnableConfigurationProperties(MagicAPIProperties.clreplaced)
@ConditionalOnClreplaced(name = "springfox.doreplacedentation.swagger.web.SwaggerResourcesProvider")
public clreplaced MagicSwaggerConfiguration {
@Autowired
@Lazy
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@Autowired
private ApplicationContext context;
private MagicAPIProperties properties;
public MagicSwaggerConfiguration(MagicAPIProperties properties) {
this.properties = properties;
}
@Bean
@Primary
public SwaggerResourcesProvider magicSwaggerResourcesProvider(MappingHandlerMapping handlerMapping, GroupServiceProvider groupServiceProvider, ServletContext servletContext) throws NoSuchMethodException {
SwaggerConfig config = properties.getSwaggerConfig();
RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(config.getLocation()).build();
// 构建文档信息
SwaggerProvider swaggerProvider = new SwaggerProvider();
swaggerProvider.setGroupServiceProvider(groupServiceProvider);
swaggerProvider.setMappingHandlerMapping(handlerMapping);
swaggerProvider.setreplacedle(config.getreplacedle());
swaggerProvider.setDescription(config.getDescription());
swaggerProvider.setVersion(config.getVersion());
swaggerProvider.setBasePath(servletContext.getContextPath());
// 注册swagger.json
requestMappingHandlerMapping.registerMapping(requestMappingInfo, swaggerProvider, SwaggerProvider.clreplaced.getDeclaredMethod("swaggerJson"));
return () -> {
List<SwaggerResource> resources = new ArrayList<>();
Map<String, SwaggerResourcesProvider> beans = context.getBeansOfType(SwaggerResourcesProvider.clreplaced);
// 获取已定义的文档信息
if (beans != null) {
for (Map.Entry<String, SwaggerResourcesProvider> entry : beans.entrySet()) {
if (!"magicSwaggerResourcesProvider".equalsIgnoreCase(entry.getKey())) {
resources.addAll(entry.getValue().get());
}
}
}
// 追加Magic Swagger信息
resources.add(swaggerResource(config.getName(), config.getLocation()));
return resources;
};
}
/**
* 构建 SwaggerResource
*
* @param name 名字
* @param location 位置
* @return
*/
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource resource = new SwaggerResource();
resource.setName(name);
resource.setLocation(location);
resource.setSwaggerVersion("2.0");
return resource;
}
}
19
Source : BankAccountDaoJpa.java
with GNU General Public License v2.0
from singerdmx
with GNU General Public License v2.0
from singerdmx
@Repository
public clreplaced BankAccountDaoJpa {
@Autowired
private BankAccountRepository bankAccountRepository;
@Autowired
private TransactionRepository transactionRepository;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private BankAccountTransactionRepository bankAccountTransactionRepository;
@Autowired
private BankAccountBalanceRepository bankAccountBalanceRepository;
@Lazy
@Autowired
private TransactionDaoJpa transactionDaoJpa;
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public List<com.bulletjournal.controller.models.BankAccount> getBankAccounts(String requester) {
List<BankAccount> bankAccounts = this.bankAccountRepository.findAllByOwner(requester);
return bankAccounts.stream().sorted((a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt())).map(b -> b.toPresentationModel(this)).collect(Collectors.toList());
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public BankAccount getBankAccount(String requester, Long bankAccountId) {
if (bankAccountId == null) {
return null;
}
BankAccount bankAccount = this.bankAccountRepository.findById(bankAccountId).orElseThrow(() -> new ResourceNotFoundException("Bank Account " + bankAccountId + " not found"));
// check access
this.authorizationService.checkAuthorizedToOperateOnContent(bankAccount.getOwner(), requester, ContentType.BANK_ACCOUNT, Operation.READ, bankAccountId);
return bankAccount;
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public com.bulletjournal.controller.models.BankAccount create(CreateBankAccountParams createBankAccountParams, String owner) {
BankAccount bankAccount = new BankAccount();
bankAccount.setOwner(owner);
bankAccount.setName(createBankAccountParams.getName());
bankAccount.setAccountType(createBankAccountParams.getAccountType());
bankAccount.setDescription(createBankAccountParams.getDescription());
bankAccount.setAccountNumber(createBankAccountParams.getAccountNumber());
// net balance is 0 when create ?
bankAccount.setNetBalance(0.0);
bankAccount = this.bankAccountRepository.save(bankAccount);
this.bankAccountBalanceRepository.save(new BankAccountBalance(bankAccount.getId(), 0));
return bankAccount.toPresentationModel();
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public com.bulletjournal.controller.models.BankAccount update(String requester, Long bankAccountId, UpdateBankAccountParams updateBankAccountParams) {
BankAccount bankAccount = getBankAccount(requester, bankAccountId);
if (!updateBankAccountParams.hasName()) {
throw new BadRequestException("Name cannot be empty");
}
if (!updateBankAccountParams.hasAccountType()) {
throw new BadRequestException("Account type cannot be empty");
}
// check access
this.authorizationService.checkAuthorizedToOperateOnContent(bankAccount.getOwner(), requester, ContentType.BANK_ACCOUNT, Operation.UPDATE, bankAccountId);
bankAccount.setAccountNumber(updateBankAccountParams.getAccountNumber());
bankAccount.setName(updateBankAccountParams.getName());
bankAccount.setDescription(updateBankAccountParams.getDescription());
bankAccount.setAccountType(updateBankAccountParams.getAccountType());
return this.bankAccountRepository.save(bankAccount).toPresentationModel(this);
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public void deleteBankAccount(String requester, Long bankAccountId) {
BankAccount bankAccount = getBankAccount(requester, bankAccountId);
List<Transaction> transactions = this.transactionRepository.findByBankAccount(bankAccount);
for (Transaction t : transactions) {
t.setBankAccount(null);
}
this.authorizationService.checkAuthorizedToOperateOnContent(bankAccount.getOwner(), requester, ContentType.BANK_ACCOUNT, Operation.DELETE, bankAccountId);
this.bankAccountRepository.delete(bankAccount);
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public double getBankAccountBalance(Long bankAccountId) {
if (this.bankAccountBalanceRepository.existsById(bankAccountId)) {
return this.bankAccountBalanceRepository.findById(bankAccountId).get().getBalance();
}
BankAccount bankAccount = this.bankAccountRepository.findById(bankAccountId).orElseThrow(() -> new ResourceNotFoundException("Bank Account " + bankAccountId + " not found"));
double sum = bankAccount.getNetBalance() + this.transactionRepository.getTransactionsAmountSumByBankAccount(bankAccountId) + this.transactionDaoJpa.getRecurringTransactionsAmountSum(bankAccount);
this.bankAccountBalanceRepository.save(new BankAccountBalance(bankAccountId, sum));
return sum;
}
@Transactional(rollbackFor = Exception.clreplaced, propagation = Propagation.REQUIRED)
public void setBalance(String requester, Long bankAccountId, double balance, String name) {
BankAccount bankAccount = getBankAccount(requester, bankAccountId);
double oldBalance = getBankAccountBalance(bankAccountId);
double change = balance - oldBalance;
if (Math.abs(change) < 0.000001) {
return;
}
BankAccountTransaction bankAccountTransaction = new BankAccountTransaction();
bankAccountTransaction.setBankAccount(bankAccount);
bankAccountTransaction.setName(name);
bankAccountTransaction.setAmount(change);
bankAccount.setNetBalance(bankAccount.getNetBalance() + change);
this.bankAccountTransactionRepository.save(bankAccountTransaction);
this.bankAccountBalanceRepository.save(new BankAccountBalance(bankAccountId, balance));
}
}
19
Source : WebserviceConfig.java
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
@Lazy
@Bean
public JNCryptor jnCryptor() {
final AES256JNCryptor aes256jnCryptor = new AES256JNCryptor();
aes256jnCryptor.setPBKDFIterations(Constants.JN_CRYPTOR_ITERATIONS);
return aes256jnCryptor;
}
19
Source : WebServiceSecurityConfig.java
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
@Lazy
@Bean
public TokenStore tokenStore(final DataSource dataSource) {
return new CachableJdbcTokenStore(dataSource);
}
19
Source : AdminAPIClientDetails.java
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
/**
* This defines the Spring's OAuth2 ClientDetails for an Administration API client.
*/
@Lazy
@Component
public final clreplaced AdminAPIClientDetails extends BaseClientDetails {
private static final long serialVersionUID = 4505193832353978832L;
public AdminAPIClientDetails(@Qualifier(WebSecurityConfig.CLIENT_PreplacedWORD_ENCODER_BEAN_NAME) final PreplacedwordEncoder clientPreplacedwordEncoder, @Value("${sebserver.webservice.api.admin.clientId}") final String clientId, @Value("${sebserver.webservice.api.admin.clientSecret}") final String clientSecret, @Value("${sebserver.webservice.api.admin.accessTokenValiditySeconds:3600}") final Integer accessTokenValiditySeconds, @Value("${sebserver.webservice.api.admin.refreshTokenValiditySeconds:-1}") final Integer refreshTokenValiditySeconds) {
super(clientId, WebserviceResourceConfiguration.ADMIN_API_RESOURCE_ID, StringUtils.joinWith(Constants.LIST_SEPARATOR, Constants.OAUTH2_SCOPE_READ, Constants.OAUTH2_SCOPE_WRITE), StringUtils.joinWith(Constants.LIST_SEPARATOR, Constants.OAUTH2_GRANT_TYPE_PreplacedWORD, Constants.OAUTH2_GRANT_TYPE_REFRESH_TOKEN), null);
super.setClientSecret(clientPreplacedwordEncoder.encode(clientSecret));
super.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
super.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
}
}
19
Source : AsyncService.java
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
@Lazy
@Service
public clreplaced AsyncService {
private final AsyncRunner asyncRunner;
protected AsyncService(final AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
/**
* Create a CircuitBreaker of specified type with the default parameter defined in the CircuitBreaker clreplaced
*
* @param <T> the type of the CircuitBreaker
* @return a CircuitBreaker of specified type with the default parameter defined in the CircuitBreaker clreplaced
*/
public <T> CircuitBreaker<T> createCircuitBreaker() {
return new CircuitBreaker<>(this.asyncRunner);
}
/**
* Create a CircuitBreaker of specified type.
*
* @param maxFailingAttempts maximal number of attempts the CircuitBreaker allows before going onto open state.
* @param maxBlockingTime maximal time since call CircuitBreaker waits for a response before going onto open state.
* @param timeToRecover the time the CircuitBreaker takes to recover form open state.
* @param <T> the type of the CircuitBreaker
* @return a CircuitBreaker of specified type
*/
public <T> CircuitBreaker<T> createCircuitBreaker(final int maxFailingAttempts, final long maxBlockingTime, final long timeToRecover) {
return new CircuitBreaker<>(this.asyncRunner, maxFailingAttempts, maxBlockingTime, timeToRecover);
}
/**
* Create a MemoizingCircuitBreaker of specified type that memoize a successful result and return the last
* successful result on fail as long as maxMemoizingTime is not exceeded.
*
* @param blockingSupplier the blocking result supplier that the MemoizingCircuitBreaker must call
* @param maxFailingAttempts maximal number of attempts the CircuitBreaker allows before going onto open state.
* @param maxBlockingTime maximal time since call CircuitBreaker waits for a response before going onto open state.
* @param timeToRecover the time the CircuitBreaker takes to recover form open state.
* @param momoized whether the memoizing functionality is on or off
* @param maxMemoizingTime the maximal time memorized data is valid
* @param <T> the type of the CircuitBreaker
* @return a CircuitBreaker of specified type
*/
public <T> MemoizingCircuitBreaker<T> createMemoizingCircuitBreaker(final Supplier<T> blockingSupplier, final int maxFailingAttempts, final long maxBlockingTime, final long timeToRecover, final boolean momoized, final long maxMemoizingTime) {
return new MemoizingCircuitBreaker<>(this.asyncRunner, blockingSupplier, maxFailingAttempts, maxBlockingTime, timeToRecover, momoized, maxMemoizingTime);
}
}
19
Source : JSONMapper.java
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
@Lazy
@Component
public clreplaced JSONMapper extends ObjectMapper {
private static final long serialVersionUID = 2883304481547670626L;
public JSONMapper() {
super();
super.registerModule(new JodaModule());
super.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
super.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false);
super.setSerializationInclusion(Include.NON_NULL);
}
}
19
Source : RuleEngineAutoConfiguration.java
with Apache License 2.0
from rule-engine
with Apache License 2.0
from rule-engine
@Lazy
@Bean
@ConditionalOnMissingBean
public RuleSetInterface ruleSetInterface() {
return this.baseInterface(RuleSetInterface.clreplaced);
}
See More Examples