Java Code Examples for org.hswebframework.utils.StringUtils

The following examples show how to use org.hswebframework.utils.StringUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: device-simulator   Source File: MQTTSimulator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    JSONObject jsonObject = new JSONObject();

    System.getProperties()
            .entrySet()
            .stream()
            .flatMap(e -> System.getenv().entrySet().stream())
            .filter(e -> String.valueOf(e.getKey()).startsWith("mqtt."))
            .forEach(e -> jsonObject.put(String.valueOf(e.getKey()).substring(5), e.getValue()));
    for (String arg : args) {
        String[] split = arg.split("[=]");
        jsonObject.put(split[0].startsWith("mqtt.") ? split[0].substring(5) : split[0], split.length == 2 ? split[1] : true);
    }
    String binds = jsonObject.getString("binds");
    if (!StringUtils.isNullOrEmpty(binds)) {
        jsonObject.put("binds", binds.split("[,]"));
    }
    MQTTSimulator simulator = jsonObject.toJavaObject(MQTTSimulator.class);
    simulator.clientMap = new ConcurrentHashMap<>(simulator.limit);
    System.out.println("使用配置:\n" + JSON.toJSONString(simulator, SerializerFeature.PrettyFormat));
    simulator.start();
}
 
Example 2
@PostMapping("/decode")
@SaveAction
public Mono<String> decode(@RequestBody Mono<ProtocolDecodeRequest> entity) {
    return entity
        .<Object>flatMapMany(request -> {
            ProtocolSupportDefinition supportEntity = request.getEntity().toDeployDefinition();
            supportEntity.setId("_debug");
            return supportLoader.load(supportEntity)
                .flatMapMany(protocol -> request
                    .getRequest()
                    .doDecode(protocol, null));
        })
        .collectList()
        .map(JSON::toJSONString)
        .onErrorResume(err-> Mono.just(StringUtils.throwable2String(err)));
}
 
Example 3
@PostMapping("/encode")
@SaveAction
public  Mono<String> encode(@RequestBody Mono<ProtocolEncodeRequest> entity) {
    return entity
        .flatMapMany(request -> {
            ProtocolSupportDefinition supportEntity = request.getEntity().toDeployDefinition();
            supportEntity.setId("_debug");
            return supportLoader.load(supportEntity)
                .flatMapMany(protocol -> request
                    .getRequest()
                    .doEncode(protocol, null));
        })
        .collectList()
        .map(JSON::toJSONString)
        .onErrorResume(err-> Mono.just(StringUtils.throwable2String(err)));
}
 
Example 4
Source Project: jetlinks-community   Source File: SerializableAccessLog.java    License: Apache License 2.0 6 votes vote down vote up
public static SerializableAccessLog of(AccessLoggerInfo info) {
    SerializableAccessLog accessLog = FastBeanCopier.copy(info, new SerializableAccessLog(), "parameters", "method", "target", "exception");
    accessLog.setMethod(info.getMethod().getName());
    accessLog.setTarget(info.getTarget().getName());
    accessLog.setException(info.getException() == null ? ""
            : StringUtils.throwable2String(info.getException()));
    Map<String, Object> newParameter = info.getParameters()
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> {
                Object value = e.getValue();
                if (value instanceof FilePart) {
                    return ("file:") + ((FilePart) value).filename();
                }
                return JSON.toJSONString(value);
            }));

    accessLog.setParameters(newParameter);
    return accessLog;
}
 
Example 5
public String converter(Object obj) {
        if (obj instanceof String) {
            return (String) obj;
        }
        String text;
        String callback = ThreadLocalUtils.getAndRemove("jsonp-callback");
        if (obj instanceof ResponseMessage) {
            ResponseMessage message = (ResponseMessage) obj;
//            if (dictSupportApi != null) {
//                message.setResult(dictSupportApi.wrap(message.getResult()));
//            }
            text = JSON.toJSONString(obj, parseFilter(message), features);
        } else {
//            if (dictSupportApi != null) {
//                obj = dictSupportApi.wrap(obj);
//            }
            text = JSON.toJSONString(obj, features);
        }
        if (!StringUtils.isNullOrEmpty(callback)) {
            text = new StringBuilder()
                    .append(callback)
                    .append("(").append(text).append(")")
                    .toString();
        }
        return text;
    }
 
Example 6
Source Project: hsweb-framework   Source File: ScriptDataAccessHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
    ScriptDataAccessConfig dataAccess = ((ScriptDataAccessConfig) access);
    DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(dataAccess.getScriptLanguage());
    if (engine == null) {
        throw new UnsupportedOperationException(dataAccess.getScriptLanguage() + " {not_support}");
    }
    String scriptId = DigestUtils.md5Hex(dataAccess.getScript());
    try {
        if (!engine.compiled(scriptId)) {
            engine.compile(scriptId, dataAccess.getScript());
        }
        Object success = engine.execute(scriptId, context.getParamContext().getParams()).getIfSuccess();
        return StringUtils.isTrue(success);
    } catch (Exception e) {
        throw new BusinessException("{script_error}", e);
    }
}
 
Example 7
Source Project: hsweb-framework   Source File: HttpTokenRequest.java    License: Apache License 2.0 6 votes vote down vote up
protected String[] decodeClientAuthenticationHeader(String authenticationHeader) {
    if (StringUtils.isNullOrEmpty(authenticationHeader)) {
        return null;
    } else {
        String[] tokens = authenticationHeader.split(" ");
        if (tokens.length != 2) {
            return null;
        } else {
            String authType = tokens[0];
            if (!"basic".equalsIgnoreCase(authType)) {
                return ErrorType.OTHER.throwThis(GrantTokenException::new, "authentication " + authType + " not support!");
            } else {
                String encodedCreds = tokens[1];
                return decodeBase64EncodedCredentials(encodedCreds);
            }
        }
    }
}
 
Example 8
private String createSetPropertyCode(TableMetaData tableMetaData) {
    StringBuilder builder = new StringBuilder();
    builder.append("public void setProperty(String property,Object value){\n");
    int index = 0;
    for (ColumnMetaData column : tableMetaData.getColumns()) {
        String propertyName = column.getAlias();
        Class type = column.getJavaType();
        if (index++ > 0) {
            builder.append("\nelse ");
        }
        builder.append("if(property.intern()==\"")
                .append(propertyName)
                .append("\"||property.intern()==\"")
                .append(column.getName()).append("\"){\n")
                .append("this.set")
                .append(StringUtils.toUpperCaseFirstOne(propertyName))
                .append("((").append(type.getName()).append(")")
                .append("org.hswebframework.web.bean.FastBeanCopier.DEFAULT_CONVERT.convert(value,")
                .append(type.getName())
                .append(".class,null));")
                .append("\n}");
    }
    builder.append("}");
    return builder.toString();
}
 
Example 9
private String createGetPropertyCode(TableMetaData tableMetaData) {
    StringBuilder builder = new StringBuilder();
    int index = 0;
    builder.append("public Object getProperty(String property){\n");
    for (ColumnMetaData column : tableMetaData.getColumns()) {
        String propertyName = column.getAlias();
        if (index++ > 0) {
            builder.append("\nelse ");
        }
        builder.append("if(property.intern()==\"")
                .append(propertyName)
                .append("\"||property.intern()==\"")
                .append(column.getName())
                .append("\"){\n")
                .append("return this.get")
                .append(StringUtils.toUpperCaseFirstOne(propertyName))
                .append("();")
                .append("\n}");

    }
    builder.append("\nreturn null;\n}");
    return builder.toString();
}
 
Example 10
Source Project: hsweb-framework   Source File: BpmTaskServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void claim(String taskId, String userId) {
    Task task = taskService.createTaskQuery().
            taskId(taskId)
            .taskCandidateUser(userId)
            .active()
            .singleResult();
    if (task == null) {
        throw new NotFoundException("无法签收此任务");
    }
    if (!StringUtils.isNullOrEmpty(task.getAssignee())) {
        throw new BusinessException("任务已签售");
    } else {
        taskService.claim(taskId, userId);
    }
}
 
Example 11
Source Project: jetlinks-community   Source File: NotifierEvent.java    License: Apache License 2.0 5 votes vote down vote up
public SerializableNotifierEvent toSerializable() {
    return SerializableNotifierEvent.builder()
        .success(success)
        .notifierId(notifierId)
        .notifyType(notifyType.getId())
        .provider(provider.getId())
        .templateId(templateId)
        .template(template)
        .context(context)
        .cause(cause != null ? StringUtils.throwable2String(cause) : "")
        .errorType(cause != null ? cause.getClass().getName() : null)
        .build();
}
 
Example 12
public String converter(Object obj) {
        if (obj instanceof String) {
            return (String) obj;
        }

        String text;
        String callback = ThreadLocalUtils.getAndRemove("jsonp-callback");
        if (obj instanceof ResponseMessage) {
            ResponseMessage message = (ResponseMessage) obj;
//            if (dictSupportApi != null) {
//                message.setResult(dictSupportApi.wrap(message.getResult()));
//            }
            text = JSON.toJSONString(obj, FastJsonHttpMessageConverter.parseFilter(message), features);
        } else {
//            if (dictSupportApi != null) {
//                obj = dictSupportApi.wrap(obj);
//            }
            text = JSON.toJSONString(obj, features);
        }
        if (!StringUtils.isNullOrEmpty(callback)) {
            text = new StringBuilder()
                    .append(callback)
                    .append("(").append(text).append(")")
                    .toString();
        }
        return text;
    }
 
Example 13
Source Project: hsweb-framework   Source File: SqlParamParser.java    License: Apache License 2.0 5 votes vote down vote up
private QueryParamParser parse(Object obj) {
    if (obj instanceof Map) {
        ((Map) obj).forEach((k, v) -> {
            String key = String.valueOf(k);
            if ("pageIndex".equals(key)) {
                query.getParam().setPageIndex(StringUtils.toInt(v));
            }
            if ("pageSize".equals(key)) {
                query.getParam().setPageSize(StringUtils.toInt(v));
            }
            if (v != null) {
                if (v instanceof Entity || v instanceof Map) {
                    List<Term> terms = new QueryParamParser().parse(v).get().getTerms();
                    Term term = new Term();
                    term.setType(key.equalsIgnoreCase("or") ? Term.Type.or : Term.Type.and);
                    term.setTerms(terms);
                    query.getParam().getTerms().add(term);
                } else {
                    consumer.accept(String.valueOf(key), v);
                }
            }
        });
    } else {
        parse(FastBeanCopier.copy(obj, new LinkedHashMap<>()));
    }
    return this;
}
 
Example 14
Source Project: hsweb-framework   Source File: HttpTokenRequest.java    License: Apache License 2.0 5 votes vote down vote up
public HttpTokenRequest(HttpServletRequest request) {
    this.parameters = WebUtil.getParameters(request);
    this.headers = WebUtil.getHeaders(request);
    String clientId = parameters.get(OAuth2Constants.client_id);
    String clientSecret = parameters.get(OAuth2Constants.client_secret);
    String authorization = headers.get(OAuth2Constants.authorization);
    clientCredentials = getClientCredentials(clientId, clientSecret, authorization);

    this.scope = getParameter(OAuth2Constants.scope)
            .filter(scopeStr -> !StringUtils.isNullOrEmpty(scopeStr))
            .map(scopeStr -> new HashSet<>(Arrays.asList(scopeStr.split("[, \n]"))))
            .orElseGet(HashSet::new);
}
 
Example 15
@Override
public List<DictionaryItemEntity> selectByDictId(String dictId) {
    if (StringUtils.isNullOrEmpty(dictId)) {
        return new java.util.ArrayList<>();
    }
    return createQuery()
            .where(DictionaryItemEntity.dictId, dictId)
            .orderByAsc(DictionaryItemEntity.sortIndex)
            .listNoPaging();
}
 
Example 16
Source Project: hsweb-framework   Source File: BpmTaskServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ActivityImpl selectActivityImplByTask(String taskId) {
    if (StringUtils.isNullOrEmpty(taskId)) {
        return new ActivityImpl(null, null);
    }
    Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
    ProcessDefinitionEntity entity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());
    List<ActivityImpl> activities = entity.getActivities();
    return activities
            .stream()
            .filter(activity -> "userTask".equals(activity.getProperty("type")) && activity.getProperty("name").equals(task.getName()))
            .findFirst()
            .orElseThrow(() -> new NotFoundException("获取节点信息失败"));
}
 
Example 17
Source Project: hsweb-framework   Source File: BpmTaskServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getVariablesByProcInstId(String procInstId) {
    List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(procInstId).list();
    String executionId = "";
    for (Execution execution : executions) {
        if (StringUtils.isNullOrEmpty(execution.getParentId())) {
            executionId = execution.getId();
        }
    }
    return runtimeService.getVariables(executionId);
}
 
Example 18
public String getName() {
    if (StringUtils.isNullOrEmpty(name)) {
        name = type.name().concat("_").concat(field);
    }
    return name;
}
 
Example 19
public String getName() {
    if (StringUtils.isNullOrEmpty(name)) {
        name = type.name().concat("_").concat(field);
    }
    return name;
}
 
Example 20
Source Project: hsweb-framework   Source File: EntityProperties.java    License: Apache License 2.0 4 votes vote down vote up
protected Class<Entity> getClass(String basePackage, String name) {
    if (!StringUtils.isNullOrEmpty(basePackage)) {
        name = basePackage.concat(".").concat(name);
    }
    return classForName(name);
}
 
Example 21
Source Project: hsweb-framework   Source File: SystemVersion.java    License: Apache License 2.0 4 votes vote down vote up
protected String getDepKey(String groupId, String artifactId) {
    return StringUtils.concat(groupId, "/", artifactId);
}
 
Example 22
Source Project: hsweb-framework   Source File: EasyOrmSqlBuilder.java    License: Apache License 2.0 4 votes vote down vote up
private List<RDBColumnMetaData> createColumn(String prefix, String columnName, ResultMapping resultMapping) {
    List<RDBColumnMetaData> metaData = new ArrayList<>();
    if (resultMapping.getNestedQueryId() == null) {

        if (resultMapping.getNestedResultMapId() != null) {
            ResultMap nests = MybatisUtils.getResultMap(resultMapping.getNestedResultMapId());
            Set<ResultMapping> resultMappings = new HashSet<>(nests.getResultMappings());
            resultMappings.addAll(nests.getIdResultMappings());
            for (ResultMapping mapping : resultMappings) {
                metaData.addAll(createColumn(resultMapping.getProperty(),
                        org.springframework.util.StringUtils.hasText(resultMapping.getColumn())
                                ? resultMapping.getColumn()
                                : resultMapping.getProperty(),
                        mapping));
            }
            return metaData;
        }

        JDBCType jdbcType = JDBCType.VARCHAR;
        try {
            jdbcType = JDBCType.valueOf(resultMapping.getJdbcType().name());
        } catch (Exception e) {
            log.warn("can not parse jdbcType:{}", resultMapping.getJdbcType());
        }
        RDBColumnMetaData column = new RDBColumnMetaData();
        column.setJdbcType(jdbcType);
        column.setName(org.springframework.util.StringUtils.hasText(columnName)
                ? columnName.concat(".").concat(resultMapping.getColumn()) : resultMapping.getColumn());

        if (resultMapping.getTypeHandler() != null) {
            column.setProperty("typeHandler", resultMapping.getTypeHandler().getClass().getName());
        }
        if (!StringUtils.isNullOrEmpty(resultMapping.getProperty())) {
            column.setAlias(org.springframework.util.StringUtils.hasText(prefix)
                    ? prefix.concat(".").concat(resultMapping.getProperty()) : resultMapping.getProperty());

        }
        column.setJavaType(resultMapping.getJavaType());
        column.setProperty("resultMapping", resultMapping);
        metaData.add(column);
    }
    return metaData;
}
 
Example 23
Source Project: hsweb-framework   Source File: StringSourceSettingHolder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Long> asLong() {
    return getNativeValue().map(StringUtils::toLong);
}
 
Example 24
Source Project: hsweb-framework   Source File: StringSourceSettingHolder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Integer> asInt() {
    return getNativeValue().map(StringUtils::toInt);
}
 
Example 25
Source Project: hsweb-framework   Source File: StringSourceSettingHolder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Double> asDouble() {
    return getNativeValue().map(StringUtils::toDouble);
}
 
Example 26
Source Project: hsweb-framework   Source File: HttpTokenRequest.java    License: Apache License 2.0 4 votes vote down vote up
protected String[] decodeBase64EncodedCredentials(String encodedCredentials) {
    String decodedCredentials = new String(Base64.getDecoder().decode(encodedCredentials));
    String[] credentials = decodedCredentials.split(":", 2);
    return credentials.length != 2 ? null : (!StringUtils.isNullOrEmpty(credentials[0]) && !StringUtils.isNullOrEmpty(credentials[1]) ? credentials : null);
}
 
Example 27
@Override
public Validator createValidator(TableMetaData tableMetaData) {
    Proxy<MapBean> proxy = Proxy.create(MapBean.class);
    StringBuilder keySet = new StringBuilder("public java.util.Set keySet(){\n return new java.util.HashSet(java.util.Arrays.asList(new String[]{");
    int index = 0;
    for (ColumnMetaData column : tableMetaData.getColumns()) {
        String propertyName = column.getAlias();
        Class type = column.getJavaType();
        String typeName = type.getName();

        if (index++ > 0) {
            keySet.append(",");
        }

        keySet.append("\"")
                .append(propertyName)
                .append("\"");

        proxy.custom(ctClass -> {
            try {
                CtField ctField = CtField.make("private " + type.getName() + " " + propertyName + ";", ctClass);
                List<JSR303AnnotationInfo> jsr303 = createValidatorAnnotation(column.getValidator());
                //添加注解
                if (!CollectionUtils.isEmpty(jsr303)) {
                    ConstPool constPool = ctClass.getClassFile().getConstPool();
                    AnnotationsAttribute attributeInfo = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
                    for (JSR303AnnotationInfo jsr303AnnotationInfo : jsr303) {
                        Class<? extends java.lang.annotation.Annotation> jsr303Ann = jsr303AnnotationInfo.getAnnotation();
                        Annotation ann = new javassist.bytecode.annotation.Annotation(jsr303Ann.getName(), constPool);
                        if (!CollectionUtils.isEmpty(jsr303AnnotationInfo.getProperties())) {
                            jsr303AnnotationInfo.getProperties().forEach((key, value) -> {
                                MemberValue memberValue = createMemberValue(value, constPool);
                                if (memberValue != null) {
                                    ann.addMemberValue(key, memberValue);
                                }
                            });
                        }
                        attributeInfo.addAnnotation(ann);
                    }
                    ctField.getFieldInfo().addAttribute(attributeInfo);
                }
                ctClass.addField(ctField);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        proxy.addMethod("public void set" + StringUtils.toUpperCaseFirstOne(propertyName) + "(" + typeName + " " + propertyName + "){\n" +
                "this." + propertyName + "=" + propertyName + ";\n" +
                "\n};");

        proxy.addMethod("public " + typeName + " get" + StringUtils.toUpperCaseFirstOne(propertyName) + "(){\n" +
                "return this." + propertyName + ";\n" +
                "\n};");
    }

    keySet.append("}));\n}");

    proxy.addMethod(keySet.toString());
    proxy.addMethod(createSetPropertyCode(tableMetaData));
    proxy.addMethod(createGetPropertyCode(tableMetaData));

    //尝试一下能否创建实例
    MapBean mapBean = proxy.newInstance();
    Assert.notNull(mapBean, "创建验证器失败!");
    return new DynamicBeanValidator(proxy::newInstance);
}
 
Example 28
Source Project: hsweb-framework   Source File: FileController.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 通过文件ID下载已经上传的文件,支持断点下载
 * 如: http://host:port/file/download/aSk2a/file.zip 将下载 ID为aSk2a的文件.并命名为file.zip
 *
 * @param idOrMd5  要下载资源文件的id或者md5值
 * @param name     自定义文件名,该文件名不能存在非法字符.如果此参数为空(null).将使用文件上传时的文件名
 * @param response {@link javax.servlet.http.HttpServletResponse}
 * @param request  {@link javax.servlet.http.HttpServletRequest}
 * @return 下载结果, 在下载失败时, 将返回错误信息
 * @throws IOException                              读写文件错误
 * @throws org.hswebframework.web.NotFoundException 文件不存在
 */
@GetMapping(value = "/download/{id}")
@ApiOperation("下载文件")
@Authorize(action = "download", description = "下载文件")
public void downLoad(@ApiParam("文件的id或者md5") @PathVariable("id") String idOrMd5,
                     @ApiParam(value = "文件名,如果未指定,默认为上传时的文件名", required = false) @RequestParam(value = "name", required = false) String name,
                     @ApiParam(hidden = true) HttpServletResponse response, @ApiParam(hidden = true) HttpServletRequest request)
        throws IOException {
    FileInfoEntity fileInfo = fileInfoService.selectByIdOrMd5(idOrMd5);
    if (fileInfo == null || !DataStatus.STATUS_ENABLED.equals(fileInfo.getStatus())) {
        throw new NotFoundException("文件不存在");
    }
    String fileName = fileInfo.getName();

    String suffix = fileName.contains(".") ?
            fileName.substring(fileName.lastIndexOf("."), fileName.length()) :
            "";
    //获取contentType
    String contentType = fileInfo.getType() == null ?
            MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName) :
            fileInfo.getType();
    //未自定义文件名,则使用上传时的文件名
    if (StringUtils.isNullOrEmpty(name)) {
        name = fileInfo.getName();
    }
    //如果未指定文件拓展名,则追加默认的文件拓展名
    if (!name.contains(".")) {
        name = name.concat(".").concat(suffix);
    }
    //关键字剔除
    name = fileNameKeyWordPattern.matcher(name).replaceAll("");
    int skip = 0;
    long fSize = fileInfo.getSize();
    //尝试判断是否为断点下载
    try {
        //获取要继续下载的位置
        String Range = request.getHeader("Range").replace("bytes=", "").replace("-", "");
        skip = StringUtils.toInt(Range);
    } catch (Exception ignore) {
    }
    response.setContentLength((int) fSize);//文件大小
    response.setContentType(contentType);
    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
    //断点下载
    if (skip > 0) {
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        String contentRange = "bytes " + skip + "-" + (fSize - 1) + "/" + fSize;
        response.setHeader("Content-Range", contentRange);
    }
    fileService.writeFile(idOrMd5, response.getOutputStream(), skip);
}
 
Example 29
Source Project: hsweb-framework   Source File: BpmProcessServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ProcessInstance startProcessInstance(StartProcessRequest request) {
    request.tryValidate();
    ProcessInstance processInstance;
    logger.debug("start workflow :{}", request);
    try {
        identityService.setAuthenticatedUserId(request.getCreatorId());

        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().processDefinitionId(request.getProcessDefineId())
                .singleResult();
        if (definition == null) {
            throw new NotFoundException("流程[" + request.getProcessDefineId() + "]不存在");
        }

        //创建业务ID
        String businessKey = IDGenerator.MD5.generate();

        //启动流程
        processInstance = runtimeService.startProcessInstanceById(
                request.getProcessDefineId()
                , businessKey
                , request.getVariables());

        //候选人设置
        Consumer<Task> candidateUserSetter = (task) -> {
            if (task == null) {
                return;
            }
            //指定了下一环节的办理人
            if (!StringUtils.isNullOrEmpty(request.getNextClaimUserId())) {
                taskService.addCandidateUser(task.getId(), request.getNextClaimUserId());
            } else {
                bpmTaskService.setCandidate(request.getCreatorId(), task);
            }
        };

        List<Task> tasks = bpmTaskService.selectTaskByProcessId(processInstance.getProcessDefinitionId());

        //当前节点
        String activityId = processInstance.getActivityId();
        if (activityId == null) {
            //所有task设置候选人
            tasks.forEach(candidateUserSetter);
        } else {
            candidateUserSetter.accept(taskService
                    .createTaskQuery()
                    .processInstanceId(processInstance.getProcessInstanceId())
                    .taskDefinitionKey(activityId)
                    .active()
                    .singleResult());
        }

        workFlowFormService.saveProcessForm(processInstance, SaveFormRequest
                .builder()
                .userId(request.getCreatorId())
                .userName(request.getCreatorName())
                .formData(request.getFormData())
                .build());

        ProcessHistoryEntity history = ProcessHistoryEntity.builder()
                .type("start")
                .typeText("启动流程")
                .businessKey(businessKey)
                .creatorId(request.getCreatorId())
                .creatorName(request.getCreatorName())
                .processInstanceId(processInstance.getProcessInstanceId())
                .processDefineId(processInstance.getProcessDefinitionId())
                .build();

        processHistoryService.insert(history);


    } finally {
        identityService.setAuthenticatedUserId(null);
    }
    return processInstance;
}
 
Example 30
Source Project: hsweb-framework   Source File: BpmTaskServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void complete(CompleteTaskRequest request) {
    request.tryValidate();

    Task task = taskService.createTaskQuery()
            .taskId(request.getTaskId())
            .includeProcessVariables()
            .active()
            .singleResult();

    Objects.requireNonNull(task, "任务不存在");
    String assignee = task.getAssignee();
    Objects.requireNonNull(assignee, "任务未签收");
    if (!assignee.equals(request.getCompleteUserId())) {
        throw new BusinessException("只能完成自己的任务");
    }
    Map<String, Object> variable = new HashMap<>();
    variable.put("preTaskId", task.getId());
    Map<String, Object> transientVariables = new HashMap<>();

    if (null != request.getVariables()) {
        variable.putAll(request.getVariables());
        transientVariables.putAll(request.getVariables());
    }

    ProcessInstance instance = runtimeService.createProcessInstanceQuery()
            .processInstanceId(task.getProcessInstanceId())
            .singleResult();

    //查询主表的数据作为变量
    Optional.of(workFlowFormService.<Map<String, Object>>selectProcessForm(instance.getProcessDefinitionId(),
            QueryParamEntity.of("processInstanceId", instance.getProcessInstanceId()).doPaging(0, 2)))
            .map(PagerResult::getData)
            .map(list -> {
                if (list.size() == 1) {
                    return list.get(0);
                }
                if (list.size() > 1) {
                    logger.warn("主表数据存在多条数据:processInstanceId={}", instance.getProcessInstanceId());
                }
                return null;
            })
            .ifPresent(transientVariables::putAll);


    //保存表单数据
    workFlowFormService.saveTaskForm(instance, task, SaveFormRequest.builder()
            .userName(request.getCompleteUserName())
            .userId(request.getCompleteUserId())
            .formData(request.getFormData())
            .build());

    if (null != request.getFormData()) {
        transientVariables.putAll(request.getFormData());
    }

    taskService.complete(task.getId(), null, transientVariables);

    //跳转
    if (!StringUtils.isNullOrEmpty(request.getNextActivityId())) {
        doJumpTask(task, request.getNextActivityId(), (t) -> {
        });
    }

    //下一步候选人
    List<Task> tasks = selectNowTask(task.getProcessInstanceId());
    for (Task next : tasks) {
        setVariablesLocal(next.getId(), variable);
        if (!StringUtils.isNullOrEmpty(request.getNextClaimUserId())) {
            taskService.addCandidateUser(next.getId(), request.getNextClaimUserId());
        } else {
            setCandidate(request.getCompleteUserId(), next);
        }
    }

    ProcessHistoryEntity history = ProcessHistoryEntity.builder()
            .businessKey(instance.getBusinessKey())
            .type("complete")
            .typeText("完成任务")
            .creatorId(request.getCompleteUserId())
            .creatorName(request.getCompleteUserName())
            .processDefineId(instance.getProcessDefinitionId())
            .processInstanceId(instance.getProcessInstanceId())
            .taskId(task.getId())
            .taskDefineKey(task.getTaskDefinitionKey())
            .taskName(task.getName())
            .build();

    processHistoryService.insert(history);
}