Java Code Examples for org.hswebframework.utils.StringUtils#isNullOrEmpty()

The following examples show how to use org.hswebframework.utils.StringUtils#isNullOrEmpty() . 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   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
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 3
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 4
@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 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, 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 6
@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 7
@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 8
@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 9
public String getName() {
    if (StringUtils.isNullOrEmpty(name)) {
        name = type.name().concat("_").concat(field);
    }
    return name;
}
 
Example 10
public String getName() {
    if (StringUtils.isNullOrEmpty(name)) {
        name = type.name().concat("_").concat(field);
    }
    return name;
}
 
Example 11
protected Class<Entity> getClass(String basePackage, String name) {
    if (!StringUtils.isNullOrEmpty(basePackage)) {
        name = basePackage.concat(".").concat(name);
    }
    return classForName(name);
}
 
Example 12
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 13
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 14
Source Project: hsweb-framework   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 15
@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 16
@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);
}