Search in sources :

Example 6 with GeneralResponse

use of com.webank.wedatasphere.qualitis.response.GeneralResponse in project Qualitis by WeBankFinTech.

the class FileRuleServiceImpl method addRuleReal.

private GeneralResponse<RuleResponse> addRuleReal(AddFileRuleRequest request, String loginUser) throws UnExpectedRequestException, PermissionDeniedRequestException {
    // Check Arguments
    AddFileRuleRequest.checkRequest(request, false);
    // Generate Template, TemplateOutputMeta and save
    Template template = ruleTemplateService.addFileTemplate(request);
    // Check existence of project
    Project projectInDb = projectService.checkProjectExistence(request.getProjectId(), loginUser);
    String nowDate = ExecutionManagerImpl.PRINT_TIME_FORMAT.format(new Date());
    // Check permissions of project
    List<Integer> permissions = new ArrayList<>();
    permissions.add(ProjectUserPermissionEnum.DEVELOPER.getCode());
    projectService.checkProjectPermission(projectInDb, loginUser, permissions);
    // Check unique of rule name
    ruleService.checkRuleName(request.getRuleName(), projectInDb, null);
    // Check cluster support
    ruleDataSourceService.checkDataSourceClusterSupport(request.getDatasource().getClusterName());
    RuleGroup ruleGroup;
    if (request.getRuleGroupId() != null) {
        ruleGroup = ruleGroupDao.findById(request.getRuleGroupId());
        if (ruleGroup == null) {
            throw new UnExpectedRequestException(String.format("Rule Group: %s {&DOES_NOT_EXIST}", request.getRuleGroupId()));
        }
    } else {
        ruleGroup = ruleGroupDao.saveRuleGroup(new RuleGroup("Group_" + UUID.randomUUID().toString().replace("-", ""), projectInDb.getId()));
    }
    // Save rule.
    Rule newRule = new Rule();
    newRule.setRuleType(RuleTypeEnum.FILE_TEMPLATE_RULE.getCode());
    newRule.setTemplate(template);
    newRule.setName(request.getRuleName());
    newRule.setCnName(request.getRuleCnName());
    newRule.setDetail(request.getRuleDetail());
    newRule.setAlarm(request.getAlarm());
    newRule.setProject(projectInDb);
    newRule.setRuleTemplateName(template.getName());
    newRule.setRuleGroup(ruleGroup);
    newRule.setAbortOnFailure(request.getAbortOnFailure());
    newRule.setCreateUser(loginUser);
    newRule.setCreateTime(nowDate);
    String csId = request.getCsId();
    boolean cs = false;
    if (StringUtils.isNotBlank(csId)) {
        newRule.setCsId(csId);
        cs = true;
    }
    Rule savedRule = ruleDao.saveRule(newRule);
    LOGGER.info("Succeed to save file rule, rule_id: {}", savedRule.getId());
    List<AlarmConfig> savedAlarmConfigs = new ArrayList<>();
    if (request.getAlarm()) {
        savedAlarmConfigs = alarmConfigService.checkAndSaveFileAlarmVariable(request.getAlarmVariable(), savedRule);
        LOGGER.info("Succeed to save alarm_configs, alarm_configs: {}", savedAlarmConfigs);
    }
    List<RuleDataSource> ruleDataSources = new ArrayList<>();
    ruleDataSources.add(ruleDataSourceService.checkAndSaveFileRuleDataSource(request.getDatasource(), savedRule, cs));
    savedRule.setAlarmConfigs(new HashSet<>(savedAlarmConfigs));
    savedRule.setRuleDataSources(new HashSet<>(ruleDataSources));
    // Update rule count of datasource
    ruleDataSourceService.updateRuleDataSourceCount(savedRule, 1);
    RuleResponse response = new RuleResponse(savedRule);
    LOGGER.info("Succeed to add file rule, rule_id: {}", savedRule.getId());
    return new GeneralResponse<>("200", "{&SUCCEED_TO_ADD_FILE_RULE}", response);
}
Also used : UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) RuleDataSource(com.webank.wedatasphere.qualitis.rule.entity.RuleDataSource) RuleResponse(com.webank.wedatasphere.qualitis.rule.response.RuleResponse) ArrayList(java.util.ArrayList) Date(java.util.Date) RuleGroup(com.webank.wedatasphere.qualitis.rule.entity.RuleGroup) Template(com.webank.wedatasphere.qualitis.rule.entity.Template) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) Project(com.webank.wedatasphere.qualitis.project.entity.Project) Rule(com.webank.wedatasphere.qualitis.rule.entity.Rule) AlarmConfig(com.webank.wedatasphere.qualitis.rule.entity.AlarmConfig)

Example 7 with GeneralResponse

use of com.webank.wedatasphere.qualitis.response.GeneralResponse in project Qualitis by WeBankFinTech.

the class MultiSourceRuleServiceImpl method getMultiSourceRule.

@Override
public GeneralResponse<MultiRuleDetailResponse> getMultiSourceRule(Long ruleId) throws UnExpectedRequestException {
    // Check existence of rule
    Rule ruleInDb = ruleDao.findById(ruleId);
    if (ruleInDb == null) {
        throw new UnExpectedRequestException("rule_id [" + ruleId + "] {&DOES_NOT_EXIST}");
    }
    if (!ruleInDb.getRuleType().equals(RuleTypeEnum.MULTI_TEMPLATE_RULE.getCode())) {
        throw new UnExpectedRequestException("rule_id: [" + ruleId + "]) {&IS_NOT_A_MULTI_TEMPLATE_RULE}");
    }
    Long projectInDbId = ruleInDb.getProject().getId();
    String loginUser = HttpUtils.getUserName(httpServletRequest);
    projectService.checkProjectExistence(projectInDbId, loginUser);
    MultiRuleDetailResponse multiRuleDetailResponse = new MultiRuleDetailResponse(ruleInDb);
    return new GeneralResponse<>("200", "{&SUCCEED_TO_GET_DETAIL_OF_MULTI_RULE}", multiRuleDetailResponse);
}
Also used : GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) MultiRuleDetailResponse(com.webank.wedatasphere.qualitis.rule.response.MultiRuleDetailResponse)

Example 8 with GeneralResponse

use of com.webank.wedatasphere.qualitis.response.GeneralResponse in project Qualitis by WeBankFinTech.

the class ProjectUserServiceImpl method getAllProjectUser.

@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = { RuntimeException.class, UnExpectedRequestException.class })
public GeneralResponse<List<ProjectUserResponse>> getAllProjectUser(Long projectId) throws UnExpectedRequestException, PermissionDeniedRequestException {
    List<ProjectUserResponse> projectUserResponses = new ArrayList<>();
    Project projectInDb = projectDao.findById(projectId);
    if (projectInDb == null) {
        throw new UnExpectedRequestException("{&PROJECT}: [ID=" + projectId + "] {&DOES_NOT_EXIST}");
    }
    String userName = HttpUtils.getUserName(httpRequest);
    List<ProjectUser> projectUsers = projectUserDao.findByProject(projectInDb);
    List<String> projectUserNames = projectUsers.stream().map(ProjectUser::getUserName).collect(Collectors.toList());
    if (!projectUserNames.contains(userName)) {
        throw new PermissionDeniedRequestException("{&HAS_NO_PERMISSION_TO_ACCESS}", 403);
    }
    for (ProjectUser currentProjectUser : projectUsers) {
        List<String> userNames = projectUserResponses.stream().map(ProjectUserResponse::getAuthorizedUser).collect(Collectors.toList());
        String currentUser = currentProjectUser.getUserName();
        if (userNames.contains(currentUser)) {
            continue;
        }
        String projectCreator = projectInDb.getCreateUser();
        ProjectUserResponse projectUserResponse = new ProjectUserResponse(projectInDb.getName(), projectCreator, currentUser);
        List<Integer> permissions = getPermissionList(projectUsers, currentUser);
        projectUserResponse.setPermissions(permissions);
        projectUserResponses.add(projectUserResponse);
    }
    return new GeneralResponse<>("200", "{&SUCCESS_TO_GET_PROJECT_USER}", projectUserResponses);
}
Also used : UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) ProjectUser(com.webank.wedatasphere.qualitis.project.entity.ProjectUser) PermissionDeniedRequestException(com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException) ArrayList(java.util.ArrayList) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) Project(com.webank.wedatasphere.qualitis.project.entity.Project) ProjectUserResponse(com.webank.wedatasphere.qualitis.project.response.ProjectUserResponse) Transactional(org.springframework.transaction.annotation.Transactional)

Example 9 with GeneralResponse

use of com.webank.wedatasphere.qualitis.response.GeneralResponse in project Qualitis by WeBankFinTech.

the class RuleQueryController method query.

@POST
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> query(RuleQueryRequest param, @Context HttpServletRequest request) {
    if (param == null) {
        param = new RuleQueryRequest();
    }
    // Get login user
    param.setUser(HttpUtils.getUserName(request));
    try {
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPage(param.getPage());
        pageRequest.setSize(param.getSize());
        PageRequest.checkRequest(pageRequest);
        DataInfo<RuleQueryDataSource> results = new DataInfo<>();
        List<RuleQueryDataSource> ruleQueryDataSources = ruleQueryService.filter(pageRequest, param.getUser(), param.getCluster(), param.getDb(), param.getTable(), false);
        results.setContent(ruleQueryDataSources);
        List<RuleQueryDataSource> allRuleDataSource = ruleQueryService.filter(null, param.getUser(), param.getCluster(), param.getDb(), param.getTable(), true);
        results.setTotalCount(allRuleDataSource == null ? 0 : allRuleDataSource.size());
        LOG.info("[My DataSource] Query successfully. The number of results:{}", allRuleDataSource == null ? 0 : allRuleDataSource.size());
        return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
    } catch (Exception e) {
        LOG.error("[My DataSource] Query failed, internal error.", e);
        return new GeneralResponse<>("500", e.getMessage(), null);
    }
}
Also used : DataInfo(com.webank.wedatasphere.qualitis.metadata.response.DataInfo) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) PageRequest(com.webank.wedatasphere.qualitis.request.PageRequest) RuleQueryRequest(com.webank.wedatasphere.qualitis.query.request.RuleQueryRequest) RuleQueryDataSource(com.webank.wedatasphere.qualitis.query.response.RuleQueryDataSource) MetaDataAcquireFailedException(com.webank.wedatasphere.qualitis.metadata.exception.MetaDataAcquireFailedException) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 10 with GeneralResponse

use of com.webank.wedatasphere.qualitis.response.GeneralResponse in project Qualitis by WeBankFinTech.

the class AddRuleRequestBuilder method solveDatasource.

private void solveDatasource(String datasource) throws UnExpectedRequestException, MetaDataAcquireFailedException {
    List<DataSourceRequest> dataSourceRequests = new ArrayList<>(1);
    List<DataSourceColumnRequest> dataSourceColumnRequests = new ArrayList<>(1);
    DataSourceRequest dataSourceRequest = new DataSourceRequest();
    String clusterName;
    String database;
    String table;
    String col;
    String filter;
    String[] datasourceStrs = datasource.split(SpecCharEnum.COLON.getValue());
    if (datasourceStrs.length > TWO) {
        throw new UnExpectedRequestException("Datasource param is illegle");
    }
    String dbAndTable = datasourceStrs[0];
    String dataSourceId = "";
    Matcher matcherId = DATA_SOURCE_ID.matcher(dbAndTable.toUpperCase());
    String dataSourceName = "";
    Matcher matcherName = DATA_SOURCE_NAME.matcher(dbAndTable.toUpperCase());
    while (matcherId.find()) {
        String group = matcherId.group();
        dataSourceId = group.replace(".(", "").replace(")", "").split("=")[1];
        int startIndex = dbAndTable.toUpperCase().indexOf(group);
        String replaceStr = dbAndTable.substring(startIndex, startIndex + group.length());
        dbAndTable = dbAndTable.replace(replaceStr, "");
    }
    if (StringUtils.isBlank(dataSourceId)) {
        while (matcherName.find()) {
            String group = matcherName.group();
            int startIndex = dbAndTable.toUpperCase().indexOf(group);
            String replaceStr = dbAndTable.substring(startIndex, startIndex + group.length());
            dataSourceName = replaceStr.replace(".(", "").replace(")", "").split("=")[1];
            dbAndTable = dbAndTable.replace(replaceStr, "");
        }
    }
    String[] datasources = dbAndTable.split(SpecCharEnum.PERIOD.getValue());
    filter = datasourceStrs[1];
    if (datasources.length != FOUR && datasources.length != THREE) {
        throw new UnExpectedRequestException("Datasource param is illegle");
    }
    clusterName = datasources[0];
    database = datasources[1];
    table = datasources[2];
    col = datasources.length >= FOUR ? datasources[3] : "";
    List<ColumnInfoDetail> cols = metaDataClient.getColumnInfo(clusterName, database, table, userName);
    if (StringUtils.isNotBlank(dataSourceId)) {
        LOGGER.info("Find data source connect. Data source ID: " + dataSourceId);
        dataSourceRequest.setLinkisDataSourceId(Long.parseLong(dataSourceId));
        GeneralResponse<Map> response = metaDataClient.getDataSourceInfoDetail(clusterName, userName, dataSourceRequest.getLinkisDataSourceId(), null);
        cols = metaDataClient.getColumnsByDataSource(clusterName, userName, dataSourceRequest.getLinkisDataSourceId(), database, table).getContent();
        Map dataSourceInfo = ((Map) response.getData().get("info"));
        String dataSourceInfoName = (String) dataSourceInfo.get("dataSourceName");
        String dataSourceInfoType = (String) ((Map) dataSourceInfo.get("dataSourceType")).get("name");
        dataSourceRequest.setLinkisDataSourceName(dataSourceInfoName);
        dataSourceRequest.setLinkisDataSourceType(dataSourceInfoType);
    } else if (StringUtils.isNotBlank(dataSourceName)) {
        LOGGER.info("Find data source connect. Data source name: " + dataSourceName);
        GeneralResponse<Map> response = metaDataClient.getDataSourceInfoDetailByName(clusterName, userName, dataSourceName);
        Map dataSourceInfo = ((Map) response.getData().get("info"));
        String dataSourceInfoName = (String) dataSourceInfo.get("dataSourceName");
        String dataSourceInfoType = (String) ((Map) dataSourceInfo.get("dataSourceType")).get("name");
        Integer currentDataSourceId = (Integer) dataSourceInfo.get("id");
        dataSourceRequest.setLinkisDataSourceId(currentDataSourceId.longValue());
        cols = metaDataClient.getColumnsByDataSource(clusterName, userName, currentDataSourceId.longValue(), database, table).getContent();
        dataSourceRequest.setLinkisDataSourceName(dataSourceInfoName);
        dataSourceRequest.setLinkisDataSourceType(dataSourceInfoType);
    }
    // For one or more fields
    if (StringUtils.isBlank(col)) {
        LOGGER.info("Table count check.");
    } else {
        boolean blackList = false;
        List<String> colsInDatasource = new ArrayList<>();
        if (col.startsWith(SpecCharEnum.MINUS.getValue())) {
            blackList = true;
            col = col.replace(SpecCharEnum.MINUS.getValue(), "");
        }
        if (col.contains(SpecCharEnum.LEFT_BRACKET.getValue()) && col.contains(SpecCharEnum.RIGHT_BRACKET.getValue())) {
            col = col.replace(SpecCharEnum.LEFT_BRACKET.getValue(), "").replace(SpecCharEnum.RIGHT_BRACKET.getValue(), "");
            for (String currentCol : col.split(SpecCharEnum.COMMA.getValue())) {
                colsInDatasource.add(currentCol);
            }
        } else {
            colsInDatasource.add(col);
        }
        if (blackList) {
            for (ColumnInfoDetail columnInfoDetail : cols) {
                if (colsInDatasource.contains(columnInfoDetail.getFieldName())) {
                    continue;
                } else {
                    DataSourceColumnRequest dataSourceColumnRequest = new DataSourceColumnRequest(columnInfoDetail.getFieldName(), columnInfoDetail.getDataType());
                    dataSourceColumnRequests.add(dataSourceColumnRequest);
                }
            }
        } else {
            for (String colName : colsInDatasource) {
                String type = cols.stream().filter(field -> field.getFieldName().equals(colName)).map(ColumnInfoDetail::getDataType).collect(Collectors.joining());
                DataSourceColumnRequest dataSourceColumnRequest = new DataSourceColumnRequest(colName, type);
                dataSourceColumnRequests.add(dataSourceColumnRequest);
            }
        }
        dataSourceRequest.setBlackList(blackList);
    }
    dataSourceRequest.setClusterName(clusterName);
    dataSourceRequest.setDbName(database);
    dataSourceRequest.setTableName(table);
    dataSourceRequest.setColNames(dataSourceColumnRequests);
    dataSourceRequest.setFilter(filter);
    dataSourceRequest.setProxyUser(userName);
    dataSourceRequests.add(dataSourceRequest);
    this.addRuleRequest.setDatasource(dataSourceRequests);
}
Also used : DataSourceRequest(com.webank.wedatasphere.qualitis.rule.request.DataSourceRequest) DataSourceColumnRequest(com.webank.wedatasphere.qualitis.rule.request.DataSourceColumnRequest) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) ColumnInfoDetail(com.webank.wedatasphere.qualitis.metadata.response.column.ColumnInfoDetail) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

GeneralResponse (com.webank.wedatasphere.qualitis.response.GeneralResponse)146 UnExpectedRequestException (com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException)96 Transactional (org.springframework.transaction.annotation.Transactional)49 ArrayList (java.util.ArrayList)48 User (com.webank.wedatasphere.qualitis.entity.User)40 GetAllResponse (com.webank.wedatasphere.qualitis.response.GetAllResponse)30 Project (com.webank.wedatasphere.qualitis.project.entity.Project)28 Map (java.util.Map)27 ClusterInfo (com.webank.wedatasphere.qualitis.entity.ClusterInfo)26 MetaDataAcquireFailedException (com.webank.wedatasphere.qualitis.metadata.exception.MetaDataAcquireFailedException)24 List (java.util.List)22 Rule (com.webank.wedatasphere.qualitis.rule.entity.Rule)21 PermissionDeniedRequestException (com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException)17 IOException (java.io.IOException)16 UserRole (com.webank.wedatasphere.qualitis.entity.UserRole)15 Date (java.util.Date)15 Task (com.webank.wedatasphere.qualitis.entity.Task)14 JSONObject (org.json.JSONObject)14 HttpEntity (org.springframework.http.HttpEntity)14 HttpHeaders (org.springframework.http.HttpHeaders)14