repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
2929004360/ruoyi-sign
1,838
ruoyi-flowable/src/main/java/com/ruoyi/flowable/subscription/PendingApprovalTemplate.java
package com.ruoyi.flowable.subscription; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; import me.chanjar.weixin.common.error.WxErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; /** * 待审批通知模板 * * @author fengcheng */ @Component public class PendingApprovalTemplate { /** * 待审批通知模板id */ @Value("${wx.pendingApprovalId}") private String pendingApprovalId; @Lazy @Autowired private WxMaService wxMaService; /** * 发送待审批通知 * * @param openid 接收人 * @param deptName 申请部门 * @param userName 申请人 * @param riskArea 隐患区域 * @param createTime 发起时间 * @param schedule 审批进度 * @return */ public void sending(String openid,String deptName, String userName, String riskArea, String createTime, String schedule) throws WxErrorException { List<WxMaSubscribeMessage.MsgData> msgData = Arrays.asList( new WxMaSubscribeMessage.MsgData("thing8", deptName), new WxMaSubscribeMessage.MsgData("name1", userName), new WxMaSubscribeMessage.MsgData("thing76", riskArea), new WxMaSubscribeMessage.MsgData("time72", createTime), new WxMaSubscribeMessage.MsgData("phrase32", schedule) ); WxMaSubscribeMessage message = WxMaSubscribeMessage.builder() .toUser(openid) .templateId(pendingApprovalId) .data(msgData) .build(); wxMaService.getMsgService().sendSubscribeMsg(message); } }
2929004360/ruoyi-sign
1,949
ruoyi-flowable/src/main/java/com/ruoyi/flowable/subscription/ApprovalResultTemplate.java
package com.ruoyi.flowable.subscription; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; import me.chanjar.weixin.common.error.WxErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; /** * 审批结果通知模板 * * @author fengcheng */ @Component public class ApprovalResultTemplate { /** * 审批结果通知模板id */ @Value("${wx.approvalResultId}") private String approvalResultId; @Lazy @Autowired private WxMaService wxMaService; /** * 发送审批结果通知 * * @param openid 接收人 * @param approver 审批人 * @param approvalResult 审批结果 * @param approvalInstructions 审批意见 * @param approvalTime 审批时间 * @param remark 备注 * @throws WxErrorException */ public void sending(String openid, String approver, String approvalResult, String approvalInstructions, String approvalTime, String remark) throws WxErrorException { List<WxMaSubscribeMessage.MsgData> msgData = Arrays.asList( new WxMaSubscribeMessage.MsgData("name2", approver), new WxMaSubscribeMessage.MsgData("phrase1", approvalResult), new WxMaSubscribeMessage.MsgData("thing11", approvalInstructions), new WxMaSubscribeMessage.MsgData("time26", approvalTime), new WxMaSubscribeMessage.MsgData("thing20", remark) ); WxMaSubscribeMessage message = WxMaSubscribeMessage.builder() .toUser(openid) .templateId(approvalResultId) .data(msgData) .build(); wxMaService.getMsgService().sendSubscribeMsg(message); } }
2929004360/ruoyi-sign
5,416
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/BeanCopyUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.SimpleCache; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.springframework.cglib.beans.BeanCopier; import org.springframework.cglib.beans.BeanMap; import org.springframework.cglib.core.Converter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * bean深拷贝工具(基于 cglib 性能优异) * <p> * 重点 cglib 不支持 拷贝到链式对象 * 例如: 源对象 拷贝到 目标(链式对象) * 请区分好`浅拷贝`和`深拷贝`再做使用 * * @author fengcheng */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class BeanCopyUtils { /** * 单对象基于class创建拷贝 * * @param source 数据来源实体 * @param desc 描述对象 转换后的对象 * @return desc */ public static <T, V> V copy(T source, Class<V> desc) { if (ObjectUtil.isNull(source)) { return null; } if (ObjectUtil.isNull(desc)) { return null; } final V target = ReflectUtil.newInstanceIfPossible(desc); return copy(source, target); } /** * 单对象基于对象创建拷贝 * * @param source 数据来源实体 * @param desc 转换后的对象 * @return desc */ public static <T, V> V copy(T source, V desc) { if (ObjectUtil.isNull(source)) { return null; } if (ObjectUtil.isNull(desc)) { return null; } BeanCopier beanCopier = BeanCopierCache.INSTANCE.get(source.getClass(), desc.getClass(), null); beanCopier.copy(source, desc, null); return desc; } /** * 列表对象基于class创建拷贝 * * @param sourceList 数据来源实体列表 * @param desc 描述对象 转换后的对象 * @return desc */ public static <T, V> List<V> copyList(List<T> sourceList, Class<V> desc) { if (ObjectUtil.isNull(sourceList)) { return null; } if (CollUtil.isEmpty(sourceList)) { return CollUtil.newArrayList(); } return StreamUtils.toList(sourceList, source -> { V target = ReflectUtil.newInstanceIfPossible(desc); copy(source, target); return target; }); } /** * bean拷贝到map * * @param bean 数据来源实体 * @return map对象 */ @SuppressWarnings("unchecked") public static <T> Map<String, Object> copyToMap(T bean) { if (ObjectUtil.isNull(bean)) { return null; } return BeanMap.create(bean); } /** * map拷贝到bean * * @param map 数据来源 * @param beanClass bean类 * @return bean对象 */ public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) { if (MapUtil.isEmpty(map)) { return null; } if (ObjectUtil.isNull(beanClass)) { return null; } T bean = ReflectUtil.newInstanceIfPossible(beanClass); return mapToBean(map, bean); } /** * map拷贝到bean * * @param map 数据来源 * @param bean bean对象 * @return bean对象 */ public static <T> T mapToBean(Map<String, Object> map, T bean) { if (MapUtil.isEmpty(map)) { return null; } if (ObjectUtil.isNull(bean)) { return null; } BeanMap.create(bean).putAll(map); return bean; } /** * map拷贝到map * * @param map 数据来源 * @param clazz 返回的对象类型 * @return map对象 */ public static <T, V> Map<String, V> mapToMap(Map<String, T> map, Class<V> clazz) { if (MapUtil.isEmpty(map)) { return null; } if (ObjectUtil.isNull(clazz)) { return null; } Map<String, V> copyMap = new LinkedHashMap<>(map.size()); map.forEach((k, v) -> copyMap.put(k, copy(v, clazz))); return copyMap; } /** * BeanCopier属性缓存<br> * 缓存用于防止多次反射造成的性能问题 * * @author Looly * @since 5.4.1 */ public enum BeanCopierCache { /** * BeanCopier属性缓存单例 */ INSTANCE; private final SimpleCache<String, BeanCopier> cache = new SimpleCache<>(); /** * 获得类与转换器生成的key在{@link BeanCopier}的Map中对应的元素 * * @param srcClass 源Bean的类 * @param targetClass 目标Bean的类 * @param converter 转换器 * @return Map中对应的BeanCopier */ public BeanCopier get(Class<?> srcClass, Class<?> targetClass, Converter converter) { final String key = genKey(srcClass, targetClass, converter); return cache.get(key, () -> BeanCopier.create(srcClass, targetClass, converter != null)); } /** * 获得类与转换器生成的key * * @param srcClass 源Bean的类 * @param targetClass 目标Bean的类 * @param converter 转换器 * @return 属性名和Map映射的key */ private String genKey(Class<?> srcClass, Class<?> targetClass, Converter converter) { final StringBuilder key = StrUtil.builder() .append(srcClass.getName()).append('#').append(targetClass.getName()); if (null != converter) { key.append('#').append(converter.getClass().getName()); } return key.toString(); } } }
281677160/openwrt-package
2,877
luci-app-mentohust/root/etc/init.d/mentohust
#!/bin/sh /etc/rc.common START=93 run_mentohust() { local enable local username local password local ifname local cmd config_get_bool enable $1 enable config_get username $1 username config_get password $1 password config_get ifname $1 ifname if [ $enable ] && [ $username ] && [ $password ] && [ $ifname ]; then local pinghost local startmode local dhcpmode local ipaddr local mask local gateway local dns local timeout local echointerval local restartwait local shownotify local version local datafile local dhcpscript config_get pinghost $1 pinghost config_get startmode $1 startmode config_get dhcpmode $1 dhcpmode config_get ipaddr $1 ipaddr config_get mask $1 mask config_get gateway $1 gateway config_get dns $1 dns config_get timeout $1 timeout config_get echointerval $1 echointerval config_get restartwait $1 restartwait config_get shownotify $1 shownotify config_get version $1 version config_get datafile $1 datafile config_get dhcpscript $1 dhcpscript if [ "$ipaddr" != "" ]; then cmd=$cmd" -i"$ipaddr;fi if [ "$mask" != "" ]; then cmd=$cmd" -m"$mask;fi if [ "$pinghost" != "0.0.0.0" ] && [ "$pinghost" != "" ]; then cmd=$cmd" -o"$pinghost;fi if [ "$startmode" != "0" ] && [ "$startmode" != "" ]; then cmd=$cmd" -a"$startmode;fi if [ "$dhcpmode" != "0" ] && [ "$dhcpmode" != "" ]; then cmd=$cmd" -d"$dhcpmode;fi if [ "$gateway" != "0.0.0.0" ] && [ "$gateway" != "" ]; then cmd=$cmd" -g"$gateway;fi if [ "$dns" != "0.0.0.0" ] && [ "$dns" != "" ]; then cmd=$cmd" -s"$dns;fi if [ "$timeout" != "8" ] && [ "$timeout" != "" ]; then cmd=$cmd" -t"$timeout;fi if [ "$echointerval" != "30" ] && [ "$echointerval" != "" ]; then cmd=$cmd" -e"$echointerval;fi if [ "$restartwait" != "15" ] && [ "$restartwait" != "" ]; then cmd=$cmd" -r"$restartwait;fi if [ "$shownotify" != "5" ] && [ "$shownotify" != "" ]; then cmd=$cmd" -y"$shownotify;fi if [ "$version" != "0.00" ] && [ "$version" != "" ]; then cmd=$cmd" -v"$version;fi if [ "$datafile" != "/etc/mentohust/" ] && [ "$datafile" != "" ]; then cmd=$cmd" -f"$datafile;fi if [ "$dhcpscript" != "udhcpc -i" ] && [ "$dhcpscript" != "" ]; then cmd=$cmd" -c'"$dhcpscript"'";fi /bin/ash -c "mentohust -u$username -p$password -n$ifname -b3 -w $cmd" else /bin/ash -c "mentohust -k" fi } start() { config_load mentohust config_foreach run_mentohust mentohust } stop() { killall mentohust } restart() { mentohust -k sleep 1 config_load mentohust config_foreach run_mentohust mentohust }
2929004360/ruoyi-sign
1,468
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/ProcessFormUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.convert.Convert; import com.ruoyi.flowable.core.FormConf; import java.util.List; import java.util.Map; /** * 流程表单工具类 * * @author fengcheng * @createTime 2022/8/7 17:09 */ public class ProcessFormUtils { private static final String CONFIG = "__config__"; private static final String MODEL = "__vModel__"; /** * 填充表单项内容 * * @param formConf 表单配置信息 * @param data 表单内容 */ public static void fillFormData(FormConf formConf, Map<String, Object> data) { for (Map<String, Object> field : formConf.getFields()) { recursiveFillField(field, data); } } @SuppressWarnings("unchecked") private static void recursiveFillField(final Map<String, Object> field, final Map<String, Object> data) { if (!field.containsKey(CONFIG)) { return; } Map<String, Object> configMap = (Map<String, Object>) field.get(CONFIG); if (configMap.containsKey("children")) { List<Map<String, Object>> childrens = (List<Map<String, Object>>) configMap.get("children"); for (Map<String, Object> children : childrens) { recursiveFillField(children, data); } } String modelKey = Convert.toStr(field.get(MODEL)); Object value = data.get(modelKey); if (value != null) { configMap.put("defaultValue", value); } } }
2929004360/ruoyi-sign
1,124
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/TaskUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.constant.TaskConstants; import java.util.ArrayList; import java.util.List; /** * 工作流任务工具类 * * @author fengcheng * @createTime 2022/4/24 12:42 */ public class TaskUtils { public static String getUserId() { return String.valueOf(SecurityUtils.getUserId()); } /** * 获取用户组信息 * * @return candidateGroup */ public static List<String> getCandidateGroup() { List<String> list = new ArrayList<>(); SysUser user = SecurityUtils.getLoginUser().getUser(); if (ObjectUtil.isNotNull(user)) { if (ObjectUtil.isNotEmpty(user.getRoles())) { user.getRoles().forEach(role -> list.add(TaskConstants.ROLE_GROUP_PREFIX + role.getRoleId())); } if (ObjectUtil.isNotNull(user.getDeptId())) { list.add(TaskConstants.DEPT_GROUP_PREFIX + user.getDeptId()); } } return list; } }
2929004360/ruoyi-sign
8,064
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/StreamUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.map.MapUtil; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * stream 流工具类 * * @author fengcheng */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class StreamUtils { /** * 将collection过滤 * * @param collection 需要转化的集合 * @param function 过滤方法 * @return 过滤后的list */ public static <E> List<E> filter(Collection<E> collection, Predicate<E> function) { if (CollUtil.isEmpty(collection)) { return CollUtil.newArrayList(); } return collection.stream().filter(function).collect(Collectors.toList()); } /** * 将collection拼接 * * @param collection 需要转化的集合 * @param function 拼接方法 * @return 拼接后的list */ public static <E> String join(Collection<E> collection, Function<E, String> function) { return join(collection, function, StringUtils.SEPARATOR); } /** * 将collection拼接 * * @param collection 需要转化的集合 * @param function 拼接方法 * @param delimiter 拼接符 * @return 拼接后的list */ public static <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) { if (CollUtil.isEmpty(collection)) { return StringUtils.EMPTY; } return collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter)); } /** * 将collection排序 * * @param collection 需要转化的集合 * @param comparing 排序方法 * @return 排序后的list */ public static <E> List<E> sorted(Collection<E> collection, Comparator<E> comparing) { if (CollUtil.isEmpty(collection)) { return CollUtil.newArrayList(); } return collection.stream().sorted(comparing).collect(Collectors.toList()); } /** * 将collection转化为类型不变的map<br> * <B>{@code Collection<V> ----> Map<K,V>}</B> * * @param collection 需要转化的集合 * @param key V类型转化为K类型的lambda方法 * @param <V> collection中的泛型 * @param <K> map中的key类型 * @return 转化后的map */ public static <V, K> Map<K, V> toIdentityMap(Collection<V> collection, Function<V, K> key) { if (CollUtil.isEmpty(collection)) { return MapUtil.newHashMap(); } return collection.stream().collect(Collectors.toMap(key, Function.identity(), (l, r) -> l)); } /** * 将Collection转化为map(value类型与collection的泛型不同)<br> * <B>{@code Collection<E> -----> Map<K,V> }</B> * * @param collection 需要转化的集合 * @param key E类型转化为K类型的lambda方法 * @param value E类型转化为V类型的lambda方法 * @param <E> collection中的泛型 * @param <K> map中的key类型 * @param <V> map中的value类型 * @return 转化后的map */ public static <E, K, V> Map<K, V> toMap(Collection<E> collection, Function<E, K> key, Function<E, V> value) { if (CollUtil.isEmpty(collection)) { return MapUtil.newHashMap(); } return collection.stream().collect(Collectors.toMap(key, value, (l, r) -> l)); } /** * 将collection按照规则(比如有相同的班级id)分类成map<br> * <B>{@code Collection<E> -------> Map<K,List<E>> } </B> * * @param collection 需要分类的集合 * @param key 分类的规则 * @param <E> collection中的泛型 * @param <K> map中的key类型 * @return 分类后的map */ public static <E, K> Map<K, List<E>> groupByKey(Collection<E> collection, Function<E, K> key) { if (CollUtil.isEmpty(collection)) { return MapUtil.newHashMap(); } return collection .stream() .collect(Collectors.groupingBy(key, LinkedHashMap::new, Collectors.toList())); } /** * 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br> * <B>{@code Collection<E> ---> Map<T,Map<U,List<E>>> } </B> * * @param collection 需要分类的集合 * @param key1 第一个分类的规则 * @param key2 第二个分类的规则 * @param <E> 集合元素类型 * @param <K> 第一个map中的key类型 * @param <U> 第二个map中的key类型 * @return 分类后的map */ public static <E, K, U> Map<K, Map<U, List<E>>> groupBy2Key(Collection<E> collection, Function<E, K> key1, Function<E, U> key2) { if (CollUtil.isEmpty(collection)) { return MapUtil.newHashMap(); } return collection .stream() .collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.groupingBy(key2, LinkedHashMap::new, Collectors.toList()))); } /** * 将collection按照两个规则(比如有相同的年级id,班级id)分类成双层map<br> * <B>{@code Collection<E> ---> Map<T,Map<U,E>> } </B> * * @param collection 需要分类的集合 * @param key1 第一个分类的规则 * @param key2 第二个分类的规则 * @param <T> 第一个map中的key类型 * @param <U> 第二个map中的key类型 * @param <E> collection中的泛型 * @return 分类后的map */ public static <E, T, U> Map<T, Map<U, E>> group2Map(Collection<E> collection, Function<E, T> key1, Function<E, U> key2) { if (CollUtil.isEmpty(collection) || key1 == null || key2 == null) { return MapUtil.newHashMap(); } return collection .stream() .collect(Collectors.groupingBy(key1, LinkedHashMap::new, Collectors.toMap(key2, Function.identity(), (l, r) -> l))); } /** * 将collection转化为List集合,但是两者的泛型不同<br> * <B>{@code Collection<E> ------> List<T> } </B> * * @param collection 需要转化的集合 * @param function collection中的泛型转化为list泛型的lambda表达式 * @param <E> collection中的泛型 * @param <T> List中的泛型 * @return 转化后的list */ public static <E, T> List<T> toList(Collection<E> collection, Function<E, T> function) { if (CollUtil.isEmpty(collection)) { return CollUtil.newArrayList(); } return collection .stream() .map(function) .filter(Objects::nonNull) .collect(Collectors.toList()); } /** * 将collection转化为Set集合,但是两者的泛型不同<br> * <B>{@code Collection<E> ------> Set<T> } </B> * * @param collection 需要转化的集合 * @param function collection中的泛型转化为set泛型的lambda表达式 * @param <E> collection中的泛型 * @param <T> Set中的泛型 * @return 转化后的Set */ public static <E, T> Set<T> toSet(Collection<E> collection, Function<E, T> function) { if (CollUtil.isEmpty(collection) || function == null) { return CollUtil.newHashSet(); } return collection .stream() .map(function) .filter(Objects::nonNull) .collect(Collectors.toSet()); } /** * 合并两个相同key类型的map * * @param map1 第一个需要合并的 map * @param map2 第二个需要合并的 map * @param merge 合并的lambda,将key value1 value2合并成最终的类型,注意value可能为空的情况 * @param <K> map中的key类型 * @param <X> 第一个 map的value类型 * @param <Y> 第二个 map的value类型 * @param <V> 最终map的value类型 * @return 合并后的map */ public static <K, X, Y, V> Map<K, V> merge(Map<K, X> map1, Map<K, Y> map2, BiFunction<X, Y, V> merge) { if (MapUtil.isEmpty(map1) && MapUtil.isEmpty(map2)) { return MapUtil.newHashMap(); } else if (MapUtil.isEmpty(map1)) { map1 = MapUtil.newHashMap(); } else if (MapUtil.isEmpty(map2)) { map2 = MapUtil.newHashMap(); } Set<K> key = new HashSet<>(); key.addAll(map1.keySet()); key.addAll(map2.keySet()); Map<K, V> map = new HashMap<>(16); for (K t : key) { X x = map1.get(t); Y y = map2.get(t); V z = merge.apply(x, y); if (z != null) { map.put(t, z); } } return map; } }
2929004360/ruoyi-sign
3,341
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/JsonUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.lang.Dict; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import com.ruoyi.common.utils.spring.SpringUtils; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * JSON 工具类 * * @author fengcheng */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class JsonUtils { private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class); public static ObjectMapper getObjectMapper() { return OBJECT_MAPPER; } public static String toJsonString(Object object) { if (ObjectUtil.isNull(object)) { return null; } try { return OBJECT_MAPPER.writeValueAsString(object); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } public static <T> T parseObject(String text, Class<T> clazz) { if (StringUtils.isEmpty(text)) { return null; } try { return OBJECT_MAPPER.readValue(text, clazz); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T parseObject(byte[] bytes, Class<T> clazz) { if (ArrayUtil.isEmpty(bytes)) { return null; } try { return OBJECT_MAPPER.readValue(bytes, clazz); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T parseObject(String text, TypeReference<T> typeReference) { if (StringUtils.isBlank(text)) { return null; } try { return OBJECT_MAPPER.readValue(text, typeReference); } catch (IOException e) { throw new RuntimeException(e); } } public static Dict parseMap(String text) { if (StringUtils.isBlank(text)) { return null; } try { return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class)); } catch (MismatchedInputException e) { // 类型不匹配说明不是json return null; } catch (IOException e) { throw new RuntimeException(e); } } public static List<Dict> parseArrayMap(String text) { if (StringUtils.isBlank(text)) { return null; } try { return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class)); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> List<T> parseArray(String text, Class<T> clazz) { if (StringUtils.isEmpty(text)) { return new ArrayList<>(); } try { return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); } catch (IOException e) { throw new RuntimeException(e); } } }
2929004360/ruoyi-sign
11,820
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/ModelUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.*; import org.flowable.common.engine.impl.util.io.StringStreamSource; import java.util.*; /** * @author fengcheng */ public class ModelUtils { private static final BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter(); /** * xml转bpmnModel对象 * * @param xml xml * @return bpmnModel对象 */ public static BpmnModel getBpmnModel(String xml) { return bpmnXMLConverter.convertToBpmnModel(new StringStreamSource(xml), false, false); } /** * bpmnModel转xml字符串 * * @deprecated 存在会丢失 bpmn 连线问题 * @param bpmnModel bpmnModel对象 * @return xml字符串 */ @Deprecated public static String getBpmnXmlStr(BpmnModel bpmnModel) { return StrUtil.utf8Str(getBpmnXml(bpmnModel)); } /** * bpmnModel转xml对象 * * @deprecated 存在丢失 bpmn 连线问题 * @param bpmnModel bpmnModel对象 * @return xml */ @Deprecated public static byte[] getBpmnXml(BpmnModel bpmnModel) { return bpmnXMLConverter.convertToXML(bpmnModel); } /** * 根据节点,获取入口连线 * * @param source 起始节点 * @return 入口连线列表 */ public static List<SequenceFlow> getElementIncomingFlows(FlowElement source) { List<SequenceFlow> sequenceFlows = new ArrayList<>(); if (source instanceof FlowNode) { sequenceFlows = ((FlowNode) source).getIncomingFlows(); } return sequenceFlows; } /** * 根据节点,获取出口连线 * * @param source 起始节点 * @return 出口连线列表 */ public static List<SequenceFlow> getElementOutgoingFlows(FlowElement source) { List<SequenceFlow> sequenceFlows = new ArrayList<>(); if (source instanceof FlowNode) { sequenceFlows = ((FlowNode) source).getOutgoingFlows(); } return sequenceFlows; } /** * 获取开始节点 * * @param model bpmnModel对象 * @return 开始节点(未找到开始节点,返回null) */ public static StartEvent getStartEvent(BpmnModel model) { Process process = model.getMainProcess(); FlowElement startElement = process.getInitialFlowElement(); if (startElement instanceof StartEvent) { return (StartEvent) startElement; } return getStartEvent(process.getFlowElements()); } /** * 获取开始节点 * * @param flowElements 流程元素集合 * @return 开始节点(未找到开始节点,返回null) */ public static StartEvent getStartEvent(Collection<FlowElement> flowElements) { for (FlowElement flowElement : flowElements) { if (flowElement instanceof StartEvent) { return (StartEvent) flowElement; } } return null; } /** * 获取结束节点 * * @param model bpmnModel对象 * @return 结束节点(未找到开始节点,返回null) */ public static EndEvent getEndEvent(BpmnModel model) { Process process = model.getMainProcess(); return getEndEvent(process.getFlowElements()); } /** * 获取结束节点 * * @param flowElements 流程元素集合 * @return 结束节点(未找到开始节点,返回null) */ public static EndEvent getEndEvent(Collection<FlowElement> flowElements) { for (FlowElement flowElement : flowElements) { if (flowElement instanceof EndEvent) { return (EndEvent) flowElement; } } return null; } public static UserTask getUserTaskByKey(BpmnModel model, String taskKey) { Process process = model.getMainProcess(); FlowElement flowElement = process.getFlowElement(taskKey); if (flowElement instanceof UserTask) { return (UserTask) flowElement; } return null; } /** * 获取流程元素信息 * * @param model bpmnModel对象 * @param flowElementId 元素ID * @return 元素信息 */ public static FlowElement getFlowElementById(BpmnModel model, String flowElementId) { Process process = model.getMainProcess(); return process.getFlowElement(flowElementId); } /** * 获取元素表单Key(限开始节点和用户节点可用) * * @param flowElement 元素 * @return 表单Key */ public static String getFormKey(FlowElement flowElement) { if (flowElement != null) { if (flowElement instanceof StartEvent) { return ((StartEvent) flowElement).getFormKey(); } else if (flowElement instanceof UserTask) { return ((UserTask) flowElement).getFormKey(); } } return null; } /** * 获取开始节点属性值 * @param model bpmnModel对象 * @param name 属性名 * @return 属性值 */ public static String getStartEventAttributeValue(BpmnModel model, String name) { StartEvent startEvent = getStartEvent(model); return getElementAttributeValue(startEvent, name); } /** * 获取结束节点属性值 * @param model bpmnModel对象 * @param name 属性名 * @return 属性值 */ public static String getEndEventAttributeValue(BpmnModel model, String name) { EndEvent endEvent = getEndEvent(model); return getElementAttributeValue(endEvent, name); } /** * 获取用户任务节点属性值 * @param model bpmnModel对象 * @param taskKey 任务Key * @param name 属性名 * @return 属性值 */ public static String getUserTaskAttributeValue(BpmnModel model, String taskKey, String name) { UserTask userTask = getUserTaskByKey(model, taskKey); return getElementAttributeValue(userTask, name); } /** * 获取元素属性值 * @param baseElement 流程元素 * @param name 属性名 * @return 属性值 */ public static String getElementAttributeValue(BaseElement baseElement, String name) { if (baseElement != null) { List<ExtensionAttribute> attributes = baseElement.getAttributes().get(name); if (attributes != null && !attributes.isEmpty()) { attributes.iterator().next().getValue(); Iterator<ExtensionAttribute> attrIterator = attributes.iterator(); if(attrIterator.hasNext()) { ExtensionAttribute attribute = attrIterator.next(); return attribute.getValue(); } } } return null; } public static boolean isMultiInstance(BpmnModel model, String taskKey) { UserTask userTask = getUserTaskByKey(model, taskKey); if (ObjectUtil.isNotNull(userTask)) { return userTask.hasMultiInstanceLoopCharacteristics(); } return false; } /** * 获取所有用户任务节点 * * @param model bpmnModel对象 * @return 用户任务节点列表 */ public static Collection<UserTask> getAllUserTaskEvent(BpmnModel model) { Process process = model.getMainProcess(); Collection<FlowElement> flowElements = process.getFlowElements(); return getAllUserTaskEvent(flowElements, null); } /** * 获取所有用户任务节点 * @param flowElements 流程元素集合 * @param allElements 所有流程元素集合 * @return 用户任务节点列表 */ public static Collection<UserTask> getAllUserTaskEvent(Collection<FlowElement> flowElements, Collection<UserTask> allElements) { allElements = allElements == null ? new ArrayList<>() : allElements; for (FlowElement flowElement : flowElements) { if (flowElement instanceof UserTask) { allElements.add((UserTask) flowElement); } if (flowElement instanceof SubProcess) { // 继续深入子流程,进一步获取子流程 allElements = getAllUserTaskEvent(((SubProcess) flowElement).getFlowElements(), allElements); } } return allElements; } /** * 查找起始节点下一个用户任务列表列表 * @param source 起始节点 * @return 结果 */ public static List<UserTask> findNextUserTasks(FlowElement source) { return findNextUserTasks(source, null, null); } /** * 查找起始节点下一个用户任务列表列表 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param userTaskList 用户任务列表 * @return 结果 */ public static List<UserTask> findNextUserTasks(FlowElement source, Set<String> hasSequenceFlow, List<UserTask> userTaskList) { hasSequenceFlow = Optional.ofNullable(hasSequenceFlow).orElse(new HashSet<>()); userTaskList = Optional.ofNullable(userTaskList).orElse(new ArrayList<>()); // 获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (!sequenceFlows.isEmpty()) { for (SequenceFlow sequenceFlow : sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); FlowElement targetFlowElement = sequenceFlow.getTargetFlowElement(); if (targetFlowElement instanceof UserTask) { // 若节点为用户任务,加入到结果列表中 userTaskList.add((UserTask) targetFlowElement); } else { // 若节点非用户任务,继续递归查找下一个节点 findNextUserTasks(targetFlowElement, hasSequenceFlow, userTaskList); } } } return userTaskList; } /** * 迭代从后向前扫描,判断目标节点相对于当前节点是否是串行 * 不存在直接回退到子流程中的情况,但存在从子流程出去到父流程情况 * @param source 起始节点 * @param target 目标节点 * @param visitedElements 已经经过的连线的 ID,用于判断线路是否重复 * @return 结果 */ public static boolean isSequentialReachable(FlowElement source, FlowElement target, Set<String> visitedElements) { visitedElements = visitedElements == null ? new HashSet<>() : visitedElements; if (source instanceof StartEvent && isInEventSubprocess(source)) { return false; } // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null && sequenceFlows.size() > 0) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (visitedElements.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 visitedElements.add(sequenceFlow.getId()); FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement(); // 这条线路存在目标节点,这条线路完成,进入下个线路 if (target.getId().equals(sourceFlowElement.getId())) { continue; } // 如果目标节点为并行网关,则不继续 if (sourceFlowElement instanceof ParallelGateway) { return false; } // 否则就继续迭代 boolean isSequential = isSequentialReachable(sourceFlowElement, target, visitedElements); if (!isSequential) { return false; } } } return true; } protected static boolean isInEventSubprocess(FlowElement flowElement) { FlowElementsContainer flowElementsContainer = flowElement.getParentContainer(); while (flowElementsContainer != null) { if (flowElementsContainer instanceof EventSubProcess) { return true; } if (flowElementsContainer instanceof FlowElement) { flowElementsContainer = ((FlowElement) flowElementsContainer).getParentContainer(); } else { flowElementsContainer = null; } } return false; } }
2929004360/ruoyi-sign
1,870
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/NumberUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.StrUtil; import java.math.BigDecimal; /** * 数字的工具类,补全 {@link NumberUtil} 的功能 * * @author fengcheng */ public class NumberUtils { public static Long parseLong(String str) { return StrUtil.isNotEmpty(str) ? Long.valueOf(str) : null; } public static Integer parseInt(String str) { return StrUtil.isNotEmpty(str) ? Integer.valueOf(str) : null; } /** * 通过经纬度获取地球上两点之间的距离 * * 参考 <<a href="https://gitee.com/dromara/hutool/blob/1caabb586b1f95aec66a21d039c5695df5e0f4c1/hutool-core/src/main/java/cn/hutool/core/util/DistanceUtil.java">DistanceUtil</a>> 实现,目前它已经被 hutool 删除 * * @param lat1 经度1 * @param lng1 纬度1 * @param lat2 经度2 * @param lng2 纬度2 * @return 距离,单位:千米 */ public static double getDistance(double lat1, double lng1, double lat2, double lng2) { double radLat1 = lat1 * Math.PI / 180.0; double radLat2 = lat2 * Math.PI / 180.0; double a = radLat1 - radLat2; double b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0; double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); distance = distance * 6378.137; distance = Math.round(distance * 10000d) / 10000d; return distance; } /** * 提供精确的乘法运算 * * 和 hutool {@link NumberUtil#mul(BigDecimal...)} 的差别是,如果存在 null,则返回 null * * @param values 多个被乘值 * @return 积 */ public static BigDecimal mul(BigDecimal... values) { for (BigDecimal value : values) { if (value == null) { return null; } } return NumberUtil.mul(values); } }
2929004360/ruoyi-sign
4,646
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/ProcessUtils.java
package com.ruoyi.flowable.utils; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.flowable.core.domain.ProcessQuery; import org.flowable.common.engine.api.query.Query; import org.flowable.common.engine.impl.db.SuspensionState; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.repository.ProcessDefinitionQuery; import org.flowable.task.api.TaskQuery; import org.flowable.task.api.history.HistoricTaskInstanceQuery; import java.util.Map; /** * 流程工具类 * * @author fengcheng * @since 2022/12/11 03:35 */ public class ProcessUtils { public static void buildProcessSearch(Query<?, ?> query, ProcessQuery process) { if (query instanceof ProcessDefinitionQuery) { buildProcessDefinitionSearch((ProcessDefinitionQuery) query, process); } else if (query instanceof TaskQuery) { buildTaskSearch((TaskQuery) query, process); } else if (query instanceof HistoricTaskInstanceQuery) { buildHistoricTaskInstanceSearch((HistoricTaskInstanceQuery) query, process); } else if (query instanceof HistoricProcessInstanceQuery) { buildHistoricProcessInstanceSearch((HistoricProcessInstanceQuery) query, process); } } /** * 构建流程定义搜索 */ public static void buildProcessDefinitionSearch(ProcessDefinitionQuery query, ProcessQuery process) { // 流程标识 if (StringUtils.isNotBlank(process.getProcessKey())) { query.processDefinitionKeyLike("%" + process.getProcessKey() + "%"); } // 流程名称 if (StringUtils.isNotBlank(process.getProcessName())) { query.processDefinitionNameLike("%" + process.getProcessName() + "%"); } // 流程分类 if (StringUtils.isNotBlank(process.getCategory())) { query.processDefinitionCategory(process.getCategory()); } // 流程状态 if (StringUtils.isNotBlank(process.getState())) { if (SuspensionState.ACTIVE.toString().equals(process.getState())) { query.active(); } else if (SuspensionState.SUSPENDED.toString().equals(process.getState())) { query.suspended(); } } } /** * 构建任务搜索 */ public static void buildTaskSearch(TaskQuery query, ProcessQuery process) { Map<String, Object> params = process.getParams(); if (StringUtils.isNotBlank(process.getProcessKey())) { query.processDefinitionKeyLike("%" + process.getProcessKey() + "%"); } if (StringUtils.isNotBlank(process.getProcessName())) { query.processDefinitionNameLike("%" + process.getProcessName() + "%"); } if (params.get("beginTime") != null && params.get("endTime") != null) { query.taskCreatedAfter(DateUtils.parseDate(params.get("beginTime"))); query.taskCreatedBefore(DateUtils.parseDate(params.get("endTime"))); } } private static void buildHistoricTaskInstanceSearch(HistoricTaskInstanceQuery query, ProcessQuery process) { Map<String, Object> params = process.getParams(); if (StringUtils.isNotBlank(process.getProcessKey())) { query.processDefinitionKeyLike("%" + process.getProcessKey() + "%"); } if (StringUtils.isNotBlank(process.getProcessName())) { query.processDefinitionNameLike("%" + process.getProcessName() + "%"); } if (params.get("beginTime") != null && params.get("endTime") != null) { query.taskCompletedAfter(DateUtils.parseDate(params.get("beginTime"))); query.taskCompletedBefore(DateUtils.parseDate(params.get("endTime"))); } } /** * 构建历史流程实例搜索 */ public static void buildHistoricProcessInstanceSearch(HistoricProcessInstanceQuery query, ProcessQuery process) { Map<String, Object> params = process.getParams(); // 流程标识 if (StringUtils.isNotBlank(process.getProcessKey())) { query.processDefinitionKey(process.getProcessKey()); } // 流程名称 if (StringUtils.isNotBlank(process.getProcessName())) { query.processDefinitionName(process.getProcessName()); } // 流程名称 if (StringUtils.isNotBlank(process.getCategory())) { query.processDefinitionCategory(process.getCategory()); } if (params.get("beginTime") != null && params.get("endTime") != null) { query.startedAfter(DateUtils.parseDate(params.get("beginTime"))); query.startedBefore(DateUtils.parseDate(params.get("endTime"))); } } }
2929004360/ruoyi-sign
4,967
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/DateUtils.java
package com.ruoyi.flowable.utils; import org.apache.commons.lang3.time.DateFormatUtils; import java.lang.management.ManagementFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.*; import java.util.Date; /** * 时间工具类 * * @author ruoyi */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { public static String YYYY = "yyyy"; public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM_DD = "yyyy-MM-dd"; public static String YYYY_MM_DD_BAR = "yyyy/MM/dd"; public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 获取当前Date型日期 * * @return Date() 当前日期 */ public static Date getNowDate() { return new Date(); } /** * 获取当前日期, 默认格式为yyyy-MM-dd * * @return String */ public static String getDate() { return dateTimeNow(YYYY_MM_DD); } public static final String getTime() { return dateTimeNow(YYYY_MM_DD_HH_MM_SS); } public static final String dateTimeNow() { return dateTimeNow(YYYYMMDDHHMMSS); } public static final String dateTimeNow(final String format) { return parseDateToStr(format, new Date()); } public static final String dateTime(final Date date) { return parseDateToStr(YYYY_MM_DD, date); } public static final String date(final Date date) { return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date); } public static final String parseDateToStr(final String format, final Date date) { return new SimpleDateFormat(format).format(date); } public static final Date dateTime(final String format, final String ts) { try { return new SimpleDateFormat(format).parse(ts); } catch (ParseException e) { throw new RuntimeException(e); } } /** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date now = new Date(); return DateFormatUtils.format(now, "yyyy/MM/dd"); } /** * 日期路径 即年/月/日 如20180808 */ public static final String dateTime() { Date now = new Date(); return DateFormatUtils.format(now, "yyyyMMdd"); } /** * 日期型字符串转化为日期 格式 */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取服务器启动时间 */ public static Date getServerStartDate() { long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return new Date(time); } /** * 计算时间差 * * @param endDate 最后时间 * @param startTime 开始时间 * @return 时间差(天/小时/分钟) */ public static String timeDistance(Date endDate, Date startTime) { long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - startTime.getTime(); // 计算差多少天 long day = diff / nd; // 计算差多少小时 long hour = diff % nd / nh; // 计算差多少分钟 long min = diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; return day + "天" + hour + "小时" + min + "分钟"; } /** * 增加 LocalDateTime ==> Date */ public static Date toDate(LocalDateTime temporalAccessor) { ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } /** * 增加 LocalDate ==> Date */ public static Date toDate(LocalDate temporalAccessor) { LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0)); ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } /** * 计算两个时间差 */ public static String getDatePoor(Date endDate, Date nowDate) { long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - nowDate.getTime(); // 计算差多少天 long day = diff / nd; // 计算差多少小时 long hour = diff % nd / nh; // 计算差多少分钟 long min = diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; return day + "天" + hour + "小时" + min + "分钟"; } }
281677160/openwrt-package
1,158
luci-app-cpulimit/luasrc/model/cbi/cpulimit.lua
m = Map("cpulimit", translate("cpulimit")) m.description = translate("cpulimit ") s = m:section(TypedSection, "list", translate("Settings")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true enable = s:option(Flag, "enabled", translate("enable", "enable")) enable.optional = false enable.rmempty = false exename = s:option(Value, "exename", translate("exename"), translate("name of the executable program file or path name")) exename.optional = false exename.rmempty = false exename.default = "/usr/bin/transmission-daemon" exename:value("transmission","/usr/bin/transmission-daemon") exename:value("samba","/usr/sbin/smbd") exename:value("mount.ntfs-3g","mount.ntfs-3g") exename:value("vsftpd","/usr/sbin/vsftpd") exename:value("pure-ftpd","/usr/sbin/pure-ftpd") limit = s:option(Value, "limit", translate("limit")) limit.optional = false limit.rmempty = false limit.default = "50" limit:value("100","100%") limit:value("90","90%") limit:value("80","80%") limit:value("70","70%") limit:value("60","60%") limit:value("50","50%") limit:value("40","40%") limit:value("30","30%") limit:value("20","20%") limit:value("10","10%") return m
2929004360/ruoyi-sign
5,276
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/IdWorker.java
package com.ruoyi.flowable.utils; import org.springframework.stereotype.Component; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; /** * <p>名称:IdWorker.java</p> * <p>描述:分布式自增长ID</p> * <pre> * Twitter的 Snowflake JAVA实现方案 * </pre> * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用: * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000 * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间, * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识), * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。 * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分), * 并且效率较高,经测试,snowflake【每秒能够产生26万ID左右,完全满足需要】。 * <p> * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) */ @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase") @Component public class IdWorker { // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) private final static long twepoch = 1288834974657L; // 机器标识位数 private final static long workerIdBits = 5L; // 数据中心标识位数 private final static long datacenterIdBits = 5L; // 机器ID最大值 private final static long maxWorkerId = -1L ^ (-1L << workerIdBits); // 数据中心ID最大值 private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 毫秒内自增位 private final static long sequenceBits = 12L; // 机器ID偏左移12位 private final static long workerIdShift = sequenceBits; // 数据中心ID左移17位 private final static long datacenterIdShift = sequenceBits + workerIdBits; // 时间毫秒左移22位 private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final static long sequenceMask = -1L ^ (-1L << sequenceBits); /* 上次生产id时间戳 */ private static long lastTimestamp = -1L; private final long workerId; private final long datacenterId; // 数据标识id部分 // 0,并发控制 private long sequence = 0L; public IdWorker() { this.datacenterId = getDatacenterId(maxDatacenterId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); } /** * @param workerId 工作机器ID * @param datacenterId 序列号 */ public IdWorker(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } /** * <p> * 获取 maxWorkerId * </p> */ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** * <p> * 数据标识id部分 * </p> */ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; } /** * 获取下一个ID * * @return */ public synchronized Long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; } private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } }
2929004360/ruoyi-sign
8,001
ruoyi-flowable/src/main/java/com/ruoyi/flowable/utils/StringUtils.java
package com.ruoyi.flowable.utils; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Validator; import cn.hutool.core.util.StrUtil; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.springframework.util.AntPathMatcher; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * 字符串工具类 * * @author fengcheng */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class StringUtils extends org.apache.commons.lang3.StringUtils { public static final String SEPARATOR = ","; /** * 获取参数不为空值 * * @param str defaultValue 要判断的value * @return value 返回值 */ public static String blankToDefault(String str, String defaultValue) { return StrUtil.blankToDefault(str, defaultValue); } /** * * 判断一个字符串是否为空串 * * @param str String * @return true:为空 false:非空 */ public static boolean isEmpty(String str) { return StrUtil.isEmpty(str); } /** * * 判断一个字符串是否为非空串 * * @param str String * @return true:非空串 false:空串 */ public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * 去空格 */ public static String trim(String str) { return StrUtil.trim(str); } /** * 截取字符串 * * @param str 字符串 * @param start 开始 * @return 结果 */ public static String substring(final String str, int start) { return substring(str, start, str.length()); } /** * 截取字符串 * * @param str 字符串 * @param start 开始 * @param end 结束 * @return 结果 */ public static String substring(final String str, int start, int end) { return StrUtil.sub(str, start, end); } /** * 格式化文本, {} 表示占位符<br> * 此方法只是简单将占位符 {} 按照顺序替换为参数<br> * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br> * 例:<br> * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br> * 转义{}: format("this is \\{} for {}", "a", "b") -> this is {} for a<br> * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * * @param template 文本模板,被替换的部分用 {} 表示 * @param params 参数值 * @return 格式化后的文本 */ public static String format(String template, Object... params) { return StrUtil.format(template, params); } /** * 是否为http(s)://开头 * * @param link 链接 * @return 结果 */ public static boolean ishttp(String link) { return Validator.isUrl(link); } /** * 字符串转set * * @param str 字符串 * @param sep 分隔符 * @return set集合 */ public static Set<String> str2Set(String str, String sep) { return new HashSet<>(str2List(str, sep, true, false)); } /** * 字符串转list * * @param str 字符串 * @param sep 分隔符 * @param filterBlank 过滤纯空白 * @param trim 去掉首尾空白 * @return list集合 */ public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) { List<String> list = new ArrayList<>(); if (isEmpty(str)) { return list; } // 过滤空白字符串 if (filterBlank && isBlank(str)) { return list; } String[] split = str.split(sep); for (String string : split) { if (filterBlank && isBlank(string)) { continue; } if (trim) { string = trim(string); } list.add(string); } return list; } /** * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写 * * @param cs 指定字符串 * @param searchCharSequences 需要检查的字符串数组 * @return 是否包含任意一个字符串 */ public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) { return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences); } /** * 驼峰转下划线命名 */ public static String toUnderScoreCase(String str) { return StrUtil.toUnderlineCase(str); } /** * 是否包含字符串 * * @param str 验证字符串 * @param strs 字符串组 * @return 包含返回true */ public static boolean inStringIgnoreCase(String str, String... strs) { return StrUtil.equalsAnyIgnoreCase(str, strs); } /** * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld * * @param name 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String convertToCamelCase(String name) { return StrUtil.upperFirst(StrUtil.toCamelCase(name)); } /** * 驼峰式命名法 例如:user_name->userName */ public static String toCamelCase(String s) { return StrUtil.toCamelCase(s); } /** * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 * * @param str 指定字符串 * @param strs 需要检查的字符串数组 * @return 是否匹配 */ public static boolean matches(String str, List<String> strs) { if (isEmpty(str) || CollUtil.isEmpty(strs)) { return false; } for (String pattern : strs) { if (isMatch(pattern, str)) { return true; } } return false; } /** * 判断url是否与规则配置: * ? 表示单个字符; * * 表示一层路径内的任意字符串,不可跨层级; * ** 表示任意层路径; * * @param pattern 匹配规则 * @param url 需要匹配的url */ public static boolean isMatch(String pattern, String url) { AntPathMatcher matcher = new AntPathMatcher(); return matcher.match(pattern, url); } /** * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。 * * @param num 数字对象 * @param size 字符串指定长度 * @return 返回数字的字符串格式,该字符串为指定长度。 */ public static String padl(final Number num, final int size) { return padl(num.toString(), size, '0'); } /** * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。 * * @param s 原始字符串 * @param size 字符串指定长度 * @param c 用于补齐的字符 * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。 */ public static String padl(final String s, final int size, final char c) { final StringBuilder sb = new StringBuilder(size); if (s != null) { final int len = s.length(); if (s.length() <= size) { for (int i = size - len; i > 0; i--) { sb.append(c); } sb.append(s); } else { return s.substring(len - size, len); } } else { for (int i = size; i > 0; i--) { sb.append(c); } } return sb.toString(); } /** * 切分字符串(分隔符默认逗号) * * @param str 被切分的字符串 * @return 分割后的数据列表 */ public static List<String> splitList(String str) { return splitTo(str, Convert::toStr); } /** * 切分字符串 * * @param str 被切分的字符串 * @param separator 分隔符 * @return 分割后的数据列表 */ public static List<String> splitList(String str, String separator) { return splitTo(str, separator, Convert::toStr); } /** * 切分字符串自定义转换(分隔符默认逗号) * * @param str 被切分的字符串 * @param mapper 自定义转换 * @return 分割后的数据列表 */ public static <T> List<T> splitTo(String str, Function<? super Object, T> mapper) { return splitTo(str, SEPARATOR, mapper); } /** * 切分字符串自定义转换 * * @param str 被切分的字符串 * @param separator 分隔符 * @param mapper 自定义转换 * @return 分割后的数据列表 */ public static <T> List<T> splitTo(String str, String separator, Function<? super Object, T> mapper) { if (isBlank(str)) { return new ArrayList<>(0); } return StrUtil.split(str, separator) .stream() .filter(Objects::nonNull) .map(mapper) .collect(Collectors.toList()); } }
2929004360/ruoyi-sign
16,988
ruoyi-flowable/src/main/java/com/ruoyi/flowable/flow/CustomProcessDiagramGenerator.java
package com.ruoyi.flowable.flow; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.*; import org.flowable.image.impl.DefaultProcessDiagramCanvas; import org.flowable.image.impl.DefaultProcessDiagramGenerator; import java.util.Iterator; import java.util.List; /** * @author XuanXuan * @date 2021/4/5 0:31 */ public class CustomProcessDiagramGenerator extends DefaultProcessDiagramGenerator { @Override protected DefaultProcessDiagramCanvas generateProcessDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, String activityFontName, String labelFontName, String annotationFontName, ClassLoader customClassLoader, double scaleFactor, boolean drawSequenceFlowNameWithNoLabelDI) { this.prepareBpmnModel(bpmnModel); DefaultProcessDiagramCanvas processDiagramCanvas = initProcessDiagramCanvas(bpmnModel, imageType, activityFontName, labelFontName, annotationFontName, customClassLoader); Iterator var13 = bpmnModel.getPools().iterator(); while (var13.hasNext()) { Pool process = (Pool) var13.next(); GraphicInfo subProcesses = bpmnModel.getGraphicInfo(process.getId()); processDiagramCanvas.drawPoolOrLane(process.getName(), subProcesses, scaleFactor); } var13 = bpmnModel.getProcesses().iterator(); Process process1; Iterator subProcesses1; while (var13.hasNext()) { process1 = (Process) var13.next(); subProcesses1 = process1.getLanes().iterator(); while (subProcesses1.hasNext()) { Lane artifact = (Lane) subProcesses1.next(); GraphicInfo subProcess = bpmnModel.getGraphicInfo(artifact.getId()); processDiagramCanvas.drawPoolOrLane(artifact.getName(), subProcess, scaleFactor); } } var13 = bpmnModel.getProcesses().iterator(); while (var13.hasNext()) { process1 = (Process) var13.next(); subProcesses1 = process1.findFlowElementsOfType(FlowNode.class).iterator(); while (subProcesses1.hasNext()) { FlowNode artifact1 = (FlowNode) subProcesses1.next(); if (!this.isPartOfCollapsedSubProcess(artifact1, bpmnModel)) { this.drawActivity(processDiagramCanvas, bpmnModel, artifact1, highLightedActivities, highLightedFlows, scaleFactor, Boolean.valueOf(drawSequenceFlowNameWithNoLabelDI)); } } } var13 = bpmnModel.getProcesses().iterator(); label75: while (true) { List subProcesses2; do { if (!var13.hasNext()) { return processDiagramCanvas; } process1 = (Process) var13.next(); subProcesses1 = process1.getArtifacts().iterator(); while (subProcesses1.hasNext()) { Artifact artifact2 = (Artifact) subProcesses1.next(); this.drawArtifact(processDiagramCanvas, bpmnModel, artifact2); } subProcesses2 = process1.findFlowElementsOfType(SubProcess.class, true); } while (subProcesses2 == null); Iterator artifact3 = subProcesses2.iterator(); while (true) { GraphicInfo graphicInfo; SubProcess subProcess1; do { do { if (!artifact3.hasNext()) { continue label75; } subProcess1 = (SubProcess) artifact3.next(); graphicInfo = bpmnModel.getGraphicInfo(subProcess1.getId()); } while (graphicInfo != null && graphicInfo.getExpanded() != null && !graphicInfo.getExpanded().booleanValue()); } while (this.isPartOfCollapsedSubProcess(subProcess1, bpmnModel)); Iterator var19 = subProcess1.getArtifacts().iterator(); while (var19.hasNext()) { Artifact subProcessArtifact = (Artifact) var19.next(); this.drawArtifact(processDiagramCanvas, bpmnModel, subProcessArtifact); } } } } protected static DefaultProcessDiagramCanvas initProcessDiagramCanvas(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName, String annotationFontName, ClassLoader customClassLoader) { double minX = 1.7976931348623157E308D; double maxX = 0.0D; double minY = 1.7976931348623157E308D; double maxY = 0.0D; GraphicInfo nrOfLanes; for (Iterator flowNodes = bpmnModel.getPools().iterator(); flowNodes.hasNext(); maxY = nrOfLanes.getY() + nrOfLanes.getHeight()) { Pool artifacts = (Pool) flowNodes.next(); nrOfLanes = bpmnModel.getGraphicInfo(artifacts.getId()); minX = nrOfLanes.getX(); maxX = nrOfLanes.getX() + nrOfLanes.getWidth(); minY = nrOfLanes.getY(); } List var23 = gatherAllFlowNodes(bpmnModel); Iterator var24 = var23.iterator(); label155: while (var24.hasNext()) { FlowNode var26 = (FlowNode) var24.next(); GraphicInfo artifact = bpmnModel.getGraphicInfo(var26.getId()); if (artifact.getX() + artifact.getWidth() > maxX) { maxX = artifact.getX() + artifact.getWidth(); } if (artifact.getX() < minX) { minX = artifact.getX(); } if (artifact.getY() + artifact.getHeight() > maxY) { maxY = artifact.getY() + artifact.getHeight(); } if (artifact.getY() < minY) { minY = artifact.getY(); } Iterator process = var26.getOutgoingFlows().iterator(); while (true) { List l; do { if (!process.hasNext()) { continue label155; } SequenceFlow graphicInfoList = (SequenceFlow) process.next(); l = bpmnModel.getFlowLocationGraphicInfo(graphicInfoList.getId()); } while (l == null); Iterator graphicInfo = l.iterator(); while (graphicInfo.hasNext()) { GraphicInfo graphicInfo1 = (GraphicInfo) graphicInfo.next(); if (graphicInfo1.getX() > maxX) { maxX = graphicInfo1.getX(); } if (graphicInfo1.getX() < minX) { minX = graphicInfo1.getX(); } if (graphicInfo1.getY() > maxY) { maxY = graphicInfo1.getY(); } if (graphicInfo1.getY() < minY) { minY = graphicInfo1.getY(); } } } } List var25 = gatherAllArtifacts(bpmnModel); Iterator var27 = var25.iterator(); GraphicInfo var37; while (var27.hasNext()) { Artifact var29 = (Artifact) var27.next(); GraphicInfo var31 = bpmnModel.getGraphicInfo(var29.getId()); if (var31 != null) { if (var31.getX() + var31.getWidth() > maxX) { maxX = var31.getX() + var31.getWidth(); } if (var31.getX() < minX) { minX = var31.getX(); } if (var31.getY() + var31.getHeight() > maxY) { maxY = var31.getY() + var31.getHeight(); } if (var31.getY() < minY) { minY = var31.getY(); } } List var33 = bpmnModel.getFlowLocationGraphicInfo(var29.getId()); if (var33 != null) { Iterator var35 = var33.iterator(); while (var35.hasNext()) { var37 = (GraphicInfo) var35.next(); if (var37.getX() > maxX) { maxX = var37.getX(); } if (var37.getX() < minX) { minX = var37.getX(); } if (var37.getY() > maxY) { maxY = var37.getY(); } if (var37.getY() < minY) { minY = var37.getY(); } } } } int var28 = 0; Iterator var30 = bpmnModel.getProcesses().iterator(); while (var30.hasNext()) { Process var32 = (Process) var30.next(); Iterator var34 = var32.getLanes().iterator(); while (var34.hasNext()) { Lane var36 = (Lane) var34.next(); ++var28; var37 = bpmnModel.getGraphicInfo(var36.getId()); if (var37.getX() + var37.getWidth() > maxX) { maxX = var37.getX() + var37.getWidth(); } if (var37.getX() < minX) { minX = var37.getX(); } if (var37.getY() + var37.getHeight() > maxY) { maxY = var37.getY() + var37.getHeight(); } if (var37.getY() < minY) { minY = var37.getY(); } } } if (var23.isEmpty() && bpmnModel.getPools().isEmpty() && var28 == 0) { minX = 0.0D; minY = 0.0D; } return new CustomProcessDiagramCanvas((int) maxX + 10, (int) maxY + 10, (int) minX, (int) minY, imageType, activityFontName, labelFontName, annotationFontName, customClassLoader); } private static void drawHighLight(DefaultProcessDiagramCanvas processDiagramCanvas, GraphicInfo graphicInfo) { processDiagramCanvas.drawHighLight((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight()); } private static void drawHighLightNow(CustomProcessDiagramCanvas processDiagramCanvas, GraphicInfo graphicInfo) { processDiagramCanvas.drawHighLightNow((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight()); } private static void drawHighLightEnd(CustomProcessDiagramCanvas processDiagramCanvas, GraphicInfo graphicInfo) { processDiagramCanvas.drawHighLightEnd((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight()); } @Override protected void drawActivity(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode, List<String> highLightedActivities, List<String> highLightedFlows, double scaleFactor, Boolean drawSequenceFlowNameWithNoLabelDI) { ActivityDrawInstruction drawInstruction = activityDrawInstructions.get(flowNode.getClass()); if (drawInstruction != null) { drawInstruction.draw(processDiagramCanvas, bpmnModel, flowNode); // Gather info on the multi instance marker boolean multiInstanceSequential = false; boolean multiInstanceParallel = false; boolean collapsed = false; if (flowNode instanceof Activity) { Activity activity = (Activity) flowNode; MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = activity.getLoopCharacteristics(); if (multiInstanceLoopCharacteristics != null) { multiInstanceSequential = multiInstanceLoopCharacteristics.isSequential(); multiInstanceParallel = !multiInstanceSequential; } } // Gather info on the collapsed marker GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId()); if (flowNode instanceof SubProcess) { collapsed = graphicInfo.getExpanded() != null && !graphicInfo.getExpanded(); } else if (flowNode instanceof CallActivity) { collapsed = true; } if (scaleFactor == 1.0) { // Actually draw the markers processDiagramCanvas.drawActivityMarkers((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight(), multiInstanceSequential, multiInstanceParallel, collapsed); } // Draw highlighted activities if (highLightedActivities.contains(flowNode.getId())) { if (highLightedActivities.get(highLightedActivities.size() - 1).equals(flowNode.getId()) && !"endenv".equals(flowNode.getId())) { if ((flowNode.getId().contains("Event_"))) { drawHighLightEnd((CustomProcessDiagramCanvas) processDiagramCanvas, bpmnModel.getGraphicInfo(flowNode.getId())); } else { drawHighLightNow((CustomProcessDiagramCanvas) processDiagramCanvas, bpmnModel.getGraphicInfo(flowNode.getId())); } } else { drawHighLight(processDiagramCanvas, bpmnModel.getGraphicInfo(flowNode.getId())); } } } // Outgoing transitions of activity for (SequenceFlow sequenceFlow : flowNode.getOutgoingFlows()) { boolean highLighted = (highLightedFlows.contains(sequenceFlow.getId())); String defaultFlow = null; if (flowNode instanceof Activity) { defaultFlow = ((Activity) flowNode).getDefaultFlow(); } else if (flowNode instanceof Gateway) { defaultFlow = ((Gateway) flowNode).getDefaultFlow(); } boolean isDefault = false; if (defaultFlow != null && defaultFlow.equalsIgnoreCase(sequenceFlow.getId())) { isDefault = true; } boolean drawConditionalIndicator = sequenceFlow.getConditionExpression() != null && !(flowNode instanceof Gateway); String sourceRef = sequenceFlow.getSourceRef(); String targetRef = sequenceFlow.getTargetRef(); FlowElement sourceElement = bpmnModel.getFlowElement(sourceRef); FlowElement targetElement = bpmnModel.getFlowElement(targetRef); List<GraphicInfo> graphicInfoList = bpmnModel.getFlowLocationGraphicInfo(sequenceFlow.getId()); if (graphicInfoList != null && graphicInfoList.size() > 0) { graphicInfoList = connectionPerfectionizer(processDiagramCanvas, bpmnModel, sourceElement, targetElement, graphicInfoList); int xPoints[] = new int[graphicInfoList.size()]; int yPoints[] = new int[graphicInfoList.size()]; for (int i = 1; i < graphicInfoList.size(); i++) { GraphicInfo graphicInfo = graphicInfoList.get(i); GraphicInfo previousGraphicInfo = graphicInfoList.get(i - 1); if (i == 1) { xPoints[0] = (int) previousGraphicInfo.getX(); yPoints[0] = (int) previousGraphicInfo.getY(); } xPoints[i] = (int) graphicInfo.getX(); yPoints[i] = (int) graphicInfo.getY(); } processDiagramCanvas.drawSequenceflow(xPoints, yPoints, drawConditionalIndicator, isDefault, highLighted, scaleFactor); // Draw sequenceflow label GraphicInfo labelGraphicInfo = bpmnModel.getLabelGraphicInfo(sequenceFlow.getId()); if (labelGraphicInfo != null) { processDiagramCanvas.drawLabel(sequenceFlow.getName(), labelGraphicInfo, false); } else { if (drawSequenceFlowNameWithNoLabelDI) { GraphicInfo lineCenter = getLineCenter(graphicInfoList); processDiagramCanvas.drawLabel(sequenceFlow.getName(), lineCenter, false); } } } } // Nested elements if (flowNode instanceof FlowElementsContainer) { for (FlowElement nestedFlowElement : ((FlowElementsContainer) flowNode).getFlowElements()) { if (nestedFlowElement instanceof FlowNode && !isPartOfCollapsedSubProcess(nestedFlowElement, bpmnModel)) { drawActivity(processDiagramCanvas, bpmnModel, (FlowNode) nestedFlowElement, highLightedActivities, highLightedFlows, scaleFactor, drawSequenceFlowNameWithNoLabelDI); } } } } }
2929004360/ruoyi-sign
15,116
ruoyi-flowable/src/main/java/com/ruoyi/flowable/flow/CustomProcessDiagramCanvas.java
package com.ruoyi.flowable.flow; import org.flowable.bpmn.model.AssociationDirection; import org.flowable.bpmn.model.GraphicInfo; import org.flowable.image.impl.DefaultProcessDiagramCanvas; import org.flowable.image.util.ReflectUtil; import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.text.AttributedCharacterIterator; import java.text.AttributedString; /** * @author XuanXuan * @date 2021/4/4 23:58 */ public class CustomProcessDiagramCanvas extends DefaultProcessDiagramCanvas { //定义走过流程连线颜色为绿色 protected static Color HIGHLIGHT_SequenceFlow_COLOR = Color.GREEN; //设置未走过流程的连接线颜色 protected static Color CONNECTION_COLOR = Color.BLACK; //设置flows连接线字体颜色red protected static Color LABEL_COLOR = new Color(0, 0, 0); //高亮显示task框颜色 protected static Color HIGHLIGHT_COLOR = Color.GREEN; protected static Color HIGHLIGHT_COLOR1 = Color.RED; public CustomProcessDiagramCanvas(int width, int height, int minX, int minY, String imageType, String activityFontName, String labelFontName, String annotationFontName, ClassLoader customClassLoader) { super(width, height, minX, minY, imageType, activityFontName, labelFontName, annotationFontName, customClassLoader); this.initialize(imageType); } /** * 重写绘制连线的方式,设置绘制颜色 * @param xPoints * @param yPoints * @param conditional * @param isDefault * @param connectionType * @param associationDirection * @param highLighted * @param scaleFactor */ @Override public void drawConnection(int[] xPoints, int[] yPoints, boolean conditional, boolean isDefault, String connectionType, AssociationDirection associationDirection, boolean highLighted, double scaleFactor) { Paint originalPaint = this.g.getPaint(); Stroke originalStroke = this.g.getStroke(); this.g.setPaint(CONNECTION_COLOR); if (connectionType.equals("association")) { this.g.setStroke(ASSOCIATION_STROKE); } else if (highLighted) { this.g.setPaint(HIGHLIGHT_SequenceFlow_COLOR); this.g.setStroke(HIGHLIGHT_FLOW_STROKE); } for (int i = 1; i < xPoints.length; ++i) { int sourceX = xPoints[i - 1]; int sourceY = yPoints[i - 1]; int targetX = xPoints[i]; int targetY = yPoints[i]; java.awt.geom.Line2D.Double line = new java.awt.geom.Line2D.Double((double) sourceX, (double) sourceY, (double) targetX, (double) targetY); this.g.draw(line); } java.awt.geom.Line2D.Double line; if (isDefault) { line = new java.awt.geom.Line2D.Double((double) xPoints[0], (double) yPoints[0], (double) xPoints[1], (double) yPoints[1]); this.drawDefaultSequenceFlowIndicator(line, scaleFactor); } if (conditional) { line = new java.awt.geom.Line2D.Double((double) xPoints[0], (double) yPoints[0], (double) xPoints[1], (double) yPoints[1]); this.drawConditionalSequenceFlowIndicator(line, scaleFactor); } if (associationDirection.equals(AssociationDirection.ONE) || associationDirection.equals(AssociationDirection.BOTH)) { line = new java.awt.geom.Line2D.Double((double) xPoints[xPoints.length - 2], (double) yPoints[xPoints.length - 2], (double) xPoints[xPoints.length - 1], (double) yPoints[xPoints.length - 1]); this.drawArrowHead(line, scaleFactor); } if (associationDirection.equals(AssociationDirection.BOTH)) { line = new java.awt.geom.Line2D.Double((double) xPoints[1], (double) yPoints[1], (double) xPoints[0], (double) yPoints[0]); this.drawArrowHead(line, scaleFactor); } this.g.setPaint(originalPaint); this.g.setStroke(originalStroke); } /** * 设置字体大小图标颜色 * @param imageType */ @Override public void initialize(String imageType) { if ("png".equalsIgnoreCase(imageType)) { this.processDiagram = new BufferedImage(this.canvasWidth, this.canvasHeight, 2); } else { this.processDiagram = new BufferedImage(this.canvasWidth, this.canvasHeight, 1); } this.g = this.processDiagram.createGraphics(); if (!"png".equalsIgnoreCase(imageType)) { this.g.setBackground(new Color(255, 255, 255, 0)); this.g.clearRect(0, 0, this.canvasWidth, this.canvasHeight); } this.g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //修改图标颜色,修改图标字体大小 this.g.setPaint(Color.black); Font font = new Font(this.activityFontName, 10, 14); this.g.setFont(font); this.fontMetrics = this.g.getFontMetrics(); //修改连接线字体大小 LABEL_FONT = new Font(this.labelFontName, 10, 15); ANNOTATION_FONT = new Font(this.annotationFontName, 0, 11); try { USERTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/userTask.png", this.customClassLoader)); SCRIPTTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/scriptTask.png", this.customClassLoader)); SERVICETASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/serviceTask.png", this.customClassLoader)); RECEIVETASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/receiveTask.png", this.customClassLoader)); SENDTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/sendTask.png", this.customClassLoader)); MANUALTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/manualTask.png", this.customClassLoader)); BUSINESS_RULE_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/businessRuleTask.png", this.customClassLoader)); SHELL_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/shellTask.png", this.customClassLoader)); DMN_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/dmnTask.png", this.customClassLoader)); CAMEL_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/camelTask.png", this.customClassLoader)); MULE_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/muleTask.png", this.customClassLoader)); HTTP_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/httpTask.png", this.customClassLoader)); TIMER_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/timer.png", this.customClassLoader)); COMPENSATE_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/compensate-throw.png", this.customClassLoader)); COMPENSATE_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/compensate.png", this.customClassLoader)); ERROR_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/error-throw.png", this.customClassLoader)); ERROR_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/error.png", this.customClassLoader)); MESSAGE_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/message-throw.png", this.customClassLoader)); MESSAGE_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/message.png", this.customClassLoader)); SIGNAL_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/signal-throw.png", this.customClassLoader)); SIGNAL_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/flowable/icons/signal.png", this.customClassLoader)); } catch (IOException var4) { LOGGER.warn("Could not load image for process diagram creation: {}", var4.getMessage()); } } /** * 设置连接线字体 * @param text * @param graphicInfo * @param centered */ @Override public void drawLabel(String text, GraphicInfo graphicInfo, boolean centered) { float interline = 1.0f; // text if (text != null && text.length() > 0) { Paint originalPaint = g.getPaint(); Font originalFont = g.getFont(); g.setPaint(LABEL_COLOR); g.setFont(LABEL_FONT); int wrapWidth = 100; int textY = (int) graphicInfo.getY(); // TODO: use drawMultilineText() AttributedString as = new AttributedString(text); as.addAttribute(TextAttribute.FOREGROUND, g.getPaint()); as.addAttribute(TextAttribute.FONT, g.getFont()); AttributedCharacterIterator aci = as.getIterator(); FontRenderContext frc = new FontRenderContext(null, true, false); LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc); while (lbm.getPosition() < text.length()) { TextLayout tl = lbm.nextLayout(wrapWidth); textY += tl.getAscent(); Rectangle2D bb = tl.getBounds(); double tX = graphicInfo.getX(); if (centered) { tX += (int) (graphicInfo.getWidth() / 2 - bb.getWidth() / 2); } tl.draw(g, (float) tX, textY); textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent(); } // restore originals g.setFont(originalFont); g.setPaint(originalPaint); } } /** * 高亮显示task框完成的 * @param x * @param y * @param width * @param height */ @Override public void drawHighLight(int x, int y, int width, int height) { Paint originalPaint = g.getPaint(); Stroke originalStroke = g.getStroke(); g.setPaint(HIGHLIGHT_COLOR); g.setStroke(THICK_TASK_BORDER_STROKE); RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20); g.draw(rect); g.setPaint(originalPaint); g.setStroke(originalStroke); } /** * 自定义task框当前的位置 * @param x * @param y * @param width * @param height */ public void drawHighLightNow(int x, int y, int width, int height) { Paint originalPaint = g.getPaint(); Stroke originalStroke = g.getStroke(); g.setPaint(HIGHLIGHT_COLOR1); g.setStroke(THICK_TASK_BORDER_STROKE); RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20); g.draw(rect); g.setPaint(originalPaint); g.setStroke(originalStroke); } /** * 自定义结束节点 * @param x * @param y * @param width * @param height */ public void drawHighLightEnd(int x, int y, int width, int height) { Paint originalPaint = g.getPaint(); Stroke originalStroke = g.getStroke(); g.setPaint(HIGHLIGHT_COLOR); g.setStroke(THICK_TASK_BORDER_STROKE); RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20); g.draw(rect); g.setPaint(originalPaint); g.setStroke(originalStroke); } /** * task框自定义文字 * @param name * @param graphicInfo * @param thickBorder * @param scaleFactor */ @Override protected void drawTask(String name, GraphicInfo graphicInfo, boolean thickBorder, double scaleFactor) { Paint originalPaint = g.getPaint(); int x = (int) graphicInfo.getX(); int y = (int) graphicInfo.getY(); int width = (int) graphicInfo.getWidth(); int height = (int) graphicInfo.getHeight(); // Create a new gradient paint for every task box, gradient depends on x and y and is not relative g.setPaint(TASK_BOX_COLOR); int arcR = 6; if (thickBorder) { arcR = 3; } // shape RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, arcR, arcR); g.fill(rect); g.setPaint(TASK_BORDER_COLOR); if (thickBorder) { Stroke originalStroke = g.getStroke(); g.setStroke(THICK_TASK_BORDER_STROKE); g.draw(rect); g.setStroke(originalStroke); } else { g.draw(rect); } g.setPaint(originalPaint); // text if (scaleFactor == 1.0 && name != null && name.length() > 0) { int boxWidth = width - (2 * TEXT_PADDING); int boxHeight = height - 16 - ICON_PADDING - ICON_PADDING - MARKER_WIDTH - 2 - 2; int boxX = x + width / 2 - boxWidth / 2; int boxY = y + height / 2 - boxHeight / 2 + ICON_PADDING + ICON_PADDING - 2 - 2; drawMultilineCentredText(name, boxX, boxY, boxWidth, boxHeight); } } protected static Color EVENT_COLOR = new Color(255, 255, 255); /** * 重写开始事件 * @param graphicInfo * @param image * @param scaleFactor */ @Override public void drawStartEvent(GraphicInfo graphicInfo, BufferedImage image, double scaleFactor) { Paint originalPaint = g.getPaint(); g.setPaint(EVENT_COLOR); Ellipse2D circle = new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight()); g.fill(circle); g.setPaint(EVENT_BORDER_COLOR); g.draw(circle); g.setPaint(originalPaint); if (image != null) { // calculate coordinates to center image int imageX = (int) Math.round(graphicInfo.getX() + (graphicInfo.getWidth() / 2) - (image.getWidth() / (2 * scaleFactor))); int imageY = (int) Math.round(graphicInfo.getY() + (graphicInfo.getHeight() / 2) - (image.getHeight() / (2 * scaleFactor))); g.drawImage(image, imageX, imageY, (int) (image.getWidth() / scaleFactor), (int) (image.getHeight() / scaleFactor), null); } } /** * 重写结束事件 * @param graphicInfo * @param scaleFactor */ @Override public void drawNoneEndEvent(GraphicInfo graphicInfo, double scaleFactor) { Paint originalPaint = g.getPaint(); Stroke originalStroke = g.getStroke(); g.setPaint(EVENT_COLOR); Ellipse2D circle = new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight()); g.fill(circle); g.setPaint(EVENT_BORDER_COLOR); // g.setPaint(HIGHLIGHT_COLOR); if (scaleFactor == 1.0) { g.setStroke(END_EVENT_STROKE); } else { g.setStroke(new BasicStroke(2.0f)); } g.draw(circle); g.setStroke(originalStroke); g.setPaint(originalPaint); } }
2929004360/ruoyi-sign
8,711
ruoyi-flowable/src/main/java/com/ruoyi/flowable/flow/FindNextNodeUtil.java
package com.ruoyi.flowable.flow; import com.googlecode.aviator.AviatorEvaluator; import com.googlecode.aviator.Expression; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.*; import org.flowable.engine.RepositoryService; import org.flowable.engine.repository.ProcessDefinition; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author Xuan xuan * @date 2021/4/19 20:51 */ public class FindNextNodeUtil { /** * 获取下一步骤的用户任务 * * @param repositoryService * @param map * @return */ public static List<UserTask> getNextUserTasks(RepositoryService repositoryService, org.flowable.task.api.Task task, Map<String, Object> map) { List<UserTask> data = new ArrayList<>(); ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); Process mainProcess = bpmnModel.getMainProcess(); Collection<FlowElement> flowElements = mainProcess.getFlowElements(); String key = task.getTaskDefinitionKey(); FlowElement flowElement = bpmnModel.getFlowElement(key); next(flowElements, flowElement, map, data); return data; } public static void next(Collection<FlowElement> flowElements, FlowElement flowElement, Map<String, Object> map, List<UserTask> nextUser) { //如果是结束节点 if (flowElement instanceof EndEvent) { //如果是子任务的结束节点 if (getSubProcess(flowElements, flowElement) != null) { flowElement = getSubProcess(flowElements, flowElement); } } //获取Task的出线信息--可以拥有多个 List<SequenceFlow> outGoingFlows = null; if (flowElement instanceof Task) { outGoingFlows = ((Task) flowElement).getOutgoingFlows(); } else if (flowElement instanceof Gateway) { outGoingFlows = ((Gateway) flowElement).getOutgoingFlows(); } else if (flowElement instanceof StartEvent) { outGoingFlows = ((StartEvent) flowElement).getOutgoingFlows(); } else if (flowElement instanceof SubProcess) { outGoingFlows = ((SubProcess) flowElement).getOutgoingFlows(); } else if (flowElement instanceof CallActivity) { outGoingFlows = ((CallActivity) flowElement).getOutgoingFlows(); } if (outGoingFlows != null && outGoingFlows.size() > 0) { //遍历所有的出线--找到可以正确执行的那一条 for (SequenceFlow sequenceFlow : outGoingFlows) { //1.有表达式,且为true //2.无表达式 String expression = sequenceFlow.getConditionExpression(); if (expression == null || expressionResult(map, expression.substring(expression.lastIndexOf("{") + 1, expression.lastIndexOf("}")))) { //出线的下一节点 String nextFlowElementID = sequenceFlow.getTargetRef(); if (checkSubProcess(nextFlowElementID, flowElements, nextUser)) { continue; } //查询下一节点的信息 FlowElement nextFlowElement = getFlowElementById(nextFlowElementID, flowElements); //调用流程 if (nextFlowElement instanceof CallActivity) { CallActivity ca = (CallActivity) nextFlowElement; if (ca.getLoopCharacteristics() != null) { UserTask userTask = new UserTask(); userTask.setId(ca.getId()); userTask.setId(ca.getId()); userTask.setLoopCharacteristics(ca.getLoopCharacteristics()); userTask.setName(ca.getName()); nextUser.add(userTask); } next(flowElements, nextFlowElement, map, nextUser); } //用户任务 if (nextFlowElement instanceof UserTask) { nextUser.add((UserTask) nextFlowElement); } //排他网关 else if (nextFlowElement instanceof ExclusiveGateway) { next(flowElements, nextFlowElement, map, nextUser); } //并行网关 else if (nextFlowElement instanceof ParallelGateway) { next(flowElements, nextFlowElement, map, nextUser); } //接收任务 else if (nextFlowElement instanceof ReceiveTask) { next(flowElements, nextFlowElement, map, nextUser); } //服务任务 else if (nextFlowElement instanceof ServiceTask) { next(flowElements, nextFlowElement, map, nextUser); } //子任务的起点 else if (nextFlowElement instanceof StartEvent) { next(flowElements, nextFlowElement, map, nextUser); } //结束节点 else if (nextFlowElement instanceof EndEvent) { next(flowElements, nextFlowElement, map, nextUser); } } } } } /** * 判断是否是多实例子流程并且需要设置集合类型变量 */ public static boolean checkSubProcess(String Id, Collection<FlowElement> flowElements, List<UserTask> nextUser) { for (FlowElement flowElement1 : flowElements) { if (flowElement1 instanceof SubProcess && flowElement1.getId().equals(Id)) { SubProcess sp = (SubProcess) flowElement1; if (sp.getLoopCharacteristics() != null) { String inputDataItem = sp.getLoopCharacteristics().getInputDataItem(); UserTask userTask = new UserTask(); userTask.setId(sp.getId()); userTask.setLoopCharacteristics(sp.getLoopCharacteristics()); userTask.setName(sp.getName()); nextUser.add(userTask); return true; } } } return false; } /** * 查询一个节点的是否子任务中的节点,如果是,返回子任务 * * @param flowElements 全流程的节点集合 * @param flowElement 当前节点 * @return */ public static FlowElement getSubProcess(Collection<FlowElement> flowElements, FlowElement flowElement) { for (FlowElement flowElement1 : flowElements) { if (flowElement1 instanceof SubProcess) { for (FlowElement flowElement2 : ((SubProcess) flowElement1).getFlowElements()) { if (flowElement.equals(flowElement2)) { return flowElement1; } } } } return null; } /** * 根据ID查询流程节点对象, 如果是子任务,则返回子任务的开始节点 * * @param Id 节点ID * @param flowElements 流程节点集合 * @return */ public static FlowElement getFlowElementById(String Id, Collection<FlowElement> flowElements) { for (FlowElement flowElement : flowElements) { if (flowElement.getId().equals(Id)) { //如果是子任务,则查询出子任务的开始节点 if (flowElement instanceof SubProcess) { return getStartFlowElement(((SubProcess) flowElement).getFlowElements()); } return flowElement; } if (flowElement instanceof SubProcess) { FlowElement flowElement1 = getFlowElementById(Id, ((SubProcess) flowElement).getFlowElements()); if (flowElement1 != null) { return flowElement1; } } } return null; } /** * 返回流程的开始节点 * * @param flowElements 节点集合 * @description: */ public static FlowElement getStartFlowElement(Collection<FlowElement> flowElements) { for (FlowElement flowElement : flowElements) { if (flowElement instanceof StartEvent) { return flowElement; } } return null; } /** * 校验el表达式 * * @param map * @param expression * @return */ public static boolean expressionResult(Map<String, Object> map, String expression) { Expression exp = AviatorEvaluator.compile(expression); final Object execute = exp.execute(map); return Boolean.parseBoolean(String.valueOf(execute)); } }
2929004360/ruoyi-sign
31,468
ruoyi-flowable/src/main/java/com/ruoyi/flowable/flow/FlowableUtils.java
package com.ruoyi.flowable.flow; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.exception.ServiceException; import lombok.extern.slf4j.Slf4j; import org.flowable.bpmn.model.*; import org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior; import org.flowable.engine.impl.bpmn.behavior.SequentialMultiInstanceBehavior; import org.flowable.task.api.history.HistoricTaskInstance; import java.util.*; /** * @author XuanXuan * @date 2021-04-03 23:57 */ @Slf4j public class FlowableUtils { /** * 根据节点,获取入口连线 * @param source * @return */ public static List<SequenceFlow> getElementIncomingFlows(FlowElement source) { List<SequenceFlow> sequenceFlows = null; if (source instanceof FlowNode) { sequenceFlows = ((FlowNode) source).getIncomingFlows(); } else if (source instanceof Gateway) { sequenceFlows = ((Gateway) source).getIncomingFlows(); } else if (source instanceof SubProcess) { sequenceFlows = ((SubProcess) source).getIncomingFlows(); } else if (source instanceof StartEvent) { sequenceFlows = ((StartEvent) source).getIncomingFlows(); } else if (source instanceof EndEvent) { sequenceFlows = ((EndEvent) source).getIncomingFlows(); } return sequenceFlows; } /** * 根据节点,获取出口连线 * @param source * @return */ public static List<SequenceFlow> getElementOutgoingFlows(FlowElement source) { List<SequenceFlow> sequenceFlows = null; if (source instanceof FlowNode) { sequenceFlows = ((FlowNode) source).getOutgoingFlows(); } else if (source instanceof Gateway) { sequenceFlows = ((Gateway) source).getOutgoingFlows(); } else if (source instanceof SubProcess) { sequenceFlows = ((SubProcess) source).getOutgoingFlows(); } else if (source instanceof StartEvent) { sequenceFlows = ((StartEvent) source).getOutgoingFlows(); } else if (source instanceof EndEvent) { sequenceFlows = ((EndEvent) source).getOutgoingFlows(); } return sequenceFlows; } /** * 获取全部节点列表,包含子流程节点 * @param flowElements * @param allElements * @return */ public static Collection<FlowElement> getAllElements(Collection<FlowElement> flowElements, Collection<FlowElement> allElements) { allElements = allElements == null ? new ArrayList<>() : allElements; for (FlowElement flowElement : flowElements) { allElements.add(flowElement); if (flowElement instanceof SubProcess) { // 继续深入子流程,进一步获取子流程 allElements = FlowableUtils.getAllElements(((SubProcess) flowElement).getFlowElements(), allElements); } } return allElements; } /** * 迭代获取父级任务节点列表,向前找 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param userTaskList 已找到的用户任务节点 * @return */ public static List<UserTask> iteratorFindParentUserTasks(FlowElement source, Set<String> hasSequenceFlow, List<UserTask> userTaskList) { userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList; hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (source instanceof StartEvent && source.getSubProcess() != null) { userTaskList = iteratorFindParentUserTasks(source.getSubProcess(), hasSequenceFlow, userTaskList); } // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 类型为用户节点,则新增父级节点 if (sequenceFlow.getSourceFlowElement() instanceof UserTask) { userTaskList.add((UserTask) sequenceFlow.getSourceFlowElement()); continue; } // 类型为子流程,则添加子流程开始节点出口处相连的节点 if (sequenceFlow.getSourceFlowElement() instanceof SubProcess) { // 获取子流程用户任务节点 List<UserTask> childUserTaskList = findChildProcessUserTasks((StartEvent) ((SubProcess) sequenceFlow.getSourceFlowElement()).getFlowElements().toArray()[0], null, null); // 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续 if (childUserTaskList != null && childUserTaskList.size() > 0) { userTaskList.addAll(childUserTaskList); continue; } } // 继续迭代 userTaskList = iteratorFindParentUserTasks(sequenceFlow.getSourceFlowElement(), hasSequenceFlow, userTaskList); } } return userTaskList; } /** * 根据正在运行的任务节点,迭代获取子级任务节点列表,向后找 * @param source 起始节点 * @param runTaskKeyList 正在运行的任务 Key,用于校验任务节点是否是正在运行的节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param userTaskList 需要撤回的用户任务列表 * @return */ public static List<UserTask> iteratorFindChildUserTasks(FlowElement source, List<String> runTaskKeyList, Set<String> hasSequenceFlow, List<UserTask> userTaskList) { hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList; // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (source instanceof StartEvent && source.getSubProcess() != null) { userTaskList = iteratorFindChildUserTasks(source.getSubProcess(), runTaskKeyList, hasSequenceFlow, userTaskList); } // 根据类型,获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 如果为用户任务类型,且任务节点的 Key 正在运行的任务中存在,添加 if (sequenceFlow.getTargetFlowElement() instanceof UserTask && runTaskKeyList.contains((sequenceFlow.getTargetFlowElement()).getId())) { userTaskList.add((UserTask) sequenceFlow.getTargetFlowElement()); continue; } // 如果节点为子流程节点情况,则从节点中的第一个节点开始获取 if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) { List<UserTask> childUserTaskList = iteratorFindChildUserTasks((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), runTaskKeyList, hasSequenceFlow, null); // 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续 if (childUserTaskList != null && childUserTaskList.size() > 0) { userTaskList.addAll(childUserTaskList); continue; } } // 继续迭代 userTaskList = iteratorFindChildUserTasks(sequenceFlow.getTargetFlowElement(), runTaskKeyList, hasSequenceFlow, userTaskList); } } return userTaskList; } /** * 迭代获取子流程用户任务节点 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param userTaskList 需要撤回的用户任务列表 * @return */ public static List<UserTask> findChildProcessUserTasks(FlowElement source, Set<String> hasSequenceFlow, List<UserTask> userTaskList) { hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList; // 根据类型,获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 如果为用户任务类型,且任务节点的 Key 正在运行的任务中存在,添加 if (sequenceFlow.getTargetFlowElement() instanceof UserTask) { userTaskList.add((UserTask) sequenceFlow.getTargetFlowElement()); continue; } // 如果节点为子流程节点情况,则从节点中的第一个节点开始获取 if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) { List<UserTask> childUserTaskList = findChildProcessUserTasks((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), hasSequenceFlow, null); // 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续 if (childUserTaskList != null && childUserTaskList.size() > 0) { userTaskList.addAll(childUserTaskList); continue; } } // 继续迭代 userTaskList = findChildProcessUserTasks(sequenceFlow.getTargetFlowElement(), hasSequenceFlow, userTaskList); } } return userTaskList; } /** * 从后向前寻路,获取所有脏线路上的点 * @param source 起始节点 * @param passRoads 已经经过的点集合 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param targets 目标脏线路终点 * @param dirtyRoads 确定为脏数据的点,因为不需要重复,因此使用 set 存储 * @return */ public static Set<String> iteratorFindDirtyRoads(FlowElement source, List<String> passRoads, Set<String> hasSequenceFlow, List<String> targets, Set<String> dirtyRoads) { passRoads = passRoads == null ? new ArrayList<>() : passRoads; dirtyRoads = dirtyRoads == null ? new HashSet<>() : dirtyRoads; hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (source instanceof StartEvent && source.getSubProcess() != null) { dirtyRoads = iteratorFindDirtyRoads(source.getSubProcess(), passRoads, hasSequenceFlow, targets, dirtyRoads); } // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 新增经过的路线 passRoads.add(sequenceFlow.getSourceFlowElement().getId()); // 如果此点为目标点,确定经过的路线为脏线路,添加点到脏线路中,然后找下个连线 if (targets.contains(sequenceFlow.getSourceFlowElement().getId())) { dirtyRoads.addAll(passRoads); continue; } // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (sequenceFlow.getSourceFlowElement() instanceof SubProcess) { dirtyRoads = findChildProcessAllDirtyRoad((StartEvent) ((SubProcess) sequenceFlow.getSourceFlowElement()).getFlowElements().toArray()[0], null, dirtyRoads); // 是否存在子流程上,true 是,false 否 Boolean isInChildProcess = dirtyTargetInChildProcess((StartEvent) ((SubProcess) sequenceFlow.getSourceFlowElement()).getFlowElements().toArray()[0], null, targets, null); if (isInChildProcess) { // 已在子流程上找到,该路线结束 continue; } } // 继续迭代 dirtyRoads = iteratorFindDirtyRoads(sequenceFlow.getSourceFlowElement(), passRoads, hasSequenceFlow, targets, dirtyRoads); } } return dirtyRoads; } /** * 迭代获取子流程脏路线 * 说明,假如回退的点就是子流程,那么也肯定会回退到子流程最初的用户任务节点,因此子流程中的节点全是脏路线 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param dirtyRoads 确定为脏数据的点,因为不需要重复,因此使用 set 存储 * @return */ public static Set<String> findChildProcessAllDirtyRoad(FlowElement source, Set<String> hasSequenceFlow, Set<String> dirtyRoads) { hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; dirtyRoads = dirtyRoads == null ? new HashSet<>() : dirtyRoads; // 根据类型,获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 添加脏路线 dirtyRoads.add(sequenceFlow.getTargetFlowElement().getId()); // 如果节点为子流程节点情况,则从节点中的第一个节点开始获取 if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) { dirtyRoads = findChildProcessAllDirtyRoad((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), hasSequenceFlow, dirtyRoads); } // 继续迭代 dirtyRoads = findChildProcessAllDirtyRoad(sequenceFlow.getTargetFlowElement(), hasSequenceFlow, dirtyRoads); } } return dirtyRoads; } /** * 判断脏路线结束节点是否在子流程上 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param targets 判断脏路线节点是否存在子流程上,只要存在一个,说明脏路线只到子流程为止 * @param inChildProcess 是否存在子流程上,true 是,false 否 * @return */ public static Boolean dirtyTargetInChildProcess(FlowElement source, Set<String> hasSequenceFlow, List<String> targets, Boolean inChildProcess) { hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; inChildProcess = inChildProcess == null ? false : inChildProcess; // 根据类型,获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (sequenceFlows != null && !inChildProcess) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 如果发现目标点在子流程上存在,说明只到子流程为止 if (targets.contains(sequenceFlow.getTargetFlowElement().getId())) { inChildProcess = true; break; } // 如果节点为子流程节点情况,则从节点中的第一个节点开始获取 if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) { inChildProcess = dirtyTargetInChildProcess((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), hasSequenceFlow, targets, inChildProcess); } // 继续迭代 inChildProcess = dirtyTargetInChildProcess(sequenceFlow.getTargetFlowElement(), hasSequenceFlow, targets, inChildProcess); } } return inChildProcess; } /** * 迭代从后向前扫描,判断目标节点相对于当前节点是否是串行 * 不存在直接回退到子流程中的情况,但存在从子流程出去到父流程情况 * @param source 起始节点 * @param isSequential 是否串行 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param targetKsy 目标节点 * @return */ public static Boolean iteratorCheckSequentialReferTarget(FlowElement source, String targetKsy, Set<String> hasSequenceFlow, Boolean isSequential) { isSequential = isSequential == null ? true : isSequential; hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (source instanceof StartEvent && source.getSubProcess() != null) { isSequential = iteratorCheckSequentialReferTarget(source.getSubProcess(), targetKsy, hasSequenceFlow, isSequential); } // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 如果目标节点已被判断为并行,后面都不需要执行,直接返回 if (isSequential == false) { break; } // 这条线路存在目标节点,这条线路完成,进入下个线路 if (targetKsy.equals(sequenceFlow.getSourceFlowElement().getId())) { continue; } if (sequenceFlow.getSourceFlowElement() instanceof StartEvent) { isSequential = false; break; } // 否则就继续迭代 isSequential = iteratorCheckSequentialReferTarget(sequenceFlow.getSourceFlowElement(), targetKsy, hasSequenceFlow, isSequential); } } return isSequential; } /** * 从后向前寻路,获取到达节点的所有路线 * 不存在直接回退到子流程,但是存在回退到父级流程的情况 * @param source 起始节点 * @param passRoads 已经经过的点集合 * @param roads 路线 * @return */ public static List<List<UserTask>> findRoad(FlowElement source, List<UserTask> passRoads, Set<String> hasSequenceFlow, List<List<UserTask>> roads) { passRoads = passRoads == null ? new ArrayList<>() : passRoads; roads = roads == null ? new ArrayList<>() : roads; hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow; // 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代 if (source instanceof StartEvent && source.getSubProcess() != null) { roads = findRoad(source.getSubProcess(), passRoads, hasSequenceFlow, roads); } // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null && sequenceFlows.size() != 0) { for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); // 添加经过路线 if (sequenceFlow.getSourceFlowElement() instanceof UserTask) { passRoads.add((UserTask) sequenceFlow.getSourceFlowElement()); } // 继续迭代 roads = findRoad(sequenceFlow.getSourceFlowElement(), passRoads, hasSequenceFlow, roads); } } else { // 添加路线 roads.add(passRoads); } return roads; } /** * 历史节点数据清洗,清洗掉又回滚导致的脏数据 * @param allElements 全部节点信息 * @param historicTaskInstanceList 历史任务实例信息,数据采用开始时间升序 * @return */ public static List<String> historicTaskInstanceClean(Collection<FlowElement> allElements, List<HistoricTaskInstance> historicTaskInstanceList) { // 会签节点收集 List<String> multiTask = new ArrayList<>(); allElements.forEach(flowElement -> { if (flowElement instanceof UserTask) { // 如果该节点的行为为会签行为,说明该节点为会签节点 if (((UserTask) flowElement).getBehavior() instanceof ParallelMultiInstanceBehavior || ((UserTask) flowElement).getBehavior() instanceof SequentialMultiInstanceBehavior) { multiTask.add(flowElement.getId()); } } }); // 循环放入栈,栈 LIFO:后进先出 Stack<HistoricTaskInstance> stack = new Stack<>(); historicTaskInstanceList.forEach(item -> stack.push(item)); // 清洗后的历史任务实例 List<String> lastHistoricTaskInstanceList = new ArrayList<>(); // 网关存在可能只走了部分分支情况,且还存在跳转废弃数据以及其他分支数据的干扰,因此需要对历史节点数据进行清洗 // 临时用户任务 key StringBuilder userTaskKey = null; // 临时被删掉的任务 key,存在并行情况 List<String> deleteKeyList = new ArrayList<>(); // 临时脏数据线路 List<Set<String>> dirtyDataLineList = new ArrayList<>(); // 由某个点跳到会签点,此时出现多个会签实例对应 1 个跳转情况,需要把这些连续脏数据都找到 // 会签特殊处理下标 int multiIndex = -1; // 会签特殊处理 key StringBuilder multiKey = null; // 会签特殊处理操作标识 boolean multiOpera = false; while (!stack.empty()) { // 从这里开始 userTaskKey 都还是上个栈的 key // 是否是脏数据线路上的点 final boolean[] isDirtyData = {false}; for (Set<String> oldDirtyDataLine : dirtyDataLineList) { if (oldDirtyDataLine.contains(stack.peek().getTaskDefinitionKey())) { isDirtyData[0] = true; } } // 删除原因不为空,说明从这条数据开始回跳或者回退的 // MI_END:会签完成后,其他未签到节点的删除原因,不在处理范围内 if (stack.peek().getDeleteReason() != null && !stack.peek().getDeleteReason().equals("MI_END")) { // 可以理解为脏线路起点 String dirtyPoint = ""; if (stack.peek().getDeleteReason().indexOf("Change activity to ") >= 0) { dirtyPoint = stack.peek().getDeleteReason().replace("Change activity to ", ""); } // 会签回退删除原因有点不同 if (stack.peek().getDeleteReason().indexOf("Change parent activity to ") >= 0) { dirtyPoint = stack.peek().getDeleteReason().replace("Change parent activity to ", ""); } FlowElement dirtyTask = null; // 获取变更节点的对应的入口处连线 // 如果是网关并行回退情况,会变成两条脏数据路线,效果一样 for (FlowElement flowElement : allElements) { if (flowElement.getId().equals(stack.peek().getTaskDefinitionKey())) { dirtyTask = flowElement; } } // 获取脏数据线路 Set<String> dirtyDataLine = FlowableUtils.iteratorFindDirtyRoads(dirtyTask, null, null, Arrays.asList(dirtyPoint.split(",")), null); // 自己本身也是脏线路上的点,加进去 dirtyDataLine.add(stack.peek().getTaskDefinitionKey()); log.info(stack.peek().getTaskDefinitionKey() + "点脏路线集合:" + dirtyDataLine); // 是全新的需要添加的脏线路 boolean isNewDirtyData = true; for (int i = 0; i < dirtyDataLineList.size(); i++) { // 如果发现他的上个节点在脏线路内,说明这个点可能是并行的节点,或者连续驳回 // 这时,都以之前的脏线路节点为标准,只需合并脏线路即可,也就是路线补全 if (dirtyDataLineList.get(i).contains(userTaskKey.toString())) { isNewDirtyData = false; dirtyDataLineList.get(i).addAll(dirtyDataLine); } } // 已确定时全新的脏线路 if (isNewDirtyData) { // deleteKey 单一路线驳回到并行,这种同时生成多个新实例记录情况,这时 deleteKey 其实是由多个值组成 // 按照逻辑,回退后立刻生成的实例记录就是回退的记录 // 至于驳回所生成的 Key,直接从删除原因中获取,因为存在驳回到并行的情况 deleteKeyList.add(dirtyPoint + ","); dirtyDataLineList.add(dirtyDataLine); } // 添加后,现在这个点变成脏线路上的点了 isDirtyData[0] = true; } // 如果不是脏线路上的点,说明是有效数据,添加历史实例 Key if (!isDirtyData[0]) { lastHistoricTaskInstanceList.add(stack.peek().getTaskDefinitionKey()); } // 校验脏线路是否结束 for (int i = 0; i < deleteKeyList.size(); i ++) { // 如果发现脏数据属于会签,记录下下标与对应 Key,以备后续比对,会签脏数据范畴开始 if (multiKey == null && multiTask.contains(stack.peek().getTaskDefinitionKey()) && deleteKeyList.get(i).contains(stack.peek().getTaskDefinitionKey())) { multiIndex = i; multiKey = new StringBuilder(stack.peek().getTaskDefinitionKey()); } // 会签脏数据处理,节点退回会签清空 // 如果在会签脏数据范畴中发现 Key改变,说明会签脏数据在上个节点就结束了,可以把会签脏数据删掉 if (multiKey != null && !multiKey.toString().equals(stack.peek().getTaskDefinitionKey())) { deleteKeyList.set(multiIndex , deleteKeyList.get(multiIndex).replace(stack.peek().getTaskDefinitionKey() + ",", "")); multiKey = null; // 结束进行下校验删除 multiOpera = true; } // 其他脏数据处理 // 发现该路线最后一条脏数据,说明这条脏数据线路处理完了,删除脏数据信息 // 脏数据产生的新实例中是否包含这条数据 if (multiKey == null && deleteKeyList.get(i).contains(stack.peek().getTaskDefinitionKey())) { // 删除匹配到的部分 deleteKeyList.set(i , deleteKeyList.get(i).replace(stack.peek().getTaskDefinitionKey() + ",", "")); } // 如果每组中的元素都以匹配过,说明脏数据结束 if ("".equals(deleteKeyList.get(i))) { // 同时删除脏数据 deleteKeyList.remove(i); dirtyDataLineList.remove(i); break; } } // 会签数据处理需要在循环外处理,否则可能导致溢出 // 会签的数据肯定是之前放进去的所以理论上不会溢出,但还是校验下 if (multiOpera && deleteKeyList.size() > multiIndex && "".equals(deleteKeyList.get(multiIndex))) { // 同时删除脏数据 deleteKeyList.remove(multiIndex); dirtyDataLineList.remove(multiIndex); multiIndex = -1; multiOpera = false; } // pop() 方法与 peek() 方法不同,在返回值的同时,会把值从栈中移除 // 保存新的 userTaskKey 在下个循环中使用 userTaskKey = new StringBuilder(stack.pop().getTaskDefinitionKey()); } log.info("清洗后的历史节点数据:" + lastHistoricTaskInstanceList); return lastHistoricTaskInstanceList; } /** * 深搜递归获取流程未通过的节点 * @param bpmnModel 流程模型 * @param unfinishedTaskSet 未结束的任务节点 * @param finishedSequenceFlowSet 已经完成的连线 * @param finishedTaskSet 已完成的任务节点 * @return */ public static Set<String> dfsFindRejects(BpmnModel bpmnModel, Set<String> unfinishedTaskSet, Set<String> finishedSequenceFlowSet, Set<String> finishedTaskSet) { if (ObjectUtil.isNull(bpmnModel)) { throw new ServiceException("流程模型不存在"); } Collection<FlowElement> allElements = getAllElements(bpmnModel.getMainProcess().getFlowElements(), null); Set<String> rejectedSet = new HashSet<>(); for (FlowElement flowElement : allElements) { // 用户节点且未结束元素 if (flowElement instanceof UserTask && unfinishedTaskSet.contains(flowElement.getId())) { List<String> hasSequenceFlow = iteratorFindFinishes(flowElement, null); List<String> rejects = iteratorFindRejects(flowElement, finishedSequenceFlowSet, finishedTaskSet, hasSequenceFlow, null); rejectedSet.addAll(rejects); } } return rejectedSet; } /** * 迭代获取父级节点列表,向前找 * @param source 起始节点 * @param hasSequenceFlow 已经经过的连线的ID,用于判断线路是否重复 * @return */ public static List<String> iteratorFindFinishes(FlowElement source, List<String> hasSequenceFlow) { hasSequenceFlow = hasSequenceFlow == null ? new ArrayList<>() : hasSequenceFlow; // 根据类型,获取入口连线 List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); FlowElement finishedElement = sequenceFlow.getSourceFlowElement(); // 类型为子流程,则添加子流程开始节点出口处相连的节点 if (finishedElement instanceof SubProcess) { FlowElement firstElement = (StartEvent) ((SubProcess) finishedElement).getFlowElements().toArray()[0]; // 获取子流程的连线 hasSequenceFlow.addAll(iteratorFindFinishes(firstElement, null)); } // 继续迭代 hasSequenceFlow = iteratorFindFinishes(finishedElement, hasSequenceFlow); } } return hasSequenceFlow; } /** * 根据正在运行的任务节点,迭代获取子级任务节点列表,向后找 * @param source 起始节点 * @param finishedSequenceFlowSet 已经完成的连线 * @param finishedTaskSet 已经完成的任务节点 * @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复 * @param rejectedList 未通过的元素 * @return */ public static List<String> iteratorFindRejects(FlowElement source, Set<String> finishedSequenceFlowSet, Set<String> finishedTaskSet , List<String> hasSequenceFlow, List<String> rejectedList) { hasSequenceFlow = hasSequenceFlow == null ? new ArrayList<>() : hasSequenceFlow; rejectedList = rejectedList == null ? new ArrayList<>() : rejectedList; // 根据类型,获取出口连线 List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source); if (sequenceFlows != null) { // 循环找到目标元素 for (SequenceFlow sequenceFlow: sequenceFlows) { // 如果发现连线重复,说明循环了,跳过这个循环 if (hasSequenceFlow.contains(sequenceFlow.getId())) { continue; } // 添加已经走过的连线 hasSequenceFlow.add(sequenceFlow.getId()); FlowElement targetElement = sequenceFlow.getTargetFlowElement(); // 添加未完成的节点 if (finishedTaskSet.contains(targetElement.getId())) { rejectedList.add(targetElement.getId()); } // 添加未完成的连线 if (finishedSequenceFlowSet.contains(sequenceFlow.getId())) { rejectedList.add(sequenceFlow.getId()); } // 如果节点为子流程节点情况,则从节点中的第一个节点开始获取 if (targetElement instanceof SubProcess) { FlowElement firstElement = (FlowElement) (((SubProcess) targetElement).getFlowElements().toArray()[0]); List<String> childList = iteratorFindRejects(firstElement, finishedSequenceFlowSet, finishedTaskSet, hasSequenceFlow, null); // 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续 if (childList != null && childList.size() > 0) { rejectedList.addAll(childList); continue; } } // 继续迭代 rejectedList = iteratorFindRejects(targetElement, finishedSequenceFlowSet, finishedTaskSet, hasSequenceFlow, rejectedList); } } return rejectedList; } }
2929004360/ruoyi-sign
1,775
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfModelProcdef.java
package com.ruoyi.flowable.domain; import com.ruoyi.common.core.domain.BaseEntity; /** * 模型部署对象 wf_model_procdef * * @author fengcheng * @date 2024-07-11 */ public class WfModelProcdef extends BaseEntity { private static final long serialVersionUID = 1L; /** 模型ID */ private String modelId; /** 部署id */ private String procdefId; /** * 表单类型 */ private String formType; /** * 表单创建路径 */ private String formCreatePath; /** * 表单查看路由 */ private String formViewPath; public void setModelId(String modelId) { this.modelId = modelId; } public String getModelId() { return modelId; } public void setProcdefId(String procdefId) { this.procdefId = procdefId; } public String getProcdefId() { return procdefId; } public String getFormType() { return formType; } public void setFormType(String formType) { this.formType = formType; } public String getFormCreatePath() { return formCreatePath; } public void setFormCreatePath(String formCreatePath) { this.formCreatePath = formCreatePath; } public String getFormViewPath() { return formViewPath; } public void setFormViewPath(String formViewPath) { this.formViewPath = formViewPath; } @Override public String toString() { return "WfModelProcdef{" + "modelId='" + modelId + '\'' + ", procdefId='" + procdefId + '\'' + ", formType='" + formType + '\'' + ", formCreatePath='" + formCreatePath + '\'' + ", formViewPath='" + formViewPath + '\'' + '}'; } }
2929004360/ruoyi-sign
1,030
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfForm.java
package com.ruoyi.flowable.domain; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 流程表单对象 wf_form * * @author fengcheng * @createTime 2022/3/7 22:07 */ @Data @EqualsAndHashCode(callSuper = true) @TableName("wf_form") public class WfForm extends BaseEntity { private static final long serialVersionUID = 1L; /** * 表单主键 */ @TableId(value = "form_id") private String formId; /** * 用户id */ private Long userId; /** * 部门id */ private Long deptId; /** * 创建人 */ private String userName; /** * 部门名称 */ private String deptName; /** * 表单名称 */ private String formName; /** * 使用类型(1=本级使用,2=本下级使用) */ private String type; /** * 表单内容 */ private String content; /** * 备注 */ private String remark; }
2929004360/ruoyi-sign
1,141
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/ActReModel.java
package com.ruoyi.flowable.domain; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Date; /** * 流程模型对象 ACT_RE_MODEL * * @author fengcheng */ @Data @EqualsAndHashCode(callSuper = true) public class ActReModel extends BaseEntity { private static final long serialVersionUID = 1L; /** * 数据的唯一标识 */ private String id; /** * 数据版本号 */ private Integer rev; /** * 数据名称 */ private String name; /** * 数据键 */ private String key; /** * 数据类别 */ private String category; /** * 数据创建时间 */ private Date createTime; /** * 数据最后更新时间 */ private Date lastUpdateTime; /** * 数据版本号 */ private Integer version; /** * 数据元信息 */ private String metaInfo; /** * 部署ID */ private String deploymentId; /** * 编辑器值ID */ private String editorSourceValueId; /** * 辑器额外值ID */ private String editorSourceExtraValueId; /** * 租户ID */ private String tenantId; }
2929004360/ruoyi-sign
1,123
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfIcon.java
package com.ruoyi.flowable.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 流程图标对象 wf_icon * * @author fengcheng * @date 2024-07-09 */ public class WfIcon extends BaseEntity { private static final long serialVersionUID = 1L; /** 流程部署id */ @Excel(name = "流程部署id") private String deploymentId; /** 流程图标路径 */ @Excel(name = "流程图标路径") private String icon; public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getDeploymentId() { return deploymentId; } public void setIcon(String icon) { this.icon = icon; } public String getIcon() { return icon; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("deploymentId", getDeploymentId()) .append("icon", getIcon()) .toString(); } }
2929004360/ruoyi-sign
1,558
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/Deploy.java
package com.ruoyi.flowable.domain; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 部署对象 deploy * * @author fengcheng */ @Data @EqualsAndHashCode(callSuper = true) public class Deploy extends BaseEntity { private static final long serialVersionUID = 1L; /** * 数据的唯一标识 */ private String id; /** * 数据的版本 */ private Integer rev; /** * 数据所属的类别 */ private String category; /** * 数据名称 */ private String name; /** * 数据的键 */ private String key; /** * 数据版本 */ private Integer version; /** * 部署数据的唯一标识 */ private String deploymentId; /** * 资源名称 */ private String resourceName; /** * 模板资源名称 */ private String dgrmResourceName; /** * 数据描述 */ private String description; /** * 是否具有启动表单键 */ private Integer hasStartFormKey; /** * 是否有图形表示 */ private Integer hasGraphicalNotation; /** * 挂起状态 */ private Integer suspensionState; /** * 租户ID */ private String tenantId; /** * 引擎版本 */ private String engineVersion; /** * 继承自 */ private String derivedFrom; /** * 根继承自 */ private String derivedFromRoot; /** * 继承版本 */ private Integer derivedVersion; /** * 表单类型 */ private String formType; /** * 表单创建路径 */ private String formCreatePath; }
2929004360/ruoyi-sign
1,285
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfCopy.java
package com.ruoyi.flowable.domain; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 流程抄送对象 wf_copy * * @author fengcheng * @date 2022-05-19 */ @Data @EqualsAndHashCode(callSuper = true) @TableName("wf_copy") public class WfCopy extends BaseEntity { private static final long serialVersionUID=1L; /** * 抄送主键 */ @TableId(value = "copy_id") private String copyId; /** * 抄送标题 */ private String title; /** * 流程主键 */ private String processId; /** * 流程名称 */ private String processName; /** * 流程分类主键 */ private String categoryId; /** * 部署主键 */ private String deploymentId; /** * 流程实例主键 */ private String instanceId; /** * 任务主键 */ private String taskId; /** * 用户主键 */ private Long userId; /** * 发起人Id */ private Long originatorId; /** * 发起人名称 */ private String originatorName; /** * 删除标志(0代表存在 2代表删除) */ @TableLogic private String delFlag; }
2929004360/ruoyi-sign
2,120
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfModelPermission.java
package com.ruoyi.flowable.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 流程模型权限对象 wf_model_permission * * @author fengcheng * @date 2024-07-10 */ public class WfModelPermission extends BaseEntity { private static final long serialVersionUID = 1L; /** 流程模型权限id */ private String modelPermissionId; /** 流程模型ID */ @Excel(name = "流程模型ID") private String modelId; /** 权限id */ @Excel(name = "权限id") private Long permissionId; /** 名称 */ @Excel(name = "名称") private String name; /** 权限类型(1=人员权限,2=部门权限) */ @Excel(name = "权限类型(1=人员权限,2=部门权限)") private String type; public void setModelPermissionId(String modelPermissionId) { this.modelPermissionId = modelPermissionId; } public String getModelPermissionId() { return modelPermissionId; } public void setModelId(String modelId) { this.modelId = modelId; } public String getModelId() { return modelId; } public void setPermissionId(Long permissionId) { this.permissionId = permissionId; } public Long getPermissionId() { return permissionId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setType(String type) { this.type = type; } public String getType() { return type; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("modelPermissionId", getModelPermissionId()) .append("modelId", getModelId()) .append("permissionId", getPermissionId()) .append("name", getName()) .append("type", getType()) .append("createTime", getCreateTime()) .append("updateTime", getUpdateTime()) .toString(); } }
2929004360/ruoyi-sign
1,132
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfModelTemplate.java
package com.ruoyi.flowable.domain; import com.baomidou.mybatisplus.annotation.TableName; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 模型模板对象 wf_model_template * * @author fengcheng * @date 2024-07-17 */ @Data @EqualsAndHashCode(callSuper = true) @TableName("wf_model_template") public class WfModelTemplate extends BaseEntity { private static final long serialVersionUID = 1L; /** * 模型模板id */ private String modelTemplateId; /** * 部门id */ private Long deptId; /** * 模板名称 */ @Excel(name = "模板名称" ) private String name; /** * 部门名称 */ @Excel(name = "部门名称" ) private String deptName; /** * 使用类型(1=本级使用,2=本下级使用) */ @Excel(name = "使用类型" , readConverterExp = "1=本级使用,2=本下级使用" ) private String type; /** * 流程xml */ @Excel(name = "流程xml") private String bpmnXml; /** * 表单类型 */ @Excel(name = "表单类型" , readConverterExp = "0=流程表单.1=外置表单,2=节点独立表单" ) private String formType; }
2929004360/ruoyi-sign
1,217
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/WfModelAssociationTemplate.java
package com.ruoyi.flowable.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 模型关联模板对象 wf_model_association_template * * @author fengcheng * @date 2024-07-23 */ public class WfModelAssociationTemplate extends BaseEntity { private static final long serialVersionUID = 1L; /** 模型模板id */ @Excel(name = "模型模板id") private String modelTemplateId; /** 模型ID */ @Excel(name = "模型ID") private String modelId; public void setModelTemplateId(String modelTemplateId) { this.modelTemplateId = modelTemplateId; } public String getModelTemplateId() { return modelTemplateId; } public void setModelId(String modelId) { this.modelId = modelId; } public String getModelId() { return modelId; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("modelTemplateId", getModelTemplateId()) .append("modelId", getModelId()) .toString(); } }
2929004360/ruoyi-sign
1,815
ruoyi-flowable/src/main/java/com/ruoyi/flowable/constant/ProcessConstants.java
package com.ruoyi.flowable.constant; /** * 流程常量信息 * * @author fengcheng * @date 2021/4/17 22:46 */ public class ProcessConstants { public static final String SUFFIX = ".bpmn"; /** * 动态数据 */ public static final String DATA_TYPE = "dynamic"; /** * 单个审批人 */ public static final String USER_TYPE_ASSIGNEE = "assignee"; /** * 候选人 */ public static final String USER_TYPE_USERS = "candidateUsers"; /** * 审批组 */ public static final String USER_TYPE_ROUPS = "candidateGroups"; /** * 单个审批人 */ public static final String PROCESS_APPROVAL = "approval"; /** * 会签人员 */ public static final String PROCESS_MULTI_INSTANCE_USER = "userList"; /** * nameapace */ public static final String NAMASPASE = "http://flowable.org/bpmn"; /** * 会签节点 */ public static final String PROCESS_MULTI_INSTANCE = "multiInstance"; /** * 自定义属性 dataType */ public static final String PROCESS_CUSTOM_DATA_TYPE = "dataType"; /** * 自定义属性 userType */ public static final String PROCESS_CUSTOM_USER_TYPE = "userType"; /** * 自定义属性 localScope */ public static final String PROCESS_FORM_LOCAL_SCOPE = "localScope"; /** * 自定义属性 流程状态 */ public static final String PROCESS_STATUS_KEY = "processStatus"; /** * 流程跳过 */ public static final String FLOWABLE_SKIP_EXPRESSION_ENABLED = "_FLOWABLE_SKIP_EXPRESSION_ENABLED"; /** * 显示的按钮组 */ public static final String BUTTON_LIST = "buttonList"; /** * 业务id */ public static final String BUSINESS_ID = "businessId"; /** * 业务流程类型 */ public static final String BUSINESS_PROCESS_TYPE = "businessProcessType"; }
2929004360/ruoyi-sign
78,439
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfProcessServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.BetweenFormatter; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.common.exception.DataException; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.constant.TaskConstants; import com.ruoyi.flowable.core.FormConf; import com.ruoyi.flowable.core.domain.ProcessQuery; import com.ruoyi.flowable.domain.*; import com.ruoyi.flowable.domain.bo.DdToBpmn; import com.ruoyi.flowable.domain.bo.ResubmitProcess; import com.ruoyi.flowable.domain.bo.WfModelBo; import com.ruoyi.flowable.domain.vo.*; import com.ruoyi.flowable.enums.FormType; import com.ruoyi.flowable.factory.FlowServiceFactory; import com.ruoyi.flowable.flow.FlowableUtils; import com.ruoyi.flowable.handler.BusinessProcessDetailsHandler; import com.ruoyi.flowable.handler.DeleteProcessBusinessHandler; import com.ruoyi.flowable.handler.ResubmitProcessHandler; import com.ruoyi.flowable.mapper.WfDeployFormMapper; import com.ruoyi.flowable.mapper.WfProcessMapper; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import com.ruoyi.flowable.service.*; import com.ruoyi.flowable.utils.*; import com.ruoyi.system.api.service.ISysDeptServiceApi; import com.ruoyi.system.api.service.ISysRoleServiceApi; import com.ruoyi.system.api.service.ISysUserServiceApi; import lombok.RequiredArgsConstructor; import org.apache.commons.collections4.CollectionUtils; import org.flowable.bpmn.BpmnAutoLayout; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.*; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricActivityInstanceQuery; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.repository.ProcessDefinitionQuery; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.task.Comment; import org.flowable.identitylink.api.history.HistoricIdentityLink; import org.flowable.task.api.Task; import org.flowable.task.api.TaskQuery; import org.flowable.task.api.history.HistoricTaskInstance; import org.flowable.task.api.history.HistoricTaskInstanceQuery; import org.flowable.variable.api.history.HistoricVariableInstance; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.stream.Collectors; /** * @author fengcheng */ @RequiredArgsConstructor @Service public class WfProcessServiceImpl extends FlowServiceFactory implements IWfProcessService { @Lazy private final IWfRoamHistoricalService wfRoamHistoricalService; @Lazy private final IWfTaskService wfTaskService; @Lazy private final ISysUserServiceApi userServiceApi; @Lazy private final ISysRoleServiceApi roleServiceApi; @Lazy private final ISysDeptServiceApi deptServiceApi; @Lazy private final WfDeployFormMapper deployFormMapper; @Lazy private final IWfIconService wfIconService; @Lazy private final WfProcessMapper wfProcessMapper; @Lazy private final IWfModelService wfModelService; @Lazy private final IWfModelProcdefService wfModelProcdefService; /** * 仿钉钉流程转bpmn用 */ @Lazy private BpmnModel ddBpmnModel; @Lazy private Process ddProcess; @Lazy private List<SequenceFlow> ddSequenceFlows; @Lazy private final IWfFlowMenuService wfFlowMenuService; @Lazy private final DeleteProcessBusinessHandler deleteProcessBusinessHandler; @Lazy private final BusinessProcessDetailsHandler businessProcessDetailsHandler; @Lazy private final IWfBusinessProcessService wfBusinessProcessService; @Lazy private final ResubmitProcessHandler resubmitProcessHandler; /** * 流程定义列表 * * @param processQuery 查询参数 * @return 流程定义分页列表数据 */ @Override public List<WfDefinitionVo> selectPageStartProcessList(ProcessQuery processQuery) { List<Deploy> list = new ArrayList<>(); if (SecurityUtils.hasRole("admin" )) { list = wfProcessMapper.selectProcessList(processQuery, null); } else { List<WfModelVo> wfModelVoList = wfModelService.selectList(new WfModelBo()); List<String> modelIdList = wfModelVoList.stream().map(WfModelVo::getModelId).collect(Collectors.toList()); if (modelIdList.size() == 0) { return new ArrayList<>(); } List<String> procdefIdList = wfModelProcdefService.selectWfModelProcdefListByModelIdList(modelIdList); list = wfProcessMapper.selectProcessList(processQuery, procdefIdList); } List<WfDefinitionVo> definitionVoList = new ArrayList<>(); for (Deploy deploy : list) { String deploymentId = deploy.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); WfIcon wfIcon = wfIconService.selectWfIconByDeploymentId(deploymentId); WfDefinitionVo vo = new WfDefinitionVo(); vo.setDefinitionId(deploy.getId()); vo.setIcon(wfIcon.getIcon()); vo.setProcessKey(deploy.getKey()); vo.setProcessName(deploy.getName()); vo.setVersion(deploy.getVersion()); vo.setDeploymentId(deploy.getDeploymentId()); vo.setSuspended(deploy.getSuspensionState() == 1); vo.setFormType(deploy.getFormType()); vo.setFormCreatePath(deploy.getFormCreatePath()); // 流程定义时间 vo.setCategory(deployment.getCategory()); vo.setDeploymentTime(deployment.getDeploymentTime()); definitionVoList.add(vo); } return definitionVoList; } @Override public List<WfDefinitionVo> selectStartProcessList(ProcessQuery processQuery) { // 流程定义列表数据查询 ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery().latestVersion().active().orderByProcessDefinitionKey().asc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(processDefinitionQuery, processQuery); List<ProcessDefinition> definitionList = processDefinitionQuery.list(); List<WfDefinitionVo> definitionVoList = new ArrayList<>(); for (ProcessDefinition processDefinition : definitionList) { String deploymentId = processDefinition.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); WfDefinitionVo vo = new WfDefinitionVo(); vo.setDefinitionId(processDefinition.getId()); vo.setProcessKey(processDefinition.getKey()); vo.setProcessName(processDefinition.getName()); vo.setVersion(processDefinition.getVersion()); vo.setDeploymentId(processDefinition.getDeploymentId()); vo.setSuspended(processDefinition.isSuspended()); // 流程定义时间 vo.setCategory(deployment.getCategory()); vo.setDeploymentTime(deployment.getDeploymentTime()); definitionVoList.add(vo); } return definitionVoList; } @Override public TableDataInfo<WfTaskVo> selectPageOwnProcessList(ProcessQuery processQuery, PageQuery pageQuery) { Page<WfTaskVo> page = new Page<>(); HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().orderByProcessInstanceStartTime().desc(); if (!SecurityUtils.hasRole("admin" )) { historicProcessInstanceQuery.startedBy(TaskUtils.getUserId()); } if (ObjectUtil.isNotNull(processQuery.getIsComplete()) && !processQuery.getIsComplete()) { historicProcessInstanceQuery.unfinished(); } // 构建搜索条件 ProcessUtils.buildProcessSearch(historicProcessInstanceQuery, processQuery); int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery.listPage(offset, pageQuery.getPageSize()); page.setTotal(historicProcessInstanceQuery.count()); List<WfTaskVo> taskVoList = new ArrayList<>(); for (HistoricProcessInstance hisIns : historicProcessInstances) { WfTaskVo taskVo = new WfTaskVo(); // 获取流程状态 HistoricVariableInstance processStatusVariable = historyService.createHistoricVariableInstanceQuery().processInstanceId(hisIns.getId()).variableName(ProcessConstants.PROCESS_STATUS_KEY).singleResult(); String processStatus = null; if (ObjectUtil.isNotNull(processStatusVariable)) { processStatus = Convert.toStr(processStatusVariable.getValue()); } // 兼容旧流程 if (processStatus == null) { processStatus = ObjectUtil.isNull(hisIns.getEndTime()) ? ProcessStatus.RUNNING.getStatus() : ProcessStatus.COMPLETED.getStatus(); } taskVo.setProcessStatus(processStatus); taskVo.setCreateTime(hisIns.getStartTime()); taskVo.setFinishTime(hisIns.getEndTime()); taskVo.setProcInsId(hisIns.getId()); WfBusinessProcess wfBusinessProcess = wfBusinessProcessService.selectWfBusinessProcessByProcessId(hisIns.getId()); if (ObjectUtil.isNotNull(wfBusinessProcess)) { taskVo.setBusinessId(wfBusinessProcess.getBusinessId()); } // 计算耗时 if (Objects.nonNull(hisIns.getEndTime())) { taskVo.setDuration(DateUtils.getDatePoor(hisIns.getEndTime(), hisIns.getStartTime())); } else { taskVo.setDuration(DateUtils.getDatePoor(DateUtils.getNowDate(), hisIns.getStartTime())); } // 流程部署实例信息 Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(hisIns.getDeploymentId()).singleResult(); taskVo.setDeployId(hisIns.getDeploymentId()); WfModelProcdef wfModelProcdef = wfModelProcdefService.selectWfModelProcdefByProcdefId(hisIns.getDeploymentId()); taskVo.setProcDefId(hisIns.getProcessDefinitionId()); taskVo.setFormType(wfModelProcdef.getFormType()); taskVo.setFormViewPath(wfModelProcdef.getFormViewPath()); taskVo.setFormCreatePath(wfModelProcdef.getFormCreatePath()); taskVo.setProcDefName(hisIns.getProcessDefinitionName()); taskVo.setProcDefVersion(hisIns.getProcessDefinitionVersion()); taskVo.setCategory(deployment.getCategory()); // 当前所处流程 List<Task> taskList = taskService.createTaskQuery().processInstanceId(hisIns.getId()).includeIdentityLinks().list(); if (CollUtil.isNotEmpty(taskList)) { taskVo.setTaskName(taskList.stream().map(Task::getName).filter(StringUtils::isNotEmpty).collect(Collectors.joining("," ))); } taskVoList.add(taskVo); } page.setRecords(taskVoList); return TableDataInfo.build(page); } @Override public List<WfTaskVo> selectOwnProcessList(ProcessQuery processQuery) { HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().startedBy(TaskUtils.getUserId()).orderByProcessInstanceStartTime().desc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(historicProcessInstanceQuery, processQuery); List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery.list(); List<WfTaskVo> taskVoList = new ArrayList<>(); for (HistoricProcessInstance hisIns : historicProcessInstances) { WfTaskVo taskVo = new WfTaskVo(); taskVo.setCreateTime(hisIns.getStartTime()); taskVo.setFinishTime(hisIns.getEndTime()); taskVo.setProcInsId(hisIns.getId()); // 计算耗时 if (Objects.nonNull(hisIns.getEndTime())) { taskVo.setDuration(DateUtils.getDatePoor(hisIns.getEndTime(), hisIns.getStartTime())); } else { taskVo.setDuration(DateUtils.getDatePoor(DateUtils.getNowDate(), hisIns.getStartTime())); } // 流程部署实例信息 Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(hisIns.getDeploymentId()).singleResult(); taskVo.setDeployId(hisIns.getDeploymentId()); taskVo.setProcDefId(hisIns.getProcessDefinitionId()); taskVo.setProcDefName(hisIns.getProcessDefinitionName()); taskVo.setProcDefVersion(hisIns.getProcessDefinitionVersion()); taskVo.setCategory(deployment.getCategory()); // 当前所处流程 List<Task> taskList = taskService.createTaskQuery().processInstanceId(hisIns.getId()).includeIdentityLinks().list(); if (CollUtil.isNotEmpty(taskList)) { taskVo.setTaskName(taskList.stream().map(Task::getName).filter(StringUtils::isNotEmpty).collect(Collectors.joining("," ))); } taskVoList.add(taskVo); } return taskVoList; } @Override public TableDataInfo<WfTaskVo> selectPageTodoProcessList(ProcessQuery processQuery, PageQuery pageQuery) { Page<WfTaskVo> page = new Page<>(); TaskQuery taskQuery = taskService.createTaskQuery().active().includeProcessVariables().orderByTaskCreateTime().desc(); if (!SecurityUtils.hasRole("admin" )) { taskQuery.taskCandidateOrAssigned(TaskUtils.getUserId()); taskQuery.taskCandidateGroupIn(TaskUtils.getCandidateGroup()); } // 构建搜索条件 ProcessUtils.buildProcessSearch(taskQuery, processQuery); page.setTotal(taskQuery.count()); int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<Task> taskList = taskQuery.listPage(offset, pageQuery.getPageSize()); List<WfTaskVo> flowList = new ArrayList<>(); for (Task task : taskList) { WfTaskVo flowTask = new WfTaskVo(); // 当前流程信息 flowTask.setTaskId(task.getId()); flowTask.setParentTaskId(task.getParentTaskId()); flowTask.setTaskDefKey(task.getTaskDefinitionKey()); flowTask.setCreateTime(task.getCreateTime()); flowTask.setProcDefId(task.getProcessDefinitionId()); flowTask.setTaskName(task.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); WfModelProcdef wfModelProcdef = wfModelProcdefService.selectWfModelProcdefByProcdefId(pd.getDeploymentId()); flowTask.setFormType(wfModelProcdef.getFormType()); flowTask.setFormViewPath(wfModelProcdef.getFormViewPath()); flowTask.setDeployId(pd.getDeploymentId()); flowTask.setProcDefName(pd.getName()); flowTask.setProcDefVersion(pd.getVersion()); flowTask.setProcInsId(task.getProcessInstanceId()); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult(); Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); flowTask.setStartUserId(userId); flowTask.setStartUserName(nickName); // 流程变量 flowTask.setProcVars(task.getProcessVariables()); flowList.add(flowTask); } page.setRecords(flowList); return TableDataInfo.build(page); } @Override public List<WfTaskVo> selectTodoProcessList(ProcessQuery processQuery) { TaskQuery taskQuery = taskService.createTaskQuery().active().includeProcessVariables().taskCandidateOrAssigned(TaskUtils.getUserId()).taskCandidateGroupIn(TaskUtils.getCandidateGroup()).orderByTaskCreateTime().desc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(taskQuery, processQuery); List<Task> taskList = taskQuery.list(); List<WfTaskVo> taskVoList = new ArrayList<>(); for (Task task : taskList) { WfTaskVo taskVo = new WfTaskVo(); // 当前流程信息 taskVo.setTaskId(task.getId()); taskVo.setTaskDefKey(task.getTaskDefinitionKey()); taskVo.setCreateTime(task.getCreateTime()); taskVo.setProcDefId(task.getProcessDefinitionId()); taskVo.setTaskName(task.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); taskVo.setDeployId(pd.getDeploymentId()); taskVo.setProcDefName(pd.getName()); taskVo.setProcDefVersion(pd.getVersion()); taskVo.setProcInsId(task.getProcessInstanceId()); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult(); Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); taskVo.setStartUserId(userId); taskVo.setStartUserName(nickName); taskVoList.add(taskVo); } return taskVoList; } /** * 查询待签任务列表 * * @param processQuery * @param pageQuery 分页参数 * @return */ @Override public TableDataInfo<WfTaskVo> selectPageClaimProcessList(ProcessQuery processQuery, PageQuery pageQuery) { Page<WfTaskVo> page = new Page<>(); TaskQuery taskQuery = taskService.createTaskQuery().active().includeProcessVariables().orderByTaskCreateTime().desc(); if (!SecurityUtils.hasRole("admin" )) { taskQuery.taskCandidateUser(TaskUtils.getUserId()); taskQuery.taskCandidateGroupIn(TaskUtils.getCandidateGroup()); } // 构建搜索条件 ProcessUtils.buildProcessSearch(taskQuery, processQuery); page.setTotal(taskQuery.count()); int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<Task> taskList = taskQuery.listPage(offset, pageQuery.getPageSize()); List<WfTaskVo> flowList = new ArrayList<>(); for (Task task : taskList) { WfTaskVo flowTask = new WfTaskVo(); // 当前流程信息 flowTask.setTaskId(task.getId()); flowTask.setTaskDefKey(task.getTaskDefinitionKey()); flowTask.setCreateTime(task.getCreateTime()); flowTask.setProcDefId(task.getProcessDefinitionId()); flowTask.setTaskName(task.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); flowTask.setDeployId(pd.getDeploymentId()); flowTask.setProcDefName(pd.getName()); flowTask.setProcDefVersion(pd.getVersion()); flowTask.setProcInsId(task.getProcessInstanceId()); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult(); if (ObjectUtil.isNotNull(historicProcessInstance)) { Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); flowTask.setStartUserId(userId); flowTask.setStartUserName(nickName); } flowList.add(flowTask); } page.setRecords(flowList); return TableDataInfo.build(page); } @Override public List<WfTaskVo> selectClaimProcessList(ProcessQuery processQuery) { TaskQuery taskQuery = taskService.createTaskQuery().active().includeProcessVariables().taskCandidateUser(TaskUtils.getUserId()).taskCandidateGroupIn(TaskUtils.getCandidateGroup()).orderByTaskCreateTime().desc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(taskQuery, processQuery); List<Task> taskList = taskQuery.list(); List<WfTaskVo> flowList = new ArrayList<>(); for (Task task : taskList) { WfTaskVo flowTask = new WfTaskVo(); // 当前流程信息 flowTask.setTaskId(task.getId()); flowTask.setTaskDefKey(task.getTaskDefinitionKey()); flowTask.setCreateTime(task.getCreateTime()); flowTask.setProcDefId(task.getProcessDefinitionId()); flowTask.setTaskName(task.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); flowTask.setDeployId(pd.getDeploymentId()); flowTask.setProcDefName(pd.getName()); flowTask.setProcDefVersion(pd.getVersion()); flowTask.setProcInsId(task.getProcessInstanceId()); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult(); Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); flowTask.setStartUserId(userId); flowTask.setStartUserName(nickName); flowList.add(flowTask); } return flowList; } @Override public TableDataInfo<WfTaskVo> selectPageFinishedProcessList(ProcessQuery processQuery, PageQuery pageQuery) { Page<WfTaskVo> page = new Page<>(); HistoricTaskInstanceQuery taskInstanceQuery = historyService.createHistoricTaskInstanceQuery().includeProcessVariables().finished().orderByHistoricTaskInstanceEndTime().desc(); if (!SecurityUtils.hasRole("admin" )) { taskInstanceQuery.taskAssignee(TaskUtils.getUserId()); } // 构建搜索条件 ProcessUtils.buildProcessSearch(taskInstanceQuery, processQuery); int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<HistoricTaskInstance> historicTaskInstanceList = taskInstanceQuery.listPage(offset, pageQuery.getPageSize()); List<WfTaskVo> hisTaskList = new ArrayList<>(); for (HistoricTaskInstance histTask : historicTaskInstanceList) { WfTaskVo flowTask = new WfTaskVo(); // 当前流程信息 flowTask.setTaskId(histTask.getId()); // 审批人员信息 flowTask.setCreateTime(histTask.getCreateTime()); flowTask.setFinishTime(histTask.getEndTime()); flowTask.setDuration(DateUtil.formatBetween(histTask.getDurationInMillis(), BetweenFormatter.Level.SECOND)); flowTask.setProcDefId(histTask.getProcessDefinitionId()); flowTask.setTaskDefKey(histTask.getTaskDefinitionKey()); flowTask.setTaskName(histTask.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(histTask.getProcessDefinitionId()).singleResult(); flowTask.setDeployId(pd.getDeploymentId()); flowTask.setProcDefName(pd.getName()); flowTask.setProcDefVersion(pd.getVersion()); flowTask.setProcInsId(histTask.getProcessInstanceId()); flowTask.setHisProcInsId(histTask.getProcessInstanceId()); WfModelProcdef wfModelProcdef = wfModelProcdefService.selectWfModelProcdefByProcdefId(pd.getDeploymentId()); flowTask.setFormType(wfModelProcdef.getFormType()); flowTask.setFormViewPath(wfModelProcdef.getFormViewPath()); WfBusinessProcess wfBusinessProcess = wfBusinessProcessService.selectWfBusinessProcessByProcessId(histTask.getProcessInstanceId()); if (ObjectUtil.isNotNull(wfBusinessProcess)) { flowTask.setBusinessId(wfBusinessProcess.getBusinessId()); } HistoricVariableInstance processStatusVariable = historyService.createHistoricVariableInstanceQuery().processInstanceId(histTask.getProcessInstanceId()).variableName(ProcessConstants.PROCESS_STATUS_KEY).singleResult(); String processStatus = null; if (ObjectUtil.isNotNull(processStatusVariable)) { processStatus = Convert.toStr(processStatusVariable.getValue()); } // 兼容旧流程 if (processStatus == null) { processStatus = ObjectUtil.isNull(histTask.getEndTime()) ? ProcessStatus.RUNNING.getStatus() : ProcessStatus.COMPLETED.getStatus(); } flowTask.setProcessStatus(processStatus); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(histTask.getProcessInstanceId()).singleResult(); if (ObjectUtil.isNotNull(historicProcessInstance)) { Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); flowTask.setStartUserId(userId); flowTask.setStartUserName(nickName); // 流程变量 flowTask.setProcVars(histTask.getProcessVariables()); hisTaskList.add(flowTask); } } page.setTotal(taskInstanceQuery.count()); page.setRecords(hisTaskList); // Map<String, Object> result = new HashMap<>(); // result.put("result",page); // result.put("finished",true); return TableDataInfo.build(page); } @Override public List<WfTaskVo> selectFinishedProcessList(ProcessQuery processQuery) { HistoricTaskInstanceQuery taskInstanceQuery = historyService.createHistoricTaskInstanceQuery().includeProcessVariables().finished().taskAssignee(TaskUtils.getUserId()).orderByHistoricTaskInstanceEndTime().desc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(taskInstanceQuery, processQuery); List<HistoricTaskInstance> historicTaskInstanceList = taskInstanceQuery.list(); List<WfTaskVo> hisTaskList = new ArrayList<>(); for (HistoricTaskInstance histTask : historicTaskInstanceList) { WfTaskVo flowTask = new WfTaskVo(); // 当前流程信息 flowTask.setTaskId(histTask.getId()); // 审批人员信息 flowTask.setCreateTime(histTask.getCreateTime()); flowTask.setFinishTime(histTask.getEndTime()); flowTask.setDuration(DateUtil.formatBetween(histTask.getDurationInMillis(), BetweenFormatter.Level.SECOND)); flowTask.setProcDefId(histTask.getProcessDefinitionId()); flowTask.setTaskDefKey(histTask.getTaskDefinitionKey()); flowTask.setTaskName(histTask.getName()); // 流程定义信息 ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(histTask.getProcessDefinitionId()).singleResult(); flowTask.setDeployId(pd.getDeploymentId()); flowTask.setProcDefName(pd.getName()); flowTask.setProcDefVersion(pd.getVersion()); flowTask.setProcInsId(histTask.getProcessInstanceId()); flowTask.setHisProcInsId(histTask.getProcessInstanceId()); // 流程发起人信息 HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(histTask.getProcessInstanceId()).singleResult(); Long userId = Long.parseLong(historicProcessInstance.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); flowTask.setStartUserId(userId); flowTask.setStartUserName(nickName); // 流程变量 flowTask.setProcVars(histTask.getProcessVariables()); hisTaskList.add(flowTask); } return hisTaskList; } @Override public FormConf selectFormContent(String definitionId, String deployId, String procInsId) { BpmnModel bpmnModel = repositoryService.getBpmnModel(definitionId); if (ObjectUtil.isNull(bpmnModel)) { throw new RuntimeException("获取流程设计失败!"); } StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel); WfDeployForm deployForm = deployFormMapper.selectOne(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId).eq(WfDeployForm::getFormKey, startEvent.getFormKey()).eq(WfDeployForm::getNodeKey, startEvent.getId())); FormConf formConf = JsonUtils.parseObject(deployForm.getContent(), FormConf.class); if (ObjectUtil.isNull(formConf)) { throw new RuntimeException("获取流程表单失败!"); } if (ObjectUtil.isNotEmpty(procInsId)) { // 获取流程实例 HistoricProcessInstance historicProcIns = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).includeProcessVariables().singleResult(); // 填充表单信息 ProcessFormUtils.fillFormData(formConf, historicProcIns.getProcessVariables()); } return formConf; } /** * 根据流程定义ID启动流程实例 * * @param procDefId 流程定义Id * @param variables 流程变量 * @return */ @Override @Transactional(rollbackFor = Exception.class) public ProcessInstance startProcessByDefId(String procDefId, Map<String, Object> variables) { try { ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult(); return startProcess(processDefinition, variables); } catch (Exception e) { e.printStackTrace(); throw new ServiceException("流程启动错误" ); } } /** * 通过DefinitionKey启动流程 * * @param procDefKey 流程定义Key * @param variables 扩展参数 */ @Override @Transactional(rollbackFor = Exception.class) public void startProcessByDefKey(String procDefKey, Map<String, Object> variables) { try { ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(procDefKey).latestVersion().singleResult(); startProcess(processDefinition, variables); } catch (Exception e) { e.printStackTrace(); throw new ServiceException("流程启动错误" ); } } /** * 删除流程实例 * * @param instanceIds */ @Override @Transactional(rollbackFor = Exception.class) public void deleteProcessByIds(String[] instanceIds) { List<String> ids = Arrays.asList(instanceIds); if (!SecurityUtils.hasRole("admin" )) { // 校验流程是否结束 long activeInsCount = runtimeService.createProcessInstanceQuery().processInstanceIds(new HashSet<>(ids)).active().count(); if (activeInsCount > 0) { throw new ServiceException("不允许删除进行中的流程实例" ); } } // 删除历史流程实例 historyService.bulkDeleteHistoricProcessInstances(ids); // 删除业务流程 deleteProcessBusinessHandler.delete(ids); } /** * 读取xml文件 * * @param processDefId 流程定义ID */ @Override public String queryBpmnXmlById(String processDefId) { InputStream inputStream = repositoryService.getProcessModel(processDefId); try { return IoUtil.readUtf8(inputStream); } catch (IORuntimeException exception) { throw new RuntimeException("加载xml文件异常" ); } } /** * 流程详情信息 * * @param procInsId 流程实例ID * @param taskId 任务ID * @param formType 表单类型 * @return */ @Override public WfDetailVo queryProcessDetail(String procInsId, String taskId, String formType) { WfDetailVo detailVo = new WfDetailVo(); // 获取流程实例 HistoricProcessInstance historicProcIns = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).includeProcessVariables().singleResult(); if (StringUtils.isNotBlank(taskId)) { HistoricTaskInstance taskIns = historyService.createHistoricTaskInstanceQuery().taskId(taskId).includeIdentityLinks().includeProcessVariables().includeTaskLocalVariables().singleResult(); if (taskIns == null) { throw new ServiceException("没有可办理的任务!" ); } detailVo.setTaskFormData(currTaskFormData(historicProcIns.getDeploymentId(), taskIns)); } // 获取Bpmn模型信息 InputStream inputStream = repositoryService.getProcessModel(historicProcIns.getProcessDefinitionId()); String bpmnXmlStr = StrUtil.utf8Str(IoUtil.readBytes(inputStream, false)); BpmnModel bpmnModel = ModelUtils.getBpmnModel(bpmnXmlStr); detailVo.setBpmnXml(bpmnXmlStr); String buttonList = getButtonList(bpmnModel, procInsId); if (StringUtils.isNotEmpty(buttonList)) { detailVo.setButtonList(Arrays.asList(Objects.requireNonNull(buttonList).split("," ))); } // 历史流程节点信息 detailVo.setHistoryProcNodeList(historyProcNodeList(historicProcIns)); if (FormType.PROCESS.getType().equals(formType)) { detailVo.setProcessFormList(processFormList(bpmnModel, historicProcIns)); } else { // 设置业务流程详情 businessProcessDetailsHandler.setBusinessProcess(detailVo, historicProcIns.getProcessVariables()); // 历史流程审批节点信息 Map<String, Object> processVariables = historicProcIns.getProcessVariables(); String businessId = processVariables.get(ProcessConstants.BUSINESS_ID).toString(); WfRoamHistorical wfRoamHistorical = new WfRoamHistorical(); wfRoamHistorical.setBusinessId(businessId); detailVo.setHistoryApproveProcNodeList(wfRoamHistoricalService.selectWfRoamHistoricalList(wfRoamHistorical)); detailVo.setProcessFormList(processFormList(bpmnModel, historicProcIns)); } detailVo.setFlowViewer(getFlowViewer(bpmnModel, procInsId)); return detailVo; } /** * 根据钉钉流程json转flowable的bpmn的xml格式 * * @param ddToBpmn * @return */ @Override public R<String> dingdingToBpmn(DdToBpmn ddToBpmn) { try { String ddjson = ddToBpmn.getJson(); JSONObject object = JSON.parseObject(ddjson, JSONObject.class); //JSONObject workflow = object.getJSONObject("process"); //ddBpmnModel.addProcess(ddProcess); //ddProcess.setName (workflow.getString("name")); //ddProcess.setId(workflow.getString("processId")); ddProcess = new Process(); ddBpmnModel = new BpmnModel(); ddSequenceFlows = Lists.newArrayList(); ddBpmnModel.addProcess(ddProcess); ddProcess.setId("Process_" + UUID.randomUUID()); ddProcess.setName(ddToBpmn.getName()); JSONObject flowNode = object.getJSONObject("processData" ); StartEvent startEvent = createStartEvent(flowNode); ddProcess.addFlowElement(startEvent); String lastNode = create(startEvent.getId(), flowNode); EndEvent endEvent = createEndEvent(); ddProcess.addFlowElement(endEvent); ddProcess.addFlowElement(connect(lastNode, endEvent.getId())); new BpmnAutoLayout(ddBpmnModel).execute(); return R.ok(new String(new BpmnXMLConverter().convertToXML(ddBpmnModel))); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("创建失败: e=" + e.getMessage()); } } /** * 查询可发起列表 * * @return */ private List<WfDefinitionVo> selectWfDefinitionListByModelIdList(List<String> modelIdList) { if (modelIdList.size() == 0) { return new ArrayList<>(); } List<String> procdefIdList = wfModelProcdefService.selectWfModelProcdefListByModelIdList(modelIdList); if (procdefIdList.size() == 0) { throw new RuntimeException("没有流程部署,请先部署流程!" ); } List<Deploy> list = wfProcessMapper.selectProcessList(new ProcessQuery(), procdefIdList); List<WfDefinitionVo> definitionVoList = new ArrayList<>(); for (Deploy deploy : list) { String deploymentId = deploy.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); WfIcon wfIcon = wfIconService.selectWfIconByDeploymentId(deploymentId); WfDefinitionVo vo = new WfDefinitionVo(); vo.setDefinitionId(deploy.getId()); vo.setIcon(wfIcon.getIcon()); vo.setProcessKey(deploy.getKey()); vo.setProcessName(deploy.getName()); vo.setVersion(deploy.getVersion()); vo.setDeploymentId(deploy.getDeploymentId()); vo.setSuspended(deploy.getSuspensionState() == 1); vo.setFormType(deploy.getFormType()); vo.setFormCreatePath(deploy.getFormCreatePath()); // 流程定义时间 vo.setCategory(deployment.getCategory()); vo.setDeploymentTime(deployment.getDeploymentTime()); definitionVoList.add(vo); } return definitionVoList; } /** * 根据菜单id获取可发起列表 * * @param menuId * @return */ @Override public List<WfDefinitionVo> getStartList(String menuId) { WfFlowMenu wfFlowMenu = new WfFlowMenu(); wfFlowMenu.setMenuId(menuId); wfFlowMenuService.selectWfFlowMenuList(wfFlowMenu); if (wfFlowMenuService.selectWfFlowMenuList(wfFlowMenu).size() == 0) { throw new DataException("请先配置请假表单流程!" ); } // 校验流程模型 List<WfModelVo> wfModelVoList = wfModelService.getModelByMenuId(menuId); if (wfModelVoList.size() == 0) { throw new DataException("没有流程模型,请先配置流程模型!" ); } // 校验流程部署 List<String> modelIdList = wfModelVoList.stream().map(WfModelVo::getModelId).collect(Collectors.toList()); return selectWfDefinitionListByModelIdList(modelIdList); } /** * 重新发起流程实例 * * @param resubmitProcess 重新发起 */ @Override public void resubmitProcess(ResubmitProcess resubmitProcess) { WfBusinessProcess wfBusinessProcess = wfBusinessProcessService.selectWfBusinessProcessByProcessId(resubmitProcess.getProcInsId()); resubmitProcessHandler.resubmit(wfBusinessProcess); } /** * 查询流程是否结束 * * @param procInsId * @param */ @Override public boolean processIsCompleted(String procInsId) { // 获取流程状态 HistoricVariableInstance processStatusVariable = historyService.createHistoricVariableInstanceQuery() .processInstanceId(procInsId) .variableName(ProcessConstants.PROCESS_STATUS_KEY) .singleResult(); if (ObjectUtil.isNotNull(processStatusVariable)) { String processStatus = null; if (ObjectUtil.isNotNull(processStatusVariable)) { processStatus = Convert.toStr(processStatusVariable.getValue()); if(com.ruoyi.common.utils.StringUtils.equalsIgnoreCase(processStatus, ProcessStatus.COMPLETED.getStatus())) { return true; } } } return false; } StartEvent createStartEvent(JSONObject flowNode) { String nodeType = flowNode.getString("type" ); StartEvent startEvent = new StartEvent(); startEvent.setId(id("start" )); if (Type.INITIATOR_TASK.isEqual(nodeType)) { JSONObject properties = flowNode.getJSONObject("properties" ); if (StringUtils.isNotEmpty(properties.getString("formKey" ))) { startEvent.setFormKey(properties.getString("formKey" )); } } return startEvent; } String id(String prefix) { return prefix + "_" + UUID.randomUUID().toString().replace("-" , "" ).toLowerCase(); } enum Type { /** * 并行事件 */ CONCURRENT("concurrent" , ParallelGateway.class), /** * 排他事件 */ EXCLUSIVE("exclusive" , ExclusiveGateway.class), /** * 服务任务 */ SERVICE_TASK("serviceTask" , ServiceTask.class), /** * 发起人任务 */ INITIATOR_TASK("start" , ServiceTask.class), /** * 审批任务 */ APPROVER_TASK("approver" , ServiceTask.class), /** * 用户任务 */ USER_TASK("userTask" , UserTask.class); private String type; private Class<?> typeClass; Type(String type, Class<?> typeClass) { this.type = type; this.typeClass = typeClass; } public final static Map<String, Class<?>> TYPE_MAP = Maps.newHashMap(); static { for (Type element : Type.values()) { TYPE_MAP.put(element.type, element.typeClass); } } public boolean isEqual(String type) { return this.type.equals(type); } } String create(String fromId, JSONObject flowNode) throws InvocationTargetException, IllegalAccessException { String nodeType = flowNode.getString("type" ); if (Type.INITIATOR_TASK.isEqual(nodeType)) { flowNode.put("incoming" , Collections.singletonList(fromId)); String id = createUserTask(flowNode, nodeType); if (flowNode.containsKey("concurrentNodes" )) { //并行网关 return createConcurrentGatewayBuilder(id, flowNode); } if (flowNode.containsKey("conditionNodes" )) { //排它网关或叫条件网关 return createExclusiveGatewayBuilder(id, flowNode); } // 如果当前任务还有后续任务,则遍历创建后续任务 JSONObject nextNode = flowNode.getJSONObject("childNode" ); if (Objects.nonNull(nextNode)) { FlowElement flowElement = ddBpmnModel.getFlowElement(id); return create(id, nextNode); } else { return id; } } else if (Type.USER_TASK.isEqual(nodeType) || Type.APPROVER_TASK.isEqual(nodeType)) { flowNode.put("incoming" , Collections.singletonList(fromId)); String id = createUserTask(flowNode, nodeType); if (flowNode.containsKey("concurrentNodes" )) { //并行网关 return createConcurrentGatewayBuilder(id, flowNode); } if (flowNode.containsKey("conditionNodes" )) { //排它网关或叫条件网关 return createExclusiveGatewayBuilder(id, flowNode); } // 如果当前任务还有后续任务,则遍历创建后续任务 JSONObject nextNode = flowNode.getJSONObject("childNode" ); if (Objects.nonNull(nextNode)) { FlowElement flowElement = ddBpmnModel.getFlowElement(id); return create(id, nextNode); } else { return id; } } else if (Type.SERVICE_TASK.isEqual(nodeType)) { flowNode.put("incoming" , Collections.singletonList(fromId)); String id = createServiceTask(flowNode); if (flowNode.containsKey("concurrentNodes" )) { //并行网关 return createConcurrentGatewayBuilder(id, flowNode); } if (flowNode.containsKey("conditionNodes" )) { //排它网关或叫条件网关 return createExclusiveGatewayBuilder(id, flowNode); } // 如果当前任务还有后续任务,则遍历创建后续任务 JSONObject nextNode = flowNode.getJSONObject("childNode" ); if (Objects.nonNull(nextNode)) { FlowElement flowElement = ddBpmnModel.getFlowElement(id); return create(id, nextNode); } else { return id; } } else { throw new RuntimeException("未知节点类型: nodeType=" + nodeType); } } EndEvent createEndEvent() { EndEvent endEvent = new EndEvent(); endEvent.setId(id("end" )); return endEvent; } SequenceFlow connect(String from, String to) { SequenceFlow flow = new SequenceFlow(); flow.setId(id("sequenceFlow" )); flow.setSourceRef(from); flow.setTargetRef(to); ddSequenceFlows.add(flow); return flow; } String createUserTask(JSONObject flowNode, String nodeType) { List<String> incoming = flowNode.getJSONArray("incoming" ).toJavaList(String.class); // 自动生成id String id = id("userTask" ); if (incoming != null && !incoming.isEmpty()) { UserTask userTask = new UserTask(); JSONObject properties = flowNode.getJSONObject("properties" ); userTask.setName(properties.getString("title" )); userTask.setId(id); List<ExtensionAttribute> attributes = new ArrayList<ExtensionAttribute>(); if (Type.INITIATOR_TASK.isEqual(nodeType)) { ExtensionAttribute extAttribute = new ExtensionAttribute(); extAttribute.setNamespace(ProcessConstants.NAMASPASE); extAttribute.setName("dataType" ); extAttribute.setValue("INITIATOR" ); attributes.add(extAttribute); userTask.addAttribute(extAttribute); userTask.setAssignee("${initiator}" ); } else if (Type.USER_TASK.isEqual(nodeType) || Type.APPROVER_TASK.isEqual(nodeType)) { String assignType = properties.getString("assigneeType" ); if (StringUtils.equalsAnyIgnoreCase("user" , assignType)) { JSONArray approvers = properties.getJSONArray("approvers" ); JSONObject approver = approvers.getJSONObject(0); ExtensionAttribute extDataTypeAttribute = new ExtensionAttribute(); extDataTypeAttribute.setNamespace(ProcessConstants.NAMASPASE); extDataTypeAttribute.setName("dataType" ); extDataTypeAttribute.setValue("USERS" ); userTask.addAttribute(extDataTypeAttribute); ExtensionAttribute extTextAttribute = new ExtensionAttribute(); extTextAttribute.setNamespace(ProcessConstants.NAMASPASE); extTextAttribute.setName("text" ); extTextAttribute.setValue(approver.getString("nickName" )); userTask.addAttribute(extTextAttribute); userTask.setFormKey(properties.getString("formKey" )); userTask.setAssignee(approver.getString("userName" )); } else if (StringUtils.equalsAnyIgnoreCase("director" , assignType)) { ExtensionAttribute extDataTypeAttribute = new ExtensionAttribute(); extDataTypeAttribute.setNamespace(ProcessConstants.NAMASPASE); extDataTypeAttribute.setName("dataType" ); extDataTypeAttribute.setValue("MANAGER" ); userTask.addAttribute(extDataTypeAttribute); ExtensionAttribute extTextAttribute = new ExtensionAttribute(); extTextAttribute.setNamespace(ProcessConstants.NAMASPASE); extTextAttribute.setName("text" ); extTextAttribute.setValue("部门经理" ); userTask.addAttribute(extTextAttribute); userTask.setFormKey(properties.getString("formKey" )); userTask.setAssignee("${DepManagerHandler.getUser(execution)}" ); } else if (StringUtils.equalsAnyIgnoreCase("role" , assignType)) { JSONArray approvers = properties.getJSONArray("approvers" ); JSONObject approver = approvers.getJSONObject(0); ExtensionAttribute extDataTypeAttribute = new ExtensionAttribute(); extDataTypeAttribute.setNamespace(ProcessConstants.NAMASPASE); extDataTypeAttribute.setName("dataType" ); extDataTypeAttribute.setValue("ROLES" ); userTask.addAttribute(extDataTypeAttribute); ExtensionAttribute extTextAttribute = new ExtensionAttribute(); extTextAttribute.setNamespace(ProcessConstants.NAMASPASE); extTextAttribute.setName("text" ); extTextAttribute.setValue(approver.getString("roleName" )); userTask.addAttribute(extTextAttribute); userTask.setFormKey(properties.getString("formKey" )); List<SysRole> sysroleslist = approvers.toJavaList(SysRole.class); List<String> roleslist = sysroleslist.stream().map(e -> e.getRoleKey()).collect(Collectors.toList()); userTask.setCandidateGroups(roleslist); userTask.setAssignee("${assignee}" ); MultiInstanceLoopCharacteristics loopCharacteristics = new MultiInstanceLoopCharacteristics(); if (StringUtils.equalsAnyIgnoreCase(properties.getString("counterSign" ), "true" )) {//并行会签 loopCharacteristics.setSequential(false); loopCharacteristics.setInputDataItem("${multiInstanceHandler.getUserNames(execution)}" ); loopCharacteristics.setElementVariable("assignee" ); loopCharacteristics.setCompletionCondition("${nrOfCompletedInstances &gt;= nrOfInstances}" ); } else { loopCharacteristics.setSequential(false); loopCharacteristics.setInputDataItem("${multiInstanceHandler.getUserNames(execution)}" ); loopCharacteristics.setElementVariable("assignee" ); loopCharacteristics.setCompletionCondition("${nrOfCompletedInstances &gt; 0}" ); } userTask.setLoopCharacteristics(loopCharacteristics); } } ddProcess.addFlowElement(userTask); ddProcess.addFlowElement(connect(incoming.get(0), id)); } return id; } String createConcurrentGatewayBuilder(String fromId, JSONObject flowNode) throws InvocationTargetException, IllegalAccessException { //String name = flowNode.getString("nodeName"); //下面创建并行网关并进行连线 ParallelGateway parallelGateway = new ParallelGateway(); String parallelGatewayId = id("parallelGateway" ); parallelGateway.setId(parallelGatewayId); parallelGateway.setName("并行网关" ); ddProcess.addFlowElement(parallelGateway); ddProcess.addFlowElement(connect(fromId, parallelGatewayId)); if (Objects.isNull(flowNode.getJSONArray("concurrentNodes" )) && Objects.isNull(flowNode.getJSONObject("childNode" ))) { return parallelGatewayId; } //获取并行列表数据 List<JSONObject> flowNodes = Optional.ofNullable(flowNode.getJSONArray("concurrentNodes" )).map(e -> e.toJavaList(JSONObject.class)).orElse(Collections.emptyList()); List<String> incoming = Lists.newArrayListWithCapacity(flowNodes.size()); for (JSONObject element : flowNodes) { JSONObject childNode = element.getJSONObject("childNode" ); if (Objects.isNull(childNode)) {//没子节点,就把并行id加入入口队列 incoming.add(parallelGatewayId); continue; } String identifier = create(parallelGatewayId, childNode); if (Objects.nonNull(identifier)) {//否则加入有子节点的用户id incoming.add(identifier); } } JSONObject childNode = flowNode.getJSONObject("childNode" ); if (Objects.nonNull(childNode)) { // 普通结束网关 if (CollectionUtils.isEmpty(incoming)) { return create(parallelGatewayId, childNode); } else { // 所有 user task 连接 end parallel gateway childNode.put("incoming" , incoming); FlowElement flowElement = ddBpmnModel.getFlowElement(incoming.get(0)); // 1.0 先进行边连接, 暂存 nextNode JSONObject nextNode = childNode.getJSONObject("childNode" ); childNode.put("childNode" , null); //不加这个,下面创建子节点会进入递归了 String identifier = create(incoming.get(0), childNode); for (int i = 1; i < incoming.size(); i++) {//其中0之前创建的时候已经连接过了,所以从1开始补另外一条 FlowElement flowElementIncoming = ddBpmnModel.getFlowElement(incoming.get(i)); ddProcess.addFlowElement(connect(flowElementIncoming.getId(), identifier)); } // 1.1 边连接完成后,在进行 nextNode 创建 if (Objects.nonNull(nextNode)) { return create(identifier, nextNode); } else { return identifier; } } } if (incoming.size() > 0) { return incoming.get(1); } else { return parallelGatewayId; } } String createExclusiveGatewayBuilder(String formId, JSONObject flowNode) throws InvocationTargetException, IllegalAccessException { //String name = flowNode.getString("nodeName"); String exclusiveGatewayId = id("exclusiveGateway" ); ExclusiveGateway exclusiveGateway = new ExclusiveGateway(); exclusiveGateway.setId(exclusiveGatewayId); exclusiveGateway.setName("排它条件网关" ); ddProcess.addFlowElement(exclusiveGateway); ddProcess.addFlowElement(connect(formId, exclusiveGatewayId)); if (Objects.isNull(flowNode.getJSONArray("conditionNodes" )) && Objects.isNull(flowNode.getJSONObject("childNode" ))) { return exclusiveGatewayId; } List<JSONObject> flowNodes = Optional.ofNullable(flowNode.getJSONArray("conditionNodes" )).map(e -> e.toJavaList(JSONObject.class)).orElse(Collections.emptyList()); List<String> incoming = Lists.newArrayListWithCapacity(flowNodes.size()); List<JSONObject> conditions = Lists.newCopyOnWriteArrayList(); for (JSONObject element : flowNodes) { JSONObject childNode = element.getJSONObject("childNode" ); JSONObject properties = element.getJSONObject("properties" ); String nodeName = properties.getString("title" ); String expression = properties.getString("conditions" ); if (Objects.isNull(childNode)) { incoming.add(exclusiveGatewayId); JSONObject condition = new JSONObject(); condition.fluentPut("nodeName" , nodeName).fluentPut("expression" , expression); conditions.add(condition); continue; } // 只生成一个任务,同时设置当前任务的条件 childNode.put("incoming" , Collections.singletonList(exclusiveGatewayId)); String identifier = create(exclusiveGatewayId, childNode); List<SequenceFlow> flows = ddSequenceFlows.stream().filter(flow -> StringUtils.equals(exclusiveGatewayId, flow.getSourceRef())).collect(Collectors.toList()); flows.stream().forEach(e -> { if (StringUtils.isBlank(e.getName()) && StringUtils.isNotBlank(nodeName)) { e.setName(nodeName); } // 设置条件表达式 if (Objects.isNull(e.getConditionExpression()) && StringUtils.isNotBlank(expression)) { e.setConditionExpression(expression); } }); if (Objects.nonNull(identifier)) { incoming.add(identifier); } } JSONObject childNode = flowNode.getJSONObject("childNode" ); if (Objects.nonNull(childNode)) { if (incoming == null || incoming.isEmpty()) { return create(exclusiveGatewayId, childNode); } else { // 所有 service task 连接 end exclusive gateway childNode.put("incoming" , incoming); FlowElement flowElement = ddBpmnModel.getFlowElement(incoming.get(0)); // 1.0 先进行边连接, 暂存 nextNode JSONObject nextNode = childNode.getJSONObject("childNode" ); childNode.put("childNode" , null); String identifier = create(flowElement.getId(), childNode); for (int i = 1; i < incoming.size(); i++) { ddProcess.addFlowElement(connect(incoming.get(i), identifier)); } // 针对 gateway 空任务分支 添加条件表达式 if (!conditions.isEmpty()) { FlowElement flowElement1 = ddBpmnModel.getFlowElement(identifier); // 获取从 gateway 到目标节点 未设置条件表达式的节点 List<SequenceFlow> flows = ddSequenceFlows.stream().filter(flow -> StringUtils.equals(flowElement1.getId(), flow.getTargetRef())).filter(flow -> StringUtils.equals(flow.getSourceRef(), exclusiveGatewayId)).collect(Collectors.toList()); flows.stream().forEach(sequenceFlow -> { if (!conditions.isEmpty()) { JSONObject condition = conditions.get(0); String nodeName = condition.getString("content" ); String expression = condition.getString("expression" ); if (StringUtils.isBlank(sequenceFlow.getName()) && StringUtils.isNotBlank(nodeName)) { sequenceFlow.setName(nodeName); } // 设置条件表达式 if (Objects.isNull(sequenceFlow.getConditionExpression()) && StringUtils.isNotBlank(expression)) { sequenceFlow.setConditionExpression(expression); } conditions.remove(0); } }); } // 1.1 边连接完成后,在进行 nextNode 创建 if (Objects.nonNull(nextNode)) { return create(identifier, nextNode); } else { return identifier; } } } return exclusiveGatewayId; } String createServiceTask(JSONObject flowNode) { List<String> incoming = flowNode.getJSONArray("incoming" ).toJavaList(String.class); // 自动生成id String id = id("serviceTask" ); if (incoming != null && !incoming.isEmpty()) { ServiceTask serviceTask = new ServiceTask(); serviceTask.setName(flowNode.getString("nodeName" )); serviceTask.setId(id); ddProcess.addFlowElement(serviceTask); ddProcess.addFlowElement(connect(incoming.get(0), id)); } return id; } /** * 获取节点显示的按钮 * * @param bpmnModel * @param procInsId */ private String getButtonList(BpmnModel bpmnModel, String procInsId) { ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult(); if (ObjectUtil.isNotNull(processInstance)) { String currentActivityId = runtimeService.getActiveActivityIds(processInstance.getId()).get(0); if (ObjectUtil.isNotNull(bpmnModel) && CollectionUtil.isNotEmpty(bpmnModel.getProcesses())) { Process process = bpmnModel.getProcesses().get(0); Collection<FlowElement> flowElements = process.getFlowElements(); for (FlowElement flowElement : flowElements) { if (flowElement instanceof UserTask) { UserTask userTask = (UserTask) flowElement; if (currentActivityId.equals(userTask.getId())) { List<ExtensionAttribute> extensionAttributes = userTask.getAttributes().get(ProcessConstants.BUTTON_LIST); if (ObjectUtil.isNotNull(extensionAttributes)) { ExtensionAttribute extensionAttribute = extensionAttributes.get(0); return extensionAttribute.getValue(); } } } } } } return null; } /** * 启动流程实例 */ private ProcessInstance startProcess(ProcessDefinition procDef, Map<String, Object> variables) { if (ObjectUtil.isNotNull(procDef) && procDef.isSuspended()) { throw new ServiceException("流程已被挂起,请先激活流程" ); } // 设置流程发起人Id到流程中 String userIdStr = TaskUtils.getUserId(); //设置已认证的用户ID identityService.setAuthenticatedUserId(userIdStr); variables.put(BpmnXMLConstants.ATTRIBUTE_EVENT_START_INITIATOR, userIdStr); // 设置流程状态为进行中 variables.put(ProcessConstants.PROCESS_STATUS_KEY, ProcessStatus.RUNNING.getStatus()); // 发起流程实例 ProcessInstance processInstance = runtimeService.startProcessInstanceById(procDef.getId(), variables); // 第一个用户任务为发起人,则自动完成任务 wfTaskService.startFirstTask(processInstance, variables); return processInstance; } /** * 获取流程变量 * * @param taskId 任务ID * @return 流程变量 */ private Map<String, Object> getProcessVariables(String taskId) { HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().includeProcessVariables().finished().taskId(taskId).singleResult(); if (Objects.nonNull(historicTaskInstance)) { return historicTaskInstance.getProcessVariables(); } return taskService.getVariables(taskId); } /** * 获取当前任务流程表单信息 */ private FormConf currTaskFormData(String deployId, HistoricTaskInstance taskIns) { WfDeployFormVo deployFormVo = deployFormMapper.selectVoOne(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId).eq(WfDeployForm::getFormKey, taskIns.getFormKey()).eq(WfDeployForm::getNodeKey, taskIns.getTaskDefinitionKey())); if (ObjectUtil.isNotEmpty(deployFormVo)) { FormConf currTaskFormData = JsonUtils.parseObject(deployFormVo.getContent(), FormConf.class); if (null != currTaskFormData) { currTaskFormData.setFormBtns(false); ProcessFormUtils.fillFormData(currTaskFormData, taskIns.getTaskLocalVariables()); return currTaskFormData; } } return null; } /** * 获取历史流程表单信息 */ private List<FormConf> processFormList(BpmnModel bpmnModel, HistoricProcessInstance historicProcIns) { List<FormConf> procFormList = new ArrayList<>(); List<HistoricActivityInstance> activityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(historicProcIns.getId()).finished().activityTypes(CollUtil.newHashSet(BpmnXMLConstants.ELEMENT_EVENT_START, BpmnXMLConstants.ELEMENT_TASK_USER)).orderByHistoricActivityInstanceStartTime().asc().list(); List<String> processFormKeys = new ArrayList<>(); for (HistoricActivityInstance activityInstance : activityInstanceList) { // 获取当前节点流程元素信息 FlowElement flowElement = ModelUtils.getFlowElementById(bpmnModel, activityInstance.getActivityId()); // 获取当前节点表单Key String formKey = ModelUtils.getFormKey(flowElement); if (formKey == null) { continue; } boolean localScope = Convert.toBool(ModelUtils.getElementAttributeValue(flowElement, ProcessConstants.PROCESS_FORM_LOCAL_SCOPE), false); Map<String, Object> variables; if (localScope) { // 查询任务节点参数,并转换成Map variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcIns.getId()).taskId(activityInstance.getTaskId()).list().stream().collect(Collectors.toMap(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue)); } else { if (processFormKeys.contains(formKey)) { continue; } variables = historicProcIns.getProcessVariables(); processFormKeys.add(formKey); } // 非节点表单此处查询结果可能有多条,只获取第一条信息 List<WfDeployFormVo> formInfoList = deployFormMapper.selectVoList(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, historicProcIns.getDeploymentId()).eq(WfDeployForm::getFormKey, formKey).eq(localScope, WfDeployForm::getNodeKey, flowElement.getId())); //@update by Brath:避免空集合导致的NULL空指针 WfDeployFormVo formInfo = formInfoList.stream().findFirst().orElse(null); if (ObjectUtil.isNotNull(formInfo)) { // 旧数据 formInfo.getFormName() 为 null String formName = Optional.ofNullable(formInfo.getFormName()).orElse(StringUtils.EMPTY); String title = localScope ? formName.concat("(" + flowElement.getName() + ")" ) : formName; FormConf formConf = JsonUtils.parseObject(formInfo.getContent(), FormConf.class); if (null != formConf) { formConf.setTitle(title); formConf.setDisabled(true); formConf.setFormBtns(false); ProcessFormUtils.fillFormData(formConf, variables); procFormList.add(formConf); } } } return procFormList; } @Deprecated private void buildStartFormData(HistoricProcessInstance historicProcIns, Process process, String deployId, List<FormConf> procFormList) { procFormList = procFormList == null ? new ArrayList<>() : procFormList; HistoricActivityInstance startInstance = historyService.createHistoricActivityInstanceQuery().processInstanceId(historicProcIns.getId()).activityId(historicProcIns.getStartActivityId()).singleResult(); StartEvent startEvent = (StartEvent) process.getFlowElement(startInstance.getActivityId()); WfDeployFormVo startFormInfo = deployFormMapper.selectVoOne(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId).eq(WfDeployForm::getFormKey, startEvent.getFormKey()).eq(WfDeployForm::getNodeKey, startEvent.getId())); if (ObjectUtil.isNotNull(startFormInfo)) { FormConf formConf = JsonUtils.parseObject(startFormInfo.getContent(), FormConf.class); if (null != formConf) { formConf.setTitle(startEvent.getName()); formConf.setDisabled(true); formConf.setFormBtns(false); ProcessFormUtils.fillFormData(formConf, historicProcIns.getProcessVariables()); procFormList.add(formConf); } } } @Deprecated private void buildUserTaskFormData(String procInsId, String deployId, Process process, List<FormConf> procFormList) { procFormList = procFormList == null ? new ArrayList<>() : procFormList; List<HistoricActivityInstance> activityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId).finished().activityType(BpmnXMLConstants.ELEMENT_TASK_USER).orderByHistoricActivityInstanceStartTime().asc().list(); for (HistoricActivityInstance instanceItem : activityInstanceList) { UserTask userTask = (UserTask) process.getFlowElement(instanceItem.getActivityId(), true); String formKey = userTask.getFormKey(); if (formKey == null) { continue; } // 查询任务节点参数,并转换成Map Map<String, Object> variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(procInsId).taskId(instanceItem.getTaskId()).list().stream().collect(Collectors.toMap(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue)); WfDeployFormVo deployFormVo = deployFormMapper.selectVoOne(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId).eq(WfDeployForm::getFormKey, formKey).eq(WfDeployForm::getNodeKey, userTask.getId())); if (ObjectUtil.isNotNull(deployFormVo)) { FormConf formConf = JsonUtils.parseObject(deployFormVo.getContent(), FormConf.class); if (null != formConf) { formConf.setTitle(userTask.getName()); formConf.setDisabled(true); formConf.setFormBtns(false); ProcessFormUtils.fillFormData(formConf, variables); procFormList.add(formConf); } } } } /** * 获取历史任务信息列表 */ private List<WfProcNodeVo> historyProcNodeList(HistoricProcessInstance historicProcIns) { String procInsId = historicProcIns.getId(); List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId).activityTypes(CollUtil.newHashSet(BpmnXMLConstants.ELEMENT_EVENT_START, BpmnXMLConstants.ELEMENT_EVENT_END, BpmnXMLConstants.ELEMENT_TASK_USER)).orderByHistoricActivityInstanceStartTime().desc().orderByHistoricActivityInstanceEndTime().desc().list(); List<Comment> commentList = taskService.getProcessInstanceComments(procInsId); List<WfProcNodeVo> elementVoList = new ArrayList<>(); // 用一个标志来记录是否已经添加过 `endEvent` boolean foundEndEvent = false; for (HistoricActivityInstance activityInstance : historicActivityInstanceList) { WfProcNodeVo elementVo = new WfProcNodeVo(); elementVo.setProcDefId(activityInstance.getProcessDefinitionId()); elementVo.setActivityId(activityInstance.getActivityId()); elementVo.setActivityName(activityInstance.getActivityName()); // 判断是否是 `endEvent` if ("endEvent".equals(activityInstance.getActivityType())) { if (foundEndEvent) { continue; } // 如果还没有添加过,标记已添加 `endEvent` foundEndEvent = true; } elementVo.setActivityType(activityInstance.getActivityType()); elementVo.setCreateTime(activityInstance.getStartTime()); elementVo.setEndTime(activityInstance.getEndTime()); if (ObjectUtil.isNotNull(activityInstance.getDurationInMillis())) { elementVo.setDuration(DateUtil.formatBetween(activityInstance.getDurationInMillis(), BetweenFormatter.Level.SECOND)); } if (BpmnXMLConstants.ELEMENT_EVENT_START.equals(activityInstance.getActivityType())) { if (ObjectUtil.isNotNull(historicProcIns)) { Long userId = Long.parseLong(historicProcIns.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); if (nickName != null) { elementVo.setAssigneeId(userId); elementVo.setAssigneeName(nickName); } } } else if (BpmnXMLConstants.ELEMENT_TASK_USER.equals(activityInstance.getActivityType())) { if (StringUtils.isNotBlank(activityInstance.getAssignee())) { Long userId = Long.parseLong(activityInstance.getAssignee()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); elementVo.setAssigneeId(userId); elementVo.setAssigneeName(nickName); } // 展示审批人员 List<HistoricIdentityLink> linksForTask = historyService.getHistoricIdentityLinksForTask(activityInstance.getTaskId()); StringBuilder stringBuilder = new StringBuilder(); for (HistoricIdentityLink identityLink : linksForTask) { if ("candidate".equals(identityLink.getType())) { if (StringUtils.isNotBlank(identityLink.getUserId())) { Long userId = Long.parseLong(identityLink.getUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); stringBuilder.append(nickName).append("," ); } if (StringUtils.isNotBlank(identityLink.getGroupId())) { if (identityLink.getGroupId().startsWith(TaskConstants.ROLE_GROUP_PREFIX)) { Long roleId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.ROLE_GROUP_PREFIX)); SysRole role = roleServiceApi.selectRoleById(roleId); stringBuilder.append(role.getRoleName()).append("," ); } else if (identityLink.getGroupId().startsWith(TaskConstants.DEPT_GROUP_PREFIX)) { Long deptId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.DEPT_GROUP_PREFIX)); SysDept dept = deptServiceApi.selectDeptById(deptId); stringBuilder.append(dept.getDeptName()).append("," ); } } } } if (StringUtils.isNotBlank(stringBuilder)) { elementVo.setCandidate(stringBuilder.substring(0, stringBuilder.length() - 1)); } // 获取意见评论内容 if (CollUtil.isNotEmpty(commentList)) { List<Comment> comments = new ArrayList<>(); for (Comment comment : commentList) { if (comment.getTaskId().equals(activityInstance.getTaskId())) { comments.add(comment); } } elementVo.setCommentList(comments); } } elementVoList.add(elementVo); } return elementVoList; } /** * 获取流程执行过程 * * @param procInsId * @return */ private WfViewerVo getFlowViewer(BpmnModel bpmnModel, String procInsId) { // 构建查询条件 HistoricActivityInstanceQuery query = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId); List<HistoricActivityInstance> allActivityInstanceList = query.list(); if (CollUtil.isEmpty(allActivityInstanceList)) { return new WfViewerVo(); } // 查询所有已完成的元素 List<HistoricActivityInstance> finishedElementList = allActivityInstanceList.stream().filter(item -> ObjectUtil.isNotNull(item.getEndTime())).collect(Collectors.toList()); // 所有已完成的连线 Set<String> finishedSequenceFlowSet = new HashSet<>(); // 所有已完成的任务节点 Set<String> finishedTaskSet = new HashSet<>(); finishedElementList.forEach(item -> { if (BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW.equals(item.getActivityType())) { finishedSequenceFlowSet.add(item.getActivityId()); } else { finishedTaskSet.add(item.getActivityId()); } }); // 查询所有未结束的节点 Set<String> unfinishedTaskSet = allActivityInstanceList.stream().filter(item -> ObjectUtil.isNull(item.getEndTime())).map(HistoricActivityInstance::getActivityId).collect(Collectors.toSet()); // DFS 查询未通过的元素集合 Set<String> rejectedSet = FlowableUtils.dfsFindRejects(bpmnModel, unfinishedTaskSet, finishedSequenceFlowSet, finishedTaskSet); return new WfViewerVo(finishedTaskSet, finishedSequenceFlowSet, unfinishedTaskSet, rejectedSet); } }
2929004360/ruoyi-sign
2,383
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfRoamHistoricalServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.flowable.domain.WfRoamHistorical; import com.ruoyi.flowable.mapper.WfRoamHistoricalMapper; import com.ruoyi.flowable.service.IWfRoamHistoricalService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 历史流转记录Service业务层处理 * * @author fengcheng * @date 2024-08-16 */ @Service public class WfRoamHistoricalServiceImpl implements IWfRoamHistoricalService { @Autowired private WfRoamHistoricalMapper wfRoamHistoricalMapper; /** * 查询历史流转记录 * * @param roamHistoricalId 历史流转记录主键 * @return 历史流转记录 */ @Override public WfRoamHistorical selectWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId) { return wfRoamHistoricalMapper.selectWfRoamHistoricalByRoamHistoricalId(roamHistoricalId); } /** * 查询历史流转记录列表 * * @param wfRoamHistorical 历史流转记录 * @return 历史流转记录 */ @Override public List<WfRoamHistorical> selectWfRoamHistoricalList(WfRoamHistorical wfRoamHistorical) { return wfRoamHistoricalMapper.selectWfRoamHistoricalList(wfRoamHistorical); } /** * 新增历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ @Override public int insertWfRoamHistorical(WfRoamHistorical wfRoamHistorical) { return wfRoamHistoricalMapper.insertWfRoamHistorical(wfRoamHistorical); } /** * 修改历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ @Override public int updateWfRoamHistorical(WfRoamHistorical wfRoamHistorical) { return wfRoamHistoricalMapper.updateWfRoamHistorical(wfRoamHistorical); } /** * 批量删除历史流转记录 * * @param roamHistoricalIds 需要删除的历史流转记录主键 * @return 结果 */ @Override public int deleteWfRoamHistoricalByRoamHistoricalIds(String[] roamHistoricalIds) { return wfRoamHistoricalMapper.deleteWfRoamHistoricalByRoamHistoricalIds(roamHistoricalIds); } /** * 删除历史流转记录信息 * * @param roamHistoricalId 历史流转记录主键 * @return 结果 */ @Override public int deleteWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId) { return wfRoamHistoricalMapper.deleteWfRoamHistoricalByRoamHistoricalId(roamHistoricalId); } }
2929004360/ruoyi-sign
6,155
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfCopyServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.domain.WfCopy; import com.ruoyi.flowable.domain.WfModelProcdef; import com.ruoyi.flowable.domain.bo.WfCopyBo; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import com.ruoyi.flowable.domain.vo.WfCopyVo; import com.ruoyi.flowable.mapper.WfCopyMapper; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import com.ruoyi.flowable.service.IWfBusinessProcessService; import com.ruoyi.flowable.service.IWfCopyService; import com.ruoyi.flowable.service.IWfModelProcdefService; import com.ruoyi.flowable.utils.StringUtils; import lombok.RequiredArgsConstructor; import org.flowable.engine.HistoryService; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.variable.api.history.HistoricVariableInstance; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * 流程抄送Service业务层处理 * * @author fengcheng * @date 2022-05-19 */ @RequiredArgsConstructor @Service public class WfCopyServiceImpl implements IWfCopyService { private final WfCopyMapper baseMapper; private final HistoryService historyService; @Lazy private final IWfModelProcdefService wfModelProcdefService; @Lazy private final IWfBusinessProcessService wfBusinessProcessService; /** * 查询流程抄送 * * @param copyId 流程抄送主键 * @return 流程抄送 */ @Override public WfCopyVo queryById(Long copyId) { return baseMapper.selectVoById(copyId); } /** * 查询流程抄送列表 * * @param bo 流程抄送 * @return 流程抄送 */ @Override public TableDataInfo<WfCopyVo> selectPageList(WfCopyBo bo, PageQuery pageQuery) { LambdaQueryWrapper<WfCopy> lqw = buildQueryWrapper(bo); lqw.orderByDesc(WfCopy::getCreateTime); Page<WfCopyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw); List<WfCopyVo> records = result.getRecords(); for (WfCopyVo record : records) { WfModelProcdef wfModelProcdef = wfModelProcdefService.selectWfModelProcdefByProcdefId(record.getDeploymentId()); record.setFormType(wfModelProcdef.getFormType()); record.setFormViewPath(wfModelProcdef.getFormViewPath()); WfBusinessProcess wfBusinessProcess = wfBusinessProcessService.selectWfBusinessProcessByProcessId(record.getInstanceId()); if (ObjectUtil.isNotNull(wfBusinessProcess)) { record.setBusinessId(wfBusinessProcess.getBusinessId()); } HistoricVariableInstance processStatusVariable = historyService.createHistoricVariableInstanceQuery().processInstanceId(record.getInstanceId()).variableName(ProcessConstants.PROCESS_STATUS_KEY).singleResult(); String processStatus = null; if (ObjectUtil.isNotNull(processStatusVariable)) { processStatus = Convert.toStr(processStatusVariable.getValue()); } record.setProcessStatus(processStatus); } return TableDataInfo.build(result); } /** * 查询流程抄送列表 * * @param bo 流程抄送 * @return 流程抄送 */ @Override public List<WfCopyVo> selectList(WfCopyBo bo) { LambdaQueryWrapper<WfCopy> lqw = buildQueryWrapper(bo); return baseMapper.selectVoList(lqw); } private LambdaQueryWrapper<WfCopy> buildQueryWrapper(WfCopyBo bo) { Map<String, Object> params = bo.getParams(); LambdaQueryWrapper<WfCopy> lqw = Wrappers.lambdaQuery(); lqw.eq(bo.getUserId() != null, WfCopy::getUserId, bo.getUserId()); lqw.like(StringUtils.isNotBlank(bo.getProcessName()), WfCopy::getProcessName, bo.getProcessName()); lqw.like(StringUtils.isNotBlank(bo.getOriginatorName()), WfCopy::getOriginatorName, bo.getOriginatorName()); return lqw; } @Override public Boolean makeCopy(WfTaskBo taskBo) { if (StringUtils.isBlank(taskBo.getCopyUserIds())) { // 若抄送用户为空,则不需要处理,返回成功 return true; } HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(taskBo.getProcInsId()).singleResult(); String[] ids = taskBo.getCopyUserIds().split("," ); List<WfCopy> copyList = new ArrayList<>(ids.length); Long originatorId = SecurityUtils.getUserId(); String originatorName = SecurityUtils.getLoginUser().getUser().getNickName(); String title = historicProcessInstance.getProcessDefinitionName() + "-" + taskBo.getTaskName(); for (String id : ids) { Long userId = Long.valueOf(id); WfCopy copy = new WfCopy(); copy.setTitle(title); copy.setProcessId(historicProcessInstance.getProcessDefinitionId()); copy.setProcessName(historicProcessInstance.getProcessDefinitionName()); copy.setDeploymentId(historicProcessInstance.getDeploymentId()); copy.setInstanceId(taskBo.getProcInsId()); copy.setTaskId(taskBo.getTaskId()); copy.setUserId(userId); copy.setOriginatorId(originatorId); copy.setOriginatorName(originatorName); copy.setCreateTime(DateUtils.getNowDate()); copyList.add(copy); } return baseMapper.insertBatch(copyList); } /** * 删除抄送列表 * * @param copyIds 抄送id * @return */ @Override public void deleteCopy(String[] copyIds) { baseMapper.deleteBatchIds(Arrays.asList(copyIds)); } }
2929004360/ruoyi-sign
4,536
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfFormServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.domain.WfForm; import com.ruoyi.flowable.domain.bo.WfFormBo; import com.ruoyi.flowable.domain.vo.WfFormVo; import com.ruoyi.flowable.mapper.WfFormMapper; import com.ruoyi.flowable.service.IWfFormService; import com.ruoyi.flowable.utils.StringUtils; import com.ruoyi.system.api.service.ISysDeptServiceApi; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.List; /** * 流程表单Service业务层处理 * * @author fengcheng * @createTime 2022/3/7 22:07 */ @RequiredArgsConstructor @Service public class WfFormServiceImpl implements IWfFormService { private final WfFormMapper baseMapper; private final ISysDeptServiceApi deptServiceApi; /** * 查询流程表单 * * @param formId 流程表单ID * @return 流程表单 */ @Override public WfFormVo queryById(String formId) { return baseMapper.selectVoById(formId); } /** * 查询流程表单列表 * * @param bo 流程表单 * @return 流程表单 */ @Override public List<WfFormVo> queryPageList(WfFormBo bo) { if (SecurityUtils.hasRole("admin")) { return baseMapper.selectVoList(buildQueryWrapper(bo)); } Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId(); List<Long> deptIdList = deptServiceApi.selectBranchDeptId(deptId); deptIdList.add(deptId); bo.setDeptId(deptId); SysDept sysDept = deptServiceApi.selectDeptById(deptId); String[] ancestorsArr = sysDept.getAncestors().split(","); List<Long> ancestorsList = Convert.toList(Long.class, ancestorsArr); return baseMapper.selectWfFormList(bo, deptIdList, ancestorsList); } /** * 查询流程表单列表 * * @param bo 流程表单 * @return 流程表单 */ @Override public List<WfFormVo> queryList(WfFormBo bo) { LambdaQueryWrapper<WfForm> lqw = buildQueryWrapper(bo); return baseMapper.selectVoList(lqw); } /** * 新增流程表单 * * @param bo 流程表单 * @return 结果 */ @Override public int insertForm(WfFormBo bo) { WfForm wfForm = new WfForm(); wfForm.setFormName(bo.getFormName()); wfForm.setContent(bo.getContent()); wfForm.setRemark(bo.getRemark()); wfForm.setCreateTime(DateUtils.getNowDate()); wfForm.setCreateBy(String.valueOf(SecurityUtils.getUserId())); wfForm.setUserName(SecurityUtils.getLoginUser().getUser().getNickName()); wfForm.setUserId(SecurityUtils.getUserId()); wfForm.setDeptId(bo.getDeptId()); wfForm.setDeptName(bo.getDeptName()); wfForm.setType(bo.getType()); return baseMapper.insert(wfForm); } /** * 修改流程表单 * * @param bo 流程表单 * @return 结果 */ @Override public int updateForm(WfFormBo bo) { return baseMapper.update(new WfForm(), new LambdaUpdateWrapper<WfForm>().set(ObjectUtil.isNotEmpty(bo.getDeptId()), WfForm::getDeptId, bo.getDeptId()).set(StrUtil.isNotBlank(bo.getDeptName()), WfForm::getDeptName, bo.getDeptName()).set(StrUtil.isNotBlank(bo.getFormName()), WfForm::getFormName, bo.getFormName()).set(StrUtil.isNotBlank(bo.getType()), WfForm::getType, bo.getType()).set(StrUtil.isNotBlank(bo.getContent()), WfForm::getContent, bo.getContent()).set(StrUtil.isNotBlank(bo.getRemark()), WfForm::getRemark, bo.getRemark()).set(WfForm::getUpdateTime, DateUtils.getNowDate()).set(WfForm::getUpdateBy, SecurityUtils.getUserId()).eq(WfForm::getFormId, bo.getFormId())); } /** * 批量删除流程表单 * * @param ids 需要删除的流程表单ID * @return 结果 */ @Override public Boolean deleteWithValidByIds(Collection<String> ids) { return baseMapper.deleteBatchIds(ids) > 0; } private LambdaQueryWrapper<WfForm> buildQueryWrapper(WfFormBo bo) { LambdaQueryWrapper<WfForm> lqw = Wrappers.lambdaQuery(); lqw.like(StringUtils.isNotBlank(bo.getFormName()), WfForm::getFormName, bo.getFormName()); return lqw; } }
2929004360/ruoyi-sign
2,644
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfFlowMenuServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.flowable.domain.WfFlowMenu; import com.ruoyi.flowable.mapper.WfFlowMenuMapper; import com.ruoyi.flowable.service.IWfFlowMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 流程菜单Service业务层处理 * * @author fengcheng * @date 2024-07-12 */ @Service public class WfFlowMenuServiceImpl implements IWfFlowMenuService { @Autowired private WfFlowMenuMapper wfFlowMenuMapper; /** * 查询流程菜单 * * @param flowMenuId 流程菜单主键 * @return 流程菜单 */ @Override public WfFlowMenu selectWfFlowMenuByFlowMenuId(String flowMenuId) { return wfFlowMenuMapper.selectWfFlowMenuByFlowMenuId(flowMenuId); } /** * 查询流程菜单列表 * * @param wfFlowMenu 流程菜单 * @return 流程菜单 */ @Override public List<WfFlowMenu> selectWfFlowMenuList(WfFlowMenu wfFlowMenu) { return wfFlowMenuMapper.selectWfFlowMenuList(wfFlowMenu); } /** * 新增流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ @Override public int insertWfFlowMenu(WfFlowMenu wfFlowMenu) { WfFlowMenu menu = new WfFlowMenu(); menu.setMenuId(wfFlowMenu.getMenuId()); List<WfFlowMenu> wfFlowMenus = wfFlowMenuMapper.selectWfFlowMenuList(menu); if (wfFlowMenus.size() > 0) { throw new RuntimeException("菜单已存在" ); } wfFlowMenu.setCreateTime(DateUtils.getNowDate()); return wfFlowMenuMapper.insertWfFlowMenu(wfFlowMenu); } /** * 修改流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ @Override public int updateWfFlowMenu(WfFlowMenu wfFlowMenu) { wfFlowMenu.setUpdateTime(DateUtils.getNowDate()); return wfFlowMenuMapper.updateWfFlowMenu(wfFlowMenu); } /** * 批量删除流程菜单 * * @param flowMenuIds 需要删除的流程菜单主键 * @return 结果 */ @Override public int deleteWfFlowMenuByFlowMenuIds(Long[] flowMenuIds) { return wfFlowMenuMapper.deleteWfFlowMenuByFlowMenuIds(flowMenuIds); } /** * 删除流程菜单信息 * * @param flowMenuId 流程菜单主键 * @return 结果 */ @Override public int deleteWfFlowMenuByFlowMenuId(Long flowMenuId) { return wfFlowMenuMapper.deleteWfFlowMenuByFlowMenuId(flowMenuId); } /** * 获取流程菜单信息 * * @param menuId * @return */ @Override public WfFlowMenu getWfFlowMenuInfo(String menuId) { return wfFlowMenuMapper.getWfFlowMenuInfo(menuId); } }
2929004360/ruoyi-sign
10,367
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfDeployServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.core.domain.ProcessQuery; import com.ruoyi.flowable.domain.Deploy; import com.ruoyi.flowable.domain.WfCopy; import com.ruoyi.flowable.domain.WfDeployForm; import com.ruoyi.flowable.domain.WfIcon; import com.ruoyi.flowable.domain.vo.WfDeployVo; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.flowable.mapper.WfCopyMapper; import com.ruoyi.flowable.mapper.WfDeployFormMapper; import com.ruoyi.flowable.mapper.WfDeployMapper; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import com.ruoyi.flowable.service.*; import com.ruoyi.flowable.utils.ProcessUtils; import lombok.RequiredArgsConstructor; import org.flowable.common.engine.impl.db.SuspensionState; import org.flowable.engine.HistoryService; import org.flowable.engine.RepositoryService; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.repository.ProcessDefinitionQuery; import org.flowable.variable.api.history.HistoricVariableInstance; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author fengcheng * @createTime 2022/6/30 9:04 */ @RequiredArgsConstructor @Service public class WfDeployServiceImpl implements IWfDeployService { private final RepositoryService repositoryService; private final WfDeployFormMapper deployFormMapper; private final WfCopyMapper wfCopyMapper; private final IWfIconService wfIconService; private final IWfModelService wfModelService; private final WfDeployMapper wfDeployMapper; private final IWfModelProcdefService wfModelProcdefService; private final IWfFlowMenuService wfFlowMenuService; protected final HistoryService historyService; @Override public TableDataInfo<WfDeployVo> queryPageList(ProcessQuery processQuery, PageQuery pageQuery) { // 流程定义列表数据查询 ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery() .latestVersion() .orderByProcessDefinitionKey() .asc(); // 构建搜索条件 ProcessUtils.buildProcessSearch(processDefinitionQuery, processQuery); long pageTotal = processDefinitionQuery.count(); if (pageTotal <= 0) { return TableDataInfo.build(); } int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<ProcessDefinition> definitionList = processDefinitionQuery.listPage(offset, pageQuery.getPageSize()); List<WfDeployVo> deployVoList = new ArrayList<>(definitionList.size()); for (ProcessDefinition processDefinition : definitionList) { String deploymentId = processDefinition.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); WfIcon wfIcon = wfIconService.selectWfIconByDeploymentId(deploymentId); WfDeployVo vo = new WfDeployVo(); vo.setDefinitionId(processDefinition.getId()); vo.setIcon(wfIcon.getIcon()); vo.setProcessKey(processDefinition.getKey()); vo.setProcessName(processDefinition.getName()); vo.setVersion(processDefinition.getVersion()); vo.setCategory(processDefinition.getCategory()); vo.setDeploymentId(processDefinition.getDeploymentId()); vo.setSuspended(processDefinition.isSuspended()); // 流程部署信息 vo.setCategory(deployment.getCategory()); vo.setDeploymentTime(deployment.getDeploymentTime()); vo.setDeploymentTime(deployment.getDeploymentTime()); deployVoList.add(vo); } Page<WfDeployVo> page = new Page<>(); page.setRecords(deployVoList); page.setTotal(pageTotal); return TableDataInfo.build(page); } @Override public TableDataInfo<WfDeployVo> queryPublishList(String processKey, PageQuery pageQuery) { // 创建查询条件 ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery() .processDefinitionKey(processKey) .orderByProcessDefinitionVersion() .desc(); long pageTotal = processDefinitionQuery.count(); if (pageTotal <= 0) { return TableDataInfo.build(); } // 根据查询条件,查询所有版本 int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<ProcessDefinition> processDefinitionList = processDefinitionQuery .listPage(offset, pageQuery.getPageSize()); List<WfDeployVo> deployVoList = processDefinitionList.stream().map(item -> { WfDeployVo vo = new WfDeployVo(); vo.setDefinitionId(item.getId()); vo.setProcessKey(item.getKey()); vo.setProcessName(item.getName()); vo.setVersion(item.getVersion()); vo.setCategory(item.getCategory()); vo.setDeploymentId(item.getDeploymentId()); vo.setSuspended(item.isSuspended()); return vo; }).collect(Collectors.toList()); Page<WfDeployVo> page = new Page<>(); page.setRecords(deployVoList); page.setTotal(pageTotal); return TableDataInfo.build(page); } /** * 激活或挂起流程 * * @param state 状态 * @param definitionId 流程定义ID */ @Override public void updateState(String definitionId, String state) { if (SuspensionState.ACTIVE.toString().equals(state)) { // 激活 repositoryService.activateProcessDefinitionById(definitionId, true, null); } else if (SuspensionState.SUSPENDED.toString().equals(state)) { // 挂起 repositoryService.suspendProcessDefinitionById(definitionId, true, null); } } @Override public String queryBpmnXmlById(String definitionId) { InputStream inputStream = repositoryService.getProcessModel(definitionId); try { return IoUtil.readUtf8(inputStream); } catch (IORuntimeException exception) { throw new RuntimeException("加载xml文件异常"); } } @Override @Transactional(rollbackFor = Exception.class) public void deleteByIds(List<String> deployIds) { for (String deployId : deployIds) { // 获取进行中的流程 HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().deploymentId(deployId).orderByProcessInstanceStartTime().desc(); List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery.list(); for (HistoricProcessInstance hisIns : historicProcessInstances) { // 获取流程状态 HistoricVariableInstance processStatusVariable = historyService.createHistoricVariableInstanceQuery().processInstanceId(hisIns.getId()).variableName(ProcessConstants.PROCESS_STATUS_KEY).singleResult(); String processStatus = null; if (ObjectUtil.isNotNull(processStatusVariable)) { processStatus = Convert.toStr(processStatusVariable.getValue()); } // 兼容旧流程 if (processStatus == null) { processStatus = ObjectUtil.isNull(hisIns.getEndTime()) ? ProcessStatus.RUNNING.getStatus() : ProcessStatus.COMPLETED.getStatus(); } // 判断流程状态等于进行中不能删除 if(ProcessStatus.RUNNING.getStatus().equals(processStatus)){ throw new RuntimeException("[["+hisIns.getProcessDefinitionName()+"]]流程正在进行中,不能删除"); } } // 删除图标 wfIconService.deleteWfIconByDeploymentId(deployId); // 删除部署 repositoryService.deleteDeployment(deployId, true); // 删除模型关联部署数据 wfModelProcdefService.deleteWfModelProcdefByProcdefId(deployId); // 删除抄送数据 deployFormMapper.delete(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId)); wfCopyMapper.delete(new LambdaQueryWrapper<WfCopy>().eq(WfCopy::getDeploymentId, deployId)); } } /** * 查询流程部署列表 * * @param processQuery * @param procdefIdList * @return */ @Override public List<WfDeployVo> selectWfDeployList(ProcessQuery processQuery, List<String> procdefIdList) { List<Deploy> list = wfDeployMapper.selectWfDeployList(processQuery, procdefIdList); List<WfDeployVo> wfDeployVoList = new ArrayList<>(); for (Deploy deploy : list) { String deploymentId = deploy.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); WfIcon wfIcon = wfIconService.selectWfIconByDeploymentId(deploymentId); WfDeployVo vo = new WfDeployVo(); vo.setDefinitionId(deploy.getId()); vo.setIcon(wfIcon.getIcon()); vo.setProcessKey(deploy.getKey()); vo.setProcessName(deploy.getName()); vo.setVersion(deploy.getVersion()); vo.setCategory(deploy.getCategory()); vo.setDeploymentId(deploy.getDeploymentId()); vo.setSuspended(deploy.getSuspensionState() == 1); // 流程部署信息 vo.setCategory(deployment.getCategory()); vo.setDeploymentTime(deployment.getDeploymentTime()); vo.setDeploymentTime(deployment.getDeploymentTime()); wfDeployVoList.add(vo); } return wfDeployVoList; } }
2929004360/ruoyi-sign
3,076
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfModelAssociationTemplateServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.flowable.domain.WfModelAssociationTemplate; import com.ruoyi.flowable.mapper.WfModelAssociationTemplateMapper; import com.ruoyi.flowable.service.IWfModelAssociationTemplateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 模型关联模板Service业务层处理 * * @author fengcheng * @date 2024-07-23 */ @Service public class WfModelAssociationTemplateServiceImpl implements IWfModelAssociationTemplateService { @Autowired private WfModelAssociationTemplateMapper wfModelAssociationTemplateMapper; /** * 查询模型关联模板 * * @param modelTemplateId 模型关联模板主键 * @return 模型关联模板 */ @Override public WfModelAssociationTemplate selectWfModelAssociationTemplateByModelTemplateId(String modelTemplateId) { return wfModelAssociationTemplateMapper.selectWfModelAssociationTemplateByModelTemplateId(modelTemplateId); } /** * 查询模型关联模板列表 * * @param wfModelAssociationTemplate 模型关联模板 * @return 模型关联模板 */ @Override public List<WfModelAssociationTemplate> selectWfModelAssociationTemplateList(WfModelAssociationTemplate wfModelAssociationTemplate) { return wfModelAssociationTemplateMapper.selectWfModelAssociationTemplateList(wfModelAssociationTemplate); } /** * 新增模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ @Override public int insertWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate) { return wfModelAssociationTemplateMapper.insertWfModelAssociationTemplate(wfModelAssociationTemplate); } /** * 修改模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ @Override public int updateWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate) { return wfModelAssociationTemplateMapper.updateWfModelAssociationTemplate(wfModelAssociationTemplate); } /** * 批量删除模型关联模板 * * @param modelTemplateIds 需要删除的模型关联模板主键 * @return 结果 */ @Override public int deleteWfModelAssociationTemplateByModelTemplateIds(String[] modelTemplateIds) { return wfModelAssociationTemplateMapper.deleteWfModelAssociationTemplateByModelTemplateIds(modelTemplateIds); } /** * 删除模型关联模板信息 * * @param modelTemplateId 模型关联模板主键 * @return 结果 */ @Override public int deleteWfModelAssociationTemplateByModelTemplateId(String modelTemplateId) { return wfModelAssociationTemplateMapper.deleteWfModelAssociationTemplateByModelTemplateId(modelTemplateId); } /** * 删除模型关联模板信息 * * @param wfModelAssociationTemplate */ @Override public int deleteWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate) { return wfModelAssociationTemplateMapper.deleteWfModelAssociationTemplate(wfModelAssociationTemplate); } }
2929004360/ruoyi-sign
7,525
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfModelTemplateServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.domain.WfModelAssociationTemplate; import com.ruoyi.flowable.domain.WfModelTemplate; import com.ruoyi.flowable.domain.vo.WfModelVo; import com.ruoyi.flowable.enums.FormType; import com.ruoyi.flowable.mapper.WfModelTemplateMapper; import com.ruoyi.flowable.service.IWfModelAssociationTemplateService; import com.ruoyi.flowable.service.IWfModelService; import com.ruoyi.flowable.service.IWfModelTemplateService; import com.ruoyi.flowable.utils.IdWorker; import com.ruoyi.flowable.utils.ModelUtils; import com.ruoyi.system.api.service.ISysDeptServiceApi; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.SequenceFlow; import org.flowable.bpmn.model.StartEvent; import org.flowable.engine.RepositoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Objects; /** * 模型模板Service业务层处理 * * @author fengcheng * @date 2024-07-17 */ @Service public class WfModelTemplateServiceImpl implements IWfModelTemplateService { @Autowired private WfModelTemplateMapper wfModelTemplateMapper; @Autowired private ISysDeptServiceApi deptServiceApi; @Autowired private IWfModelAssociationTemplateService wfModelAssociationTemplateService; @Autowired protected RepositoryService repositoryService; /** * 流程模型服务 */ @Autowired private IWfModelService modelService; @Autowired private IdWorker idWorker; /** * 查询模型模板 * * @param modelTemplateId 模型模板主键 * @return 模型模板 */ @Override public WfModelTemplate selectWfModelTemplateByModelTemplateId(String modelTemplateId) { return wfModelTemplateMapper.selectWfModelTemplateByModelTemplateId(modelTemplateId); } /** * 查询模型模板列表 * * @param wfModelTemplate 模型模板 * @return 模型模板 */ @Override public List<WfModelTemplate> selectWfModelTemplateList(WfModelTemplate wfModelTemplate) { if (SecurityUtils.hasRole("admin")) { return wfModelTemplateMapper.selectWfModelTemplateList(wfModelTemplate); } Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId(); List<Long> deptIdList = deptServiceApi.selectBranchDeptId(deptId); deptIdList.add(deptId); wfModelTemplate.setDeptId(deptId); SysDept sysDept = deptServiceApi.selectDeptById(deptId); String[] ancestorsArr = sysDept.getAncestors().split(","); List<Long> ancestorsList = Convert.toList(Long.class, ancestorsArr); return wfModelTemplateMapper.selectWfModelTemplateListVo(wfModelTemplate, deptIdList, ancestorsList); } /** * 新增模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ @Override public int insertWfModelTemplate(WfModelTemplate wfModelTemplate) { wfModelTemplate.setModelTemplateId(String.valueOf(idWorker.nextId())); wfModelTemplate.setCreateTime(DateUtils.getNowDate()); return wfModelTemplateMapper.insertWfModelTemplate(wfModelTemplate); } /** * 修改模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ @Override public int updateWfModelTemplate(WfModelTemplate wfModelTemplate) { wfModelTemplate.setUpdateTime(DateUtils.getNowDate()); return wfModelTemplateMapper.updateWfModelTemplate(wfModelTemplate); } /** * 批量删除模型模板 * * @param modelTemplateIds 需要删除的模型模板主键 * @return 结果 */ @Override public int deleteWfModelTemplateByModelTemplateIds(String[] modelTemplateIds) { for (String modelTemplateId : modelTemplateIds) { WfModelAssociationTemplate wfModelAssociationTemplate = new WfModelAssociationTemplate(); wfModelAssociationTemplate.setModelTemplateId(modelTemplateId); if (wfModelAssociationTemplateService.selectWfModelAssociationTemplateList(wfModelAssociationTemplate).size() > 0) { throw new RuntimeException("模型模板已关联流程,请先解除关联!"); } } return wfModelTemplateMapper.deleteWfModelTemplateByModelTemplateIds(modelTemplateIds); } /** * 删除模型模板信息 * * @param modelTemplateId 模型模板主键 * @return 结果 */ @Override public int deleteWfModelTemplateByModelTemplateId(String modelTemplateId) { return wfModelTemplateMapper.deleteWfModelTemplateByModelTemplateId(modelTemplateId); } /** * 修改模型模板xml * * @param wfModelTemplate 模型模板 * @return 结果 */ @Override public int editBpmnXml(WfModelTemplate wfModelTemplate) { BpmnModel bpmnModel = ModelUtils.getBpmnModel(wfModelTemplate.getBpmnXml()); if (ObjectUtil.isEmpty(bpmnModel)) { throw new RuntimeException("获取模型设计失败!"); } // 获取开始节点 StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel); if (ObjectUtil.isNull(startEvent)) { throw new RuntimeException("开始节点不存在,请检查流程设计是否有误!"); } if (FormType.PROCESS.getType().equals(wfModelTemplate.getFormType())) { // 获取开始节点配置的表单Key if (StrUtil.isBlank(startEvent.getFormKey())) { throw new RuntimeException("请配置流程表单"); } } //查看开始节点的后一个任务节点出口 List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows(); if (Objects.isNull(outgoingFlows)) { throw new RuntimeException("导入失败,流程配置错误!"); } // 保存 BPMN XML Process process = bpmnModel.getProcesses().get(0); WfModelAssociationTemplate wfModelAssociationTemplate = new WfModelAssociationTemplate(); wfModelAssociationTemplate.setModelTemplateId(wfModelTemplate.getModelTemplateId()); List<WfModelAssociationTemplate> wfModelAssociationTemplates = wfModelAssociationTemplateService.selectWfModelAssociationTemplateList(wfModelAssociationTemplate); for (WfModelAssociationTemplate modelAssociationTemplate : wfModelAssociationTemplates) { WfModelVo model = modelService.getModel(modelAssociationTemplate.getModelId()); BpmnModel modelBpmnModel = ModelUtils.getBpmnModel(model.getBpmnXml()); Process modelProcess = modelBpmnModel.getProcesses().get(0); process.setName(modelProcess.getName()); process.setId(modelProcess.getId()); repositoryService.addModelEditorSource(modelAssociationTemplate.getModelId(), ModelUtils.getBpmnXml(bpmnModel)); } // //遍历返回下一个节点信息 // for (SequenceFlow outgoingFlow : outgoingFlows) { // //类型自己判断(获取下个节点是任务节点) // FlowElement targetFlowElement = outgoingFlow.getTargetFlowElement(); // // 下个出口是用户任务,而且是要发起人节点才让保存 // if (targetFlowElement instanceof UserTask) { // if (StringUtils.equals(((UserTask) targetFlowElement).getAssignee(), "${initiator}")) { // break; // } else { // throw new RuntimeException("导入失败,流程第一个用户任务节点必须是发起人节点"); // } // } // } return updateWfModelTemplate(wfModelTemplate); } }
2929004360/ruoyi-sign
1,879
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfIconServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.flowable.domain.WfIcon; import com.ruoyi.flowable.mapper.WfIconMapper; import com.ruoyi.flowable.service.IWfIconService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 流程图标Service业务层处理 * * @author fengcheng * @date 2024-07-09 */ @Service public class WfIconServiceImpl implements IWfIconService { @Autowired private WfIconMapper wfIconMapper; /** * 查询流程图标 * * @param deploymentId 流程图标主键 * @return 流程图标 */ @Override public WfIcon selectWfIconByDeploymentId(String deploymentId) { return wfIconMapper.selectWfIconByDeploymentId(deploymentId); } /** * 查询流程图标列表 * * @param wfIcon 流程图标 * @return 流程图标 */ @Override public List<WfIcon> selectWfIconList(WfIcon wfIcon) { return wfIconMapper.selectWfIconList(wfIcon); } /** * 新增流程图标 * * @param wfIcon 流程图标 * @return 结果 */ @Override public int insertWfIcon(WfIcon wfIcon) { return wfIconMapper.insertWfIcon(wfIcon); } /** * 修改流程图标 * * @param wfIcon 流程图标 * @return 结果 */ @Override public int updateWfIcon(WfIcon wfIcon) { return wfIconMapper.updateWfIcon(wfIcon); } /** * 批量删除流程图标 * * @param deploymentIds 需要删除的流程图标主键 * @return 结果 */ @Override public int deleteWfIconByDeploymentIds(String[] deploymentIds) { return wfIconMapper.deleteWfIconByDeploymentIds(deploymentIds); } /** * 删除流程图标信息 * * @param deploymentId 流程图标主键 * @return 结果 */ @Override public int deleteWfIconByDeploymentId(String deploymentId) { return wfIconMapper.deleteWfIconByDeploymentId(deploymentId); } }
2929004360/ruoyi-sign
3,199
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfModelPermissionServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.flowable.domain.WfModelPermission; import com.ruoyi.flowable.mapper.WfModelPermissionMapper; import com.ruoyi.flowable.service.IWfModelPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 流程模型权限Service业务层处理 * * @author fengcheng * @date 2024-07-10 */ @Service public class WfModelPermissionServiceImpl implements IWfModelPermissionService { @Autowired private WfModelPermissionMapper wfModelPermissionMapper; /** * 查询流程模型权限 * * @param modelPermissionId 流程模型权限主键 * @return 流程模型权限 */ @Override public WfModelPermission selectWfModelPermissionByModelPermissionId(String modelPermissionId) { return wfModelPermissionMapper.selectWfModelPermissionByModelPermissionId(modelPermissionId); } /** * 查询流程模型权限列表 * * @param wfModelPermission 流程模型权限 * @param permissionIdList 业务id列表 * @return 流程模型权限 */ @Override public List<WfModelPermission> selectWfModelPermissionList(WfModelPermission wfModelPermission, List<Long> permissionIdList) { return wfModelPermissionMapper.selectWfModelPermissionList(wfModelPermission, permissionIdList); } /** * 新增流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ @Override public int insertWfModelPermission(WfModelPermission wfModelPermission) { wfModelPermission.setCreateTime(DateUtils.getNowDate()); return wfModelPermissionMapper.insertWfModelPermission(wfModelPermission); } /** * 修改流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ @Override public int updateWfModelPermission(WfModelPermission wfModelPermission) { wfModelPermission.setUpdateTime(DateUtils.getNowDate()); return wfModelPermissionMapper.updateWfModelPermission(wfModelPermission); } /** * 批量删除流程模型权限 * * @param modelPermissionIds 需要删除的流程模型权限主键 * @return 结果 */ @Override public int deleteWfModelPermissionByModelPermissionIds(String[] modelPermissionIds) { return wfModelPermissionMapper.deleteWfModelPermissionByModelPermissionIds(modelPermissionIds); } /** * 删除流程模型权限信息 * * @param modelPermissionId 流程模型权限主键 * @return 结果 */ @Override public int deleteWfModelPermissionByModelPermissionId(String modelPermissionId) { return wfModelPermissionMapper.deleteWfModelPermissionByModelPermissionId(modelPermissionId); } /** * 批量新增流程模型权限 * * @param permissionsList * @return */ @Override public int insertWfModelPermissionList(List<WfModelPermission> permissionsList) { return wfModelPermissionMapper.insertWfModelPermissionList(permissionsList); } /** * 根据模型ID删除流程模型权限 * * @param modelId * @return */ @Override public int deleteWfModelPermissionByModelId(String modelId) { return wfModelPermissionMapper.deleteWfModelPermissionByModelId(modelId); } }
2929004360/ruoyi-sign
4,812
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfCategoryServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.domain.WfCategory; import com.ruoyi.flowable.domain.bo.WfModelBo; import com.ruoyi.flowable.domain.vo.WfCategoryVo; import com.ruoyi.flowable.domain.vo.WfModelVo; import com.ruoyi.flowable.mapper.WfCategoryMapper; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import com.ruoyi.flowable.service.IWfCategoryService; import com.ruoyi.flowable.service.IWfModelService; import com.ruoyi.flowable.utils.StringUtils; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; import java.util.Map; /** * 流程分类Service业务层处理 * * @author fengcheng * @date 2022-01-15 */ @RequiredArgsConstructor @Service public class WfCategoryServiceImpl implements IWfCategoryService { private final WfCategoryMapper baseMapper; private final IWfModelService modelService; /** * 获取流程分类详细信息 * * @param categoryId 分类主键 * @return */ @Override public WfCategoryVo queryById(String categoryId) { return baseMapper.selectVoById(categoryId); } /** * 查询流程分类列表 * * @param category 流程分类对象 * @param pageQuery 分页参数 * @return */ @Override public TableDataInfo<WfCategoryVo> queryPageList(WfCategory category, PageQuery pageQuery) { LambdaQueryWrapper<WfCategory> lqw = buildQueryWrapper(category); Page<WfCategoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw); return TableDataInfo.build(result); } /** * 查询全部的流程分类列表 * * @param category 流程分类对象 * @return */ @Override public List<WfCategoryVo> queryList(WfCategory category) { LambdaQueryWrapper<WfCategory> lqw = buildQueryWrapper(category); return baseMapper.selectVoList(lqw); } private LambdaQueryWrapper<WfCategory> buildQueryWrapper(WfCategory category) { Map<String, Object> params = category.getParams(); LambdaQueryWrapper<WfCategory> lqw = Wrappers.lambdaQuery(); lqw.like(StringUtils.isNotBlank(category.getCategoryName()), WfCategory::getCategoryName, category.getCategoryName()); lqw.eq(StringUtils.isNotBlank(category.getCode()), WfCategory::getCode, category.getCode()); return lqw; } /** * 新增流程分类 * * @param category 流程分类信息 * @return 结果 */ @Override public int insertCategory(WfCategory category) { WfCategory add = BeanUtil.toBean(category, WfCategory.class); add.setCreateTime(DateUtils.getNowDate()); add.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName()); return baseMapper.insert(add); } /** * 修改流程分类 * * @param category 流程分类对象 * @return */ @Override public int updateCategory(WfCategory category) { WfCategory update = BeanUtil.toBean(category, WfCategory.class); update.setUpdateTime(DateUtils.getNowDate()); update.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName()); return baseMapper.updateById(update); } /** * 校验并删除数据 * * @param ids 主键集合 * @param isValid 是否校验,true-删除前校验,false-不校验 * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteWithValidByIds(Collection<String> ids, Boolean isValid) { if (isValid) { WfModelBo modelBo = new WfModelBo(); for (String id : ids) { modelBo.setCategory(baseMapper.selectVoById(id).getCode()); List<WfModelVo> wfModelVos = modelService.selectList(modelBo); if (wfModelVos.size() > 0) { throw new ServiceException("分类下存在流程模型,不允许删除"); } } } return baseMapper.deleteBatchIds(ids); } /** * 校验分类编码是否唯一 * * @param category 流程分类 * @return 结果 */ @Override public boolean checkCategoryCodeUnique(WfCategory category) { return baseMapper.exists(new LambdaQueryWrapper<WfCategory>() .eq(WfCategory::getCode, category.getCode()) .ne(ObjectUtil.isNotNull(category.getCategoryId()), WfCategory::getCategoryId, category.getCategoryId())); } }
281677160/openwrt-package
23,137
luci-app-amlogic/luasrc/controller/amlogic.lua
module("luci.controller.amlogic", package.seeall) local sys = require "luci.sys" local PKG_NAME = "luci-app-amlogic" function index() if not nixio.fs.access("/etc/config/amlogic") then return end local page = entry({ "admin", "system", "amlogic" }, alias("admin", "system", "amlogic", "info"), _("Amlogic Service"), 88) page.dependent = true page.acl_depends = { PKG_NAME } local platfrom = luci.sys.exec("cat /etc/flippy-openwrt-release 2>/dev/null | grep PLATFORM | awk -F'=' '{print $2}' | grep -oE '(amlogic|rockchip|allwinner|qemu)' | xargs") or "Unknown" local install_menu = luci.sys.exec("cat /etc/flippy-openwrt-release 2>/dev/null | grep SHOW_INSTALL_MENU | awk -F'=' '{print $2}' | grep -oE '(yes|no)' | xargs") or "Unknown" entry({ "admin", "system", "amlogic", "info" }, form("amlogic/amlogic_info"), _("Amlogic Service"), 1).leaf = true if (string.find(platfrom, "amlogic")) ~= nil or (string.find(install_menu, "yes")) ~= nil then entry({ "admin", "system", "amlogic", "install" }, form("amlogic/amlogic_install"), _("Install OpenWrt"), 2).leaf = true end entry({ "admin", "system", "amlogic", "upload" }, form("amlogic/amlogic_upload"), _("Manually Upload Update"), 3).leaf = true entry({ "admin", "system", "amlogic", "check" }, form("amlogic/amlogic_check"), _("Online Download Update"), 4).leaf = true entry({ "admin", "system", "amlogic", "backup" }, form("amlogic/amlogic_backup"), _("Backup Firmware Config"), 5).leaf = true entry({ "admin", "system", "amlogic", "backuplist" }, form("amlogic/amlogic_backuplist")).leaf = true if (string.find(platfrom, "qemu")) == nil then entry({ "admin", "system", "amlogic", "armcpu" }, cbi("amlogic/amlogic_armcpu"), _("CPU Settings"), 6).leaf = true end entry({ "admin", "system", "amlogic", "config" }, cbi("amlogic/amlogic_config"), _("Plugin Settings"), 7).leaf = true entry({ "admin", "system", "amlogic", "log" }, form("amlogic/amlogic_log"), _("Server Logs"), 8).leaf = true entry({ "admin", "system", "amlogic", "poweroff" }, form("amlogic/amlogic_poweroff"), _("PowerOff"), 9).leaf = true entry({ "admin", "system", "amlogic", "check_firmware" }, call("action_check_firmware")) entry({ "admin", "system", "amlogic", "check_plugin" }, call("action_check_plugin")) entry({ "admin", "system", "amlogic", "check_kernel" }, call("action_check_kernel")) entry({ "admin", "system", "amlogic", "refresh_log" }, call("action_refresh_log")) entry({ "admin", "system", "amlogic", "del_log" }, call("action_del_log")) entry({ "admin", "system", "amlogic", "start_model_database" }, call("action_check_model_database")).leaf = true entry({ "admin", "system", "amlogic", "start_check_install" }, call("action_start_check_install")).leaf = true entry({ "admin", "system", "amlogic", "start_check_firmware" }, call("action_start_check_firmware")).leaf = true entry({ "admin", "system", "amlogic", "start_check_plugin" }, call("action_start_check_plugin")).leaf = true entry({ "admin", "system", "amlogic", "start_check_kernel" }, call("action_start_check_kernel")).leaf = true entry({ "admin", "system", "amlogic", "start_check_rescue" }, call("action_start_check_rescue")).leaf = true entry({ "admin", "system", "amlogic", "start_check_upfiles" }, call("action_start_check_upfiles")).leaf = true entry({ "admin", "system", "amlogic", "start_amlogic_install" }, call("action_start_amlogic_install")).leaf = true entry({ "admin", "system", "amlogic", "start_amlogic_update" }, call("action_start_amlogic_update")).leaf = true entry({ "admin", "system", "amlogic", "start_amlogic_kernel" }, call("action_start_amlogic_kernel")).leaf = true entry({ "admin", "system", "amlogic", "start_amlogic_plugin" }, call("action_start_amlogic_plugin")).leaf = true entry({ "admin", "system", "amlogic", "start_amlogic_rescue" }, call("action_start_amlogic_rescue")).leaf = true entry({ "admin", "system", "amlogic", "start_snapshot_delete" }, call("action_start_snapshot_delete")).leaf = true entry({ "admin", "system", "amlogic", "start_snapshot_restore" }, call("action_start_snapshot_restore")).leaf = true entry({ "admin", "system", "amlogic", "start_snapshot_list" }, call("action_check_snapshot")).leaf = true entry({ "admin", "system", "amlogic", "start_openwrt_author" }, call("action_openwrt_author")).leaf = true entry({ "admin", "system", "amlogic", "state" }, call("action_state")).leaf = true entry({ "admin", "system", "amlogic", "start_poweroff" }, call("action_poweroff")).leaf = true entry({ "admin", "system", "amlogic", "start_switch" }, call("action_switch")).leaf = true end --Remove the spaces in the string function trim(str) --return (string.gsub(str, "^%s*(.-)%s*$", "%1")) return (string.gsub(str, "%s+", "")) end --Create a temporary folder local tmp_upload_dir = luci.sys.exec("[ -d /tmp/upload ] || mkdir -p /tmp/upload >/dev/null") local tmp_amlogic_dir = luci.sys.exec("[ -d /tmp/amlogic ] || mkdir -p /tmp/amlogic >/dev/null") --Whether to automatically restore the firmware config local amlogic_firmware_config = luci.sys.exec("uci get amlogic.config.amlogic_firmware_config 2>/dev/null") or "1" if tonumber(amlogic_firmware_config) == 0 then update_restore_config = "no-restore" else update_restore_config = "restore" end --Whether to automatically write to the bootLoader local amlogic_write_bootloader = luci.sys.exec("uci get amlogic.config.amlogic_write_bootloader 2>/dev/null") or "1" if tonumber(amlogic_write_bootloader) == 0 then auto_write_bootloader = "no" else auto_write_bootloader = "yes" end --Set the file system type of the shared partition local amlogic_shared_fstype = luci.sys.exec("uci get amlogic.config.amlogic_shared_fstype 2>/dev/null") or "" if trim(amlogic_shared_fstype) == "" then auto_shared_fstype = "ext4" else auto_shared_fstype = trim(amlogic_shared_fstype) end --Device identification device_platfrom = luci.sys.exec("cat /etc/flippy-openwrt-release 2>/dev/null | grep PLATFORM | awk -F'=' '{print $2}' | grep -oE '(amlogic|rockchip|allwinner|qemu)' | xargs") or "Unknown" if (string.find(device_platfrom, "rockchip")) ~= nil then device_install_script = "" device_update_script = "openwrt-update-rockchip" device_kernel_script = "openwrt-kernel" elseif (string.find(device_platfrom, "allwinner")) ~= nil then device_install_script = "openwrt-install-allwinner" device_update_script = "openwrt-update-allwinner" device_kernel_script = "openwrt-kernel" elseif (string.find(device_platfrom, "qemu")) ~= nil then device_install_script = "" device_update_script = "openwrt-update-kvm" device_kernel_script = "openwrt-kernel" else device_install_script = "openwrt-install-amlogic" device_update_script = "openwrt-update-amlogic" device_kernel_script = "openwrt-kernel" end --General array functions function string.split(input, delimiter) input = tostring(input) delimiter = tostring(delimiter) if (delimiter == '') then return false end local pos, arr = 0, {} -- for each divider found for st, sp in function() return string.find(input, delimiter, pos, true) end do table.insert(arr, string.sub(input, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(input, pos)) return arr end --Refresh the log function action_refresh_log() local logfile = "/tmp/amlogic/amlogic.log" if not nixio.fs.access(logfile) then luci.sys.exec("uname -a > /tmp/amlogic/amlogic.log && sync") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_install.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_upfiles.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_plugin.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_kernel.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_firmware.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_rescue.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_running_script.log && sync >/dev/null 2>&1") end luci.http.prepare_content("text/plain; charset=utf-8") local f = io.open(logfile, "r+") f:seek("set") local a = f:read(2048000) or "" f:close() luci.http.write(a) end --Delete the logs function action_del_log() luci.sys.exec(": > /tmp/amlogic/amlogic.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_install.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_upfiles.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_plugin.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_kernel.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_firmware.log") luci.sys.exec(": > /tmp/amlogic/amlogic_check_rescue.log") luci.sys.exec(": > /tmp/amlogic/amlogic_running_script.log") end --Upgrade luci-app-amlogic plugin function start_amlogic_plugin() local log_file = "/tmp/amlogic/amlogic_check_plugin.log" local running_lock = "/tmp/amlogic/amlogic_running_script.log" local config_file = "/etc/config/amlogic" local config_bak = "/etc/config/amlogic_bak" -- 1. Create a running lock and clear previous log luci.sys.call("echo '1@Plugin update in progress, try again later!' > " .. running_lock .. " && > " .. log_file) -- 2. Backup config file luci.sys.call(string.format("[ -f %s ] && cp -vf %s %s >> %s 2>&1", config_file, config_file, config_bak, log_file)) -- 3. Detect and install local install_status = 1 if luci.sys.call("command -v opkg >/dev/null") == 0 then luci.sys.call("echo 'System uses opkg. Attempting to install .ipk package...' >> " .. log_file) local install_cmd = string.format("opkg --force-reinstall install /tmp/amlogic/*.ipk >> %s 2>&1", log_file) install_status = luci.sys.call(install_cmd) elseif luci.sys.call("command -v apk >/dev/null") == 0 then luci.sys.call("echo 'System uses apk. Attempting to install .apk package...' >> " .. log_file) local install_cmd = string.format("apk add --force-overwrite --allow-untrusted /tmp/amlogic/*.apk >> %s 2>&1", log_file) install_status = luci.sys.call(install_cmd) else luci.sys.call("echo 'Error: Neither opkg nor apk found. Aborting.' >> " .. log_file) end -- 4. Check result and finalize if install_status == 0 then -- SUCCESS luci.sys.call("echo 'Installation successful. Finalizing...' >> " .. log_file) luci.sys.call(string.format("[ -f %s ] && cp -vf %s %s >> %s 2>&1", config_bak, config_bak, config_file, log_file)) luci.sys.call("rm -rf /tmp/luci-indexcache /tmp/luci-modulecache/* " .. config_bak) luci.sys.call("echo '' > " .. running_lock) luci.sys.call("echo 'Successful Update' > " .. log_file) return 0 else -- FAILURE luci.sys.call("echo '--- INSTALLATION FAILED! ---' >> " .. log_file) luci.sys.call("echo 'Restoring configuration and aborting.' >> " .. log_file) luci.sys.call(string.format("[ -f %s ] && cp -vf %s %s >> %s 2>&1", config_bak, config_bak, config_file, log_file)) luci.sys.call("rm -f " .. config_bak) luci.sys.call("echo '' > " .. running_lock) return install_status end end --Upgrade the kernel function start_amlogic_kernel() luci.sys.call("echo '2@Kernel update in progress, try again later!' > /tmp/amlogic/amlogic_running_script.log && sync >/dev/null 2>&1") luci.sys.call("chmod +x /usr/sbin/" .. device_kernel_script .. " >/dev/null 2>&1") local state = luci.sys.call("/usr/sbin/" .. device_kernel_script .. " " .. auto_write_bootloader .. " > /tmp/amlogic/amlogic_check_kernel.log && sync >/dev/null 2>&1") return state end --Upgrade amlogic openwrt firmware function start_amlogic_update() luci.sys.call("echo '3@OpenWrt update in progress, try again later!' > /tmp/amlogic/amlogic_running_script.log && sync >/dev/null 2>&1") luci.sys.call("chmod +x /usr/sbin/" .. device_update_script .. " >/dev/null 2>&1") local amlogic_update_sel = luci.http.formvalue("amlogic_update_sel") local res = string.split(amlogic_update_sel, "@") local update_firmware_name = res[1] or "auto" local update_firmware_updated = res[2] or "updated" local update_write_path = res[3] or "/tmp" luci.sys.call("echo " .. update_firmware_updated .. " > " .. update_write_path .. "/.luci-app-amlogic/op_release_code 2>/dev/null && sync") local state = luci.sys.call("/usr/sbin/" .. device_update_script .. " " .. update_firmware_name .. " " .. auto_write_bootloader .. " " .. update_restore_config .. " > /tmp/amlogic/amlogic_check_firmware.log && sync 2>/dev/null") return state end --Read rescue kernel log local function start_amlogic_rescue() luci.sys.call("echo '4@Kernel rescue in progress, try again later!' > /tmp/amlogic/amlogic_running_script.log && sync >/dev/null 2>&1") luci.sys.call("chmod +x /usr/sbin/" .. device_kernel_script .. " >/dev/null 2>&1") local state = luci.sys.call("/usr/sbin/" .. device_kernel_script .. " -s > /tmp/amlogic/amlogic_check_rescue.log && sync >/dev/null 2>&1") luci.sys.call("echo '' > /tmp/amlogic/amlogic_running_script.log && sync >/dev/null 2>&1") return state end --Install amlogic openwrt firmware function start_amlogic_install() luci.sys.exec("chmod +x /usr/sbin/" .. device_install_script .. " >/dev/null 2>&1") local amlogic_install_sel = luci.http.formvalue("amlogic_install_sel") local res = string.split(amlogic_install_sel, "@") soc_id = res[1] or "99" if tonumber(res[1]) == 99 then dtb_filename = res[2] or "auto_dtb" else dtb_filename = "auto_dtb" end local state = luci.sys.call("/usr/sbin/" .. device_install_script .. " " .. auto_write_bootloader .. " " .. soc_id .. " " .. dtb_filename .. " " .. auto_shared_fstype .. " > /tmp/amlogic/amlogic_check_install.log && sync 2>/dev/null") return state end --Delets the snapshot function start_snapshot_delete() local snapshot_delete_sel = luci.http.formvalue("snapshot_delete_sel") local state = luci.sys.exec("btrfs subvolume delete -c /.snapshots/" .. snapshot_delete_sel .. " 2>/dev/null && sync") return state end --Restore to this snapshot function start_snapshot_restore() local snapshot_restore_sel = luci.http.formvalue("snapshot_restore_sel") local state = luci.sys.exec("btrfs subvolume snapshot /.snapshots/etc-" .. snapshot_restore_sel .. " /etc 2>/dev/null && sync") local state_nowreboot = luci.sys.exec("echo 'b' > /proc/sysrq-trigger 2>/dev/null") return state end --Check the plugin function action_check_plugin() luci.sys.exec("chmod +x /usr/share/amlogic/amlogic_check_plugin.sh >/dev/null 2>&1") return luci.sys.call("/usr/share/amlogic/amlogic_check_plugin.sh >/dev/null 2>&1") end --Check and download the kernel function check_kernel() luci.sys.exec("chmod +x /usr/share/amlogic/amlogic_check_kernel.sh >/dev/null 2>&1") local kernel_options = luci.http.formvalue("kernel_options") if kernel_options == "check" then local state = luci.sys.call("/usr/share/amlogic/amlogic_check_kernel.sh -check >/dev/null 2>&1") else local state = luci.sys.call("/usr/share/amlogic/amlogic_check_kernel.sh -download " .. kernel_options .. " >/dev/null 2>&1") end return state end --Check the kernel function action_check_kernel() luci.http.prepare_content("application/json") luci.http.write_json({ check_kernel_status = check_kernel(); }) end --Check the firmware function check_firmware() luci.sys.exec("chmod +x /usr/share/amlogic/amlogic_check_firmware.sh >/dev/null 2>&1") local firmware_options = luci.http.formvalue("firmware_options") if firmware_options == "check" then local state = luci.sys.call("/usr/share/amlogic/amlogic_check_firmware.sh -check >/dev/null 2>&1") else local state = luci.sys.call("/usr/share/amlogic/amlogic_check_firmware.sh -download " .. firmware_options .. " >/dev/null 2>&1") end return state end --Check the openwrt firmware version online function action_check_firmware() luci.http.prepare_content("application/json") luci.http.write_json({ check_firmware_status = check_firmware(); }) end --Read upload files log local function start_check_upfiles() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_upfiles.log 2>/dev/null") end --Read plug-in check log local function start_check_plugin() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_plugin.log 2>/dev/null") end --Read kernel check log local function start_check_kernel() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_kernel.log 2>/dev/null") end --Read openwrt firmware check log local function start_check_firmware() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_firmware.log 2>/dev/null") end --Read rescue kernel log local function start_check_rescue() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_rescue.log 2>/dev/null") end --Read openwrt install log local function start_check_install() return luci.sys.exec("sed -n '$p' /tmp/amlogic/amlogic_check_install.log 2>/dev/null") end --Return online check plugin result function action_start_check_plugin() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_plugin = start_check_plugin(); }) end --Return online check kernel result function action_start_check_kernel() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_kernel = start_check_kernel(); }) end --Return online check openwrt firmware result function action_start_check_firmware() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_firmware = start_check_firmware(); }) end --Return online check rescue kernel result function action_start_check_rescue() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_rescue = start_check_rescue(); }) end --Return online install openwrt result function action_start_check_install() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_install = start_check_install(); }) end --Return online install openwrt result for amlogic function action_start_amlogic_install() luci.http.prepare_content("application/json") luci.http.write_json({ rule_install_status = start_amlogic_install(); }) end --Return snapshot delete result function action_start_snapshot_delete() luci.http.prepare_content("application/json") luci.http.write_json({ rule_delete_status = start_snapshot_delete(); }) end --Return snapshot restore result function action_start_snapshot_restore() luci.http.prepare_content("application/json") luci.http.write_json({ rule_restore_status = start_snapshot_restore(); }) end --Return openwrt update result for amlogic function action_start_amlogic_update() luci.http.prepare_content("application/json") luci.http.write_json({ rule_update_status = start_amlogic_update(); }) end --Return kernel update result function action_start_amlogic_kernel() luci.http.prepare_content("application/json") luci.http.write_json({ rule_kernel_status = start_amlogic_kernel(); }) end --Return plugin update result function action_start_amlogic_plugin() luci.http.prepare_content("application/json") luci.http.write_json({ rule_plugin_status = start_amlogic_plugin(); }) end --Return rescue kernel result function action_start_amlogic_rescue() luci.http.prepare_content("application/json") luci.http.write_json({ start_amlogic_rescue = start_amlogic_rescue(); }) end --Return files upload result function action_start_check_upfiles() luci.http.prepare_content("application/json") luci.http.write_json({ start_check_upfiles = start_check_upfiles(); }) end --Return the current openwrt firmware version local function current_firmware_version() return luci.sys.exec("uname -r 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}.[0-9]+'") or "Invalid value." end --Return the current plugin version local function current_plugin_version() local version_str = "" -- Check if opkg command exists if sys.call("command -v opkg >/dev/null") == 0 then local opkg_cmd = string.format("opkg list-installed | grep '^%s' | awk '{print $3}' | cut -d'-' -f1", PKG_NAME) version_str = trim(sys.exec(opkg_cmd)) end -- If opkg failed or not found, check if apk command exists if version_str == "" and sys.call("command -v apk >/dev/null") == 0 then local apk_cmd = string.format("apk list --installed 2>/dev/null | grep '^%s' | awk '{print $1}' | cut -d'-' -f4", PKG_NAME) version_str = trim(sys.exec(apk_cmd)) end if version_str ~= "" then return version_str else return "Invalid value." end end --Return the current kernel version local function current_kernel_version() return luci.sys.exec("uname -r 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}.[0-9]+'") or "Invalid value." end --Return the current kernel branch local function current_kernel_branch() local default_kernel_branch = luci.sys.exec("uname -r 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}'") local amlogic_kernel_branch = luci.sys.exec("uci get amlogic.config.amlogic_kernel_branch 2>/dev/null | grep -oE '^[1-9].[0-9]{1,3}'") or "" if trim(amlogic_kernel_branch) == "" then return default_kernel_branch else return amlogic_kernel_branch end end --Return current version information function action_state() luci.http.prepare_content("application/json") luci.http.write_json({ current_firmware_version = current_firmware_version(), current_plugin_version = current_plugin_version(), current_kernel_version = current_kernel_version(), current_kernel_branch = current_kernel_branch(); }) end --Read external model database local function my_model_database() if (string.find(device_platfrom, "allwinner")) ~= nil then return luci.sys.exec("cat /etc/model_database.txt 2>/dev/null | grep -E '^w[0-9]{1,9}.*:' | awk -F ':' '{print $1,$2}' OFS='###' ORS='@@@' | tr ' ' '~' 2>&1") else return luci.sys.exec("cat /etc/model_database.txt 2>/dev/null | grep -E '^[0-9]{1,9}.*:' | awk -F ':' '{print $1,$2}' OFS='###' ORS='@@@' | tr ' ' '~' 2>&1") end end --Return external model database function action_check_model_database() luci.http.prepare_content("application/json") luci.http.write_json({ my_model_database = my_model_database(); }) end --Return the current snapshot list local function current_snapshot() return luci.sys.exec("btrfs subvolume list -rt / | awk '{print $4}' | grep .snapshots") or "Invalid value." end --Return current snapshot information function action_check_snapshot() luci.http.prepare_content("application/json") luci.http.write_json({ current_snapshot = current_snapshot(); }) end --Return the openwrt compile author local function openwrt_author() return luci.sys.exec("uci get amlogic.config.amlogic_firmware_repo 2>/dev/null") or "Invalid value." end --Return current snapshot information function action_openwrt_author() luci.http.prepare_content("application/json") luci.http.write_json({ openwrt_author = openwrt_author(); }) end --Shut down the router function action_poweroff() luci.sys.exec("/sbin/poweroff") end --Switching dual partition function action_switch() luci.sys.exec("[ -f /boot/efi/EFI/BOOT/grub.cfg.prev ] && (cd /boot/efi/EFI/BOOT/ && mv -f grub.cfg grub.cfg.bak && mv -f grub.cfg.prev grub.cfg && mv -f grub.cfg.bak grub.cfg.prev)") luci.sys.exec("sync && reboot") end
2929004360/ruoyi-sign
9,344
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfInstanceServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.BetweenFormatter; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import com.ruoyi.flowable.constant.TaskConstants; import com.ruoyi.flowable.domain.vo.WfFormVo; import com.ruoyi.flowable.domain.vo.WfTaskVo; import com.ruoyi.flowable.factory.FlowServiceFactory; import com.ruoyi.flowable.service.IWfDeployFormService; import com.ruoyi.flowable.service.IWfInstanceService; import com.ruoyi.flowable.utils.JsonUtils; import com.ruoyi.flowable.utils.StringUtils; import com.ruoyi.system.api.service.ISysDeptServiceApi; import com.ruoyi.system.api.service.ISysRoleServiceApi; import com.ruoyi.system.api.service.ISysUserServiceApi; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.flowable.common.engine.api.FlowableObjectNotFoundException; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.task.Comment; import org.flowable.identitylink.api.history.HistoricIdentityLink; import org.flowable.task.api.history.HistoricTaskInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 工作流流程实例管理 * * @author fengcheng * @createTime 2022/3/10 00:12 */ @RequiredArgsConstructor @Service @Slf4j public class WfInstanceServiceImpl extends FlowServiceFactory implements IWfInstanceService { private final IWfDeployFormService deployFormService; @Autowired private ISysUserServiceApi userServiceApi; @Autowired private ISysRoleServiceApi roleServiceApi; @Autowired private ISysDeptServiceApi deptServiceApi; /** * 结束流程实例 * * @param vo */ @Override public void stopProcessInstance(WfTaskBo vo) { String taskId = vo.getTaskId(); } /** * 激活或挂起流程实例 * * @param state 状态 * @param instanceId 流程实例ID */ @Override public void updateState(Integer state, String instanceId) { // 激活 if (state == 1) { runtimeService.activateProcessInstanceById(instanceId); } // 挂起 if (state == 2) { runtimeService.suspendProcessInstanceById(instanceId); } } /** * 删除流程实例ID * * @param instanceId 流程实例ID * @param deleteReason 删除原因 */ @Override @Transactional(rollbackFor = Exception.class) public void delete(String instanceId, String deleteReason) { // 查询历史数据 HistoricProcessInstance historicProcessInstance = getHistoricProcessInstanceById(instanceId); if (historicProcessInstance.getEndTime() != null) { historyService.deleteHistoricProcessInstance(historicProcessInstance.getId()); return; } // 删除流程实例 runtimeService.deleteProcessInstance(instanceId, deleteReason); // 删除历史流程实例 historyService.deleteHistoricProcessInstance(instanceId); } /** * 根据实例ID查询历史实例数据 * * @param processInstanceId * @return */ @Override public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) { HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult(); if (Objects.isNull(historicProcessInstance)) { throw new FlowableObjectNotFoundException("流程实例不存在: " + processInstanceId); } return historicProcessInstance; } /** * 流程历史流转记录 * * @param procInsId 流程实例Id * @return */ @Override public Map<String, Object> queryDetailProcess(String procInsId, String deployId) { Map<String, Object> map = new HashMap<>(16); if (StringUtils.isNotBlank(procInsId)) { List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery() .processInstanceId(procInsId) .orderByHistoricTaskInstanceStartTime().desc() .list(); List<Comment> commentList = taskService.getProcessInstanceComments(procInsId); List<WfTaskVo> taskVoList = new ArrayList<>(taskInstanceList.size()); taskInstanceList.forEach(taskInstance -> { WfTaskVo taskVo = new WfTaskVo(); taskVo.setProcDefId(taskInstance.getProcessDefinitionId()); taskVo.setTaskId(taskInstance.getId()); taskVo.setTaskDefKey(taskInstance.getTaskDefinitionKey()); taskVo.setTaskName(taskInstance.getName()); taskVo.setCreateTime(taskInstance.getStartTime()); taskVo.setFinishTime(taskInstance.getEndTime()); if (StringUtils.isNotBlank(taskInstance.getAssignee())) { Long userId = Long.parseLong(taskInstance.getAssignee()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); taskVo.setAssigneeId(userId); taskVo.setAssigneeName(nickName); } // 展示审批人员 List<HistoricIdentityLink> linksForTask = historyService.getHistoricIdentityLinksForTask(taskInstance.getId()); StringBuilder stringBuilder = new StringBuilder(); for (HistoricIdentityLink identityLink : linksForTask) { if ("candidate".equals(identityLink.getType())) { if (StringUtils.isNotBlank(identityLink.getUserId())) { Long userId = Long.parseLong(identityLink.getUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); stringBuilder.append(nickName).append(","); } if (StringUtils.isNotBlank(identityLink.getGroupId())) { if (identityLink.getGroupId().startsWith(TaskConstants.ROLE_GROUP_PREFIX)) { Long roleId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.ROLE_GROUP_PREFIX)); SysRole role = roleServiceApi.selectRoleById(roleId); stringBuilder.append(role.getRoleName()).append(","); } else if (identityLink.getGroupId().startsWith(TaskConstants.DEPT_GROUP_PREFIX)) { Long deptId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.DEPT_GROUP_PREFIX)); SysDept dept = deptServiceApi.selectDeptById(deptId); stringBuilder.append(dept.getDeptName()).append(","); } } } } if (StringUtils.isNotBlank(stringBuilder)) { taskVo.setCandidate(stringBuilder.substring(0, stringBuilder.length() - 1)); } if (ObjectUtil.isNotNull(taskInstance.getDurationInMillis())) { taskVo.setDuration(DateUtil.formatBetween(taskInstance.getDurationInMillis(), BetweenFormatter.Level.SECOND)); } // 获取意见评论内容 if (CollUtil.isNotEmpty(commentList)) { List<Comment> comments = new ArrayList<>(); // commentList.stream().filter(comment -> taskInstance.getId().equals(comment.getTaskId())).collect(Collectors.toList()); for (Comment comment : commentList) { if (comment.getTaskId().equals(taskInstance.getId())) { comments.add(comment); // taskVo.setComment(WfCommentDto.builder().type(comment.getType()).comment(comment.getFullMessage()).build()); } } taskVo.setCommentList(comments); } taskVoList.add(taskVo); }); map.put("flowList", taskVoList); // // 查询当前任务是否完成 // List<Task> taskList = taskService.createTaskQuery().processInstanceId(procInsId).list(); // if (CollectionUtils.isNotEmpty(taskList)) { // map.put("finished", true); // } else { // map.put("finished", false); // } } // 第一次申请获取初始化表单 if (StringUtils.isNotBlank(deployId)) { WfFormVo formVo = deployFormService.selectDeployFormByDeployId(deployId); if (Objects.isNull(formVo)) { throw new ServiceException("请先配置流程表单"); } map.put("formData", JsonUtils.parseObject(formVo.getContent(), Map.class)); } return map; } }
2929004360/ruoyi-sign
2,939
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfModelProcdefServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.flowable.domain.WfModelProcdef; import com.ruoyi.flowable.mapper.WfModelProcdefMapper; import com.ruoyi.flowable.service.IWfModelProcdefService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 模型部署Service业务层处理 * * @author fengcheng * @date 2024-07-11 */ @Service public class WfModelProcdefServiceImpl implements IWfModelProcdefService { @Autowired private WfModelProcdefMapper wfModelProcdefMapper; /** * 查询模型部署 * * @param modelId 模型部署主键 * @return 模型部署 */ @Override public WfModelProcdef selectWfModelProcdefByModelId(String modelId) { return wfModelProcdefMapper.selectWfModelProcdefByModelId(modelId); } /** * 查询模型部署列表 * * @param wfModelProcdef 模型部署 * @return 模型部署 */ @Override public List<WfModelProcdef> selectWfModelProcdefList(WfModelProcdef wfModelProcdef) { return wfModelProcdefMapper.selectWfModelProcdefList(wfModelProcdef); } /** * 新增模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ @Override public int insertWfModelProcdef(WfModelProcdef wfModelProcdef) { return wfModelProcdefMapper.insertWfModelProcdef(wfModelProcdef); } /** * 修改模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ @Override public int updateWfModelProcdef(WfModelProcdef wfModelProcdef) { return wfModelProcdefMapper.updateWfModelProcdef(wfModelProcdef); } /** * 批量删除模型部署 * * @param modelIds 需要删除的模型部署主键 * @return 结果 */ @Override public int deleteWfModelProcdefByModelIds(String[] modelIds) { return wfModelProcdefMapper.deleteWfModelProcdefByModelIds(modelIds); } /** * 删除模型部署信息 * * @param modelId 模型部署主键 * @return 结果 */ @Override public int deleteWfModelProcdefByModelId(String modelId) { return wfModelProcdefMapper.deleteWfModelProcdefByModelId(modelId); } /** * 根据模型id列表查询流程定义id * * @param modelIdList * @return */ @Override public List<String> selectWfModelProcdefListByModelIdList(List<String> modelIdList) { return wfModelProcdefMapper.selectWfModelProcdefListByModelIdList(modelIdList); } /** * 根据部署id删除模型部署信息 * * @param deployId * @return */ @Override public int deleteWfModelProcdefByProcdefId(String deployId) { return wfModelProcdefMapper.deleteWfModelProcdefByProcdefId(deployId); } /** * 根据部署id查询模型部署信息 * * @param procdefId * @return */ @Override public WfModelProcdef selectWfModelProcdefByProcdefId(String procdefId) { return wfModelProcdefMapper.selectWfModelProcdefByProcdefId(procdefId); } }
2929004360/ruoyi-sign
4,654
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfDeployFormServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.flowable.domain.WfDeployForm; import com.ruoyi.flowable.domain.WfForm; import com.ruoyi.flowable.domain.vo.WfFormVo; import com.ruoyi.flowable.mapper.WfDeployFormMapper; import com.ruoyi.flowable.mapper.WfFormMapper; import com.ruoyi.flowable.service.IWfDeployFormService; import com.ruoyi.flowable.utils.ModelUtils; import com.ruoyi.flowable.utils.StringUtils; import lombok.RequiredArgsConstructor; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.FlowNode; import org.flowable.bpmn.model.StartEvent; import org.flowable.bpmn.model.UserTask; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 流程实例关联表单Service业务层处理 * * @author fengcheng * @createTime 2022/3/7 22:07 */ @RequiredArgsConstructor @Service public class WfDeployFormServiceImpl implements IWfDeployFormService { private final WfDeployFormMapper baseMapper; private final WfFormMapper formMapper; /** * 新增流程实例关联表单 * * @param deployForm 流程实例关联表单 * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int insertWfDeployForm(WfDeployForm deployForm) { // 删除部署流程和表单的关联关系 baseMapper.delete(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployForm.getDeployId())); // 新增部署流程和表单关系 return baseMapper.insert(deployForm); } @Override @Transactional(rollbackFor = Exception.class) public boolean saveInternalDeployForm(String deployId, BpmnModel bpmnModel) { List<WfDeployForm> deployFormList = new ArrayList<>(); // 获取开始节点 StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel); if (ObjectUtil.isNull(startEvent)) { throw new RuntimeException("开始节点不存在,请检查流程设计是否有误!" ); } // 保存开始节点表单信息 WfDeployForm startDeployForm = buildDeployForm(deployId, startEvent); if (ObjectUtil.isNotNull(startDeployForm)) { deployFormList.add(startDeployForm); } // 保存用户节点表单信息 Collection<UserTask> userTasks = ModelUtils.getAllUserTaskEvent(bpmnModel); if (CollUtil.isNotEmpty(userTasks)) { for (UserTask userTask : userTasks) { WfDeployForm userTaskDeployForm = buildDeployForm(deployId, userTask); if (ObjectUtil.isNotNull(userTaskDeployForm)) { deployFormList.add(userTaskDeployForm); } } } // 批量新增部署流程和表单关联信息 return baseMapper.insertBatch(deployFormList); } /** * 查询流程挂着的表单 * * @param deployId * @return */ @Override public WfFormVo selectDeployFormByDeployId(String deployId) { QueryWrapper<WfForm> wrapper = Wrappers.query(); wrapper.eq("t2.deploy_id" , deployId); List<WfFormVo> list = formMapper.selectFormVoList(wrapper); if (ObjectUtil.isNotEmpty(list)) { if (list.size() != 1) { throw new ServiceException("表单信息查询错误" ); } else { return list.get(0); } } else { return null; } } /** * 构建部署表单关联信息对象 * * @param deployId 部署ID * @param node 节点信息 * @return 部署表单关联对象。若无表单信息(formKey),则返回null */ private WfDeployForm buildDeployForm(String deployId, FlowNode node) { String formKey = ModelUtils.getFormKey(node); if (StringUtils.isEmpty(formKey)) { return null; } Long formId = Convert.toLong(StringUtils.substringAfter(formKey, "key_" )); WfForm wfForm = formMapper.selectById(formId); if (ObjectUtil.isNull(wfForm)) { throw new ServiceException("表单信息查询错误" ); } WfDeployForm deployForm = new WfDeployForm(); deployForm.setDeployId(deployId); deployForm.setFormKey(formKey); deployForm.setNodeKey(node.getId()); deployForm.setFormName(wfForm.getFormName()); deployForm.setNodeName(node.getName()); deployForm.setContent(wfForm.getContent()); return deployForm; } }
281677160/openwrt-package
2,106
luci-app-amlogic/luasrc/view/amlogic/other_rescue.htm
<style> .NewsTdHeight{ line-height: 20px; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="35%" align="right"><input type="button" class="cbi-button cbi-button-reload" value="<%:Rescue the original system kernel%>" onclick="return b_rescue_kernel(this)"/></td><td width="65%" align="left"><span id="_current_rescue_version"><%:Collecting data...%></span> <span id="_check_rescue"></span></td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function b_rescue_kernel(btn) { btn.disabled = true; btn.value = '<%:Rescuing...%>'; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_rescue")%>', null, function(x, status) { if ( x && x.status == 200 ) { btn.disabled = false; btn.value = '<%:Rescue the original system kernel%>'; } else { btn.disabled = false; btn.value = '<%:Rescue the original system kernel%>'; } return false; }); } var _check_rescue = document.getElementById('_check_rescue'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_rescue")%>', status.start_check_rescue, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_rescue != "\n" && status.start_check_rescue != "" ) { _check_rescue.innerHTML = '<font color="blue"> '+status.start_check_rescue+'</font>'; } if ( status.start_check_rescue == "\n" || status.start_check_rescue == "" ) { _check_rescue.innerHTML = ''; } } }); var _current_rescue_version = document.getElementById('_current_rescue_version'); XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "state")%>', null, function(x, status) { if ( x && x.status == 200 ) { _current_rescue_version.innerHTML = status.current_kernel_version ? "<font color=green><%:Current Version%> [ "+status.current_kernel_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; } }); //]]></script>
2929004360/ruoyi-sign
2,881
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfBusinessProcessServiceImpl.java
package com.ruoyi.flowable.service.impl; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.mapper.WfBusinessProcessMapper; import com.ruoyi.flowable.service.IWfBusinessProcessService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 业务流程Service业务层处理 * * @author fengcheng * @date 2024-07-15 */ @Service public class WfBusinessProcessServiceImpl implements IWfBusinessProcessService { @Autowired private WfBusinessProcessMapper wfBusinessProcessMapper; /** * 查询业务流程 * * @param businessId 业务流程主键 * @return 业务流程 */ @Override public WfBusinessProcess selectWfBusinessProcessByBusinessId(String businessId) { return wfBusinessProcessMapper.selectWfBusinessProcessByBusinessId(businessId); } /** * 查询业务流程列表 * * @param wfBusinessProcess 业务流程 * @return 业务流程 */ @Override public List<WfBusinessProcess> selectWfBusinessProcessList(WfBusinessProcess wfBusinessProcess) { return wfBusinessProcessMapper.selectWfBusinessProcessList(wfBusinessProcess); } /** * 新增业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ @Override public int insertWfBusinessProcess(WfBusinessProcess wfBusinessProcess) { return wfBusinessProcessMapper.insertWfBusinessProcess(wfBusinessProcess); } /** * 修改业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ @Override public int updateWfBusinessProcess(WfBusinessProcess wfBusinessProcess) { return wfBusinessProcessMapper.updateWfBusinessProcess(wfBusinessProcess); } /** * 批量删除业务流程 * * @param businessIds 需要删除的业务流程主键 * @return 结果 */ @Override public int deleteWfBusinessProcessByBusinessIds(String[] businessIds) { return wfBusinessProcessMapper.deleteWfBusinessProcessByBusinessIds(businessIds); } /** * 删除业务流程信息 * * @param businessId 业务流程主键 * @param type 业务类型 * @return 结果 */ @Override public int deleteWfBusinessProcessByBusinessId(String businessId, String type) { return wfBusinessProcessMapper.deleteWfBusinessProcessByBusinessId(businessId, type); } /** * 根据流程ID查询业务流程 * * @param processId * @return */ @Override public WfBusinessProcess selectWfBusinessProcessByProcessId(String processId) { return wfBusinessProcessMapper.selectWfBusinessProcessByProcessId(processId); } /** * 根据流程ID查询业务流程列表 * * @param ids * @return */ @Override public List<WfBusinessProcess> selectWfBusinessProcessListByProcessId(List<String> ids) { return wfBusinessProcessMapper.selectWfBusinessProcessListByProcessId(ids); } }
281677160/openwrt-package
4,749
luci-app-amlogic/luasrc/view/amlogic/other_upfiles.htm
<style> .NewsTdHeight{ line-height:20px; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="100%" colspan="2"> <p align="center"> <%:After uploading firmware (.img/.img.gz/.img.xz/.7z suffix) or kernel files (3 kernel files), the update button will be displayed.%> </p> </td></tr> <tr><td width="30%" align="right"> <input id="_have_firmware" type="button" class="cbi-button cbi-button-reload" value="<%:Update OpenWrt firmware%>" onclick="return amlogic_update(this, 'auto@updated@/tmp')"/> <input id="_have_kernel" type="button" class="cbi-button cbi-button-reload" value="<%:Replace OpenWrt Kernel%>" onclick="return amlogic_kernel(this)"/> </td><td width="70%" align="left"> <span id="_current_firmware_version"><%:Collecting data...%></span>  <span id="_check_log_firmware"></span><span id="_check_log_kernel"></span> </td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function amlogic_update(btn,amlogic_update_sel) { btn.disabled = true; btn.value = '<%:Updating...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_update")%>', { amlogic_update_sel: amlogic_update_sel }, function(x,status) { if ( x && x.status == 200 ) { if(status.rule_update_status!="0") { btn.value = '<%:Update Failed%>'; } else { btn.value = '<%:Successful Update%>'; } } else { btn.value = '<%:Update OpenWrt firmware%>'; } } ); btn.disabled = false; return false; } function amlogic_kernel(btn) { btn.disabled = true; btn.value = '<%:Updating...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_kernel")%>', null, function(x, status) { if ( x && x.status == 200 ) { if(status.rule_kernel_status!="0") { btn.value = '<%:Update Failed%>'; } else { btn.value = '<%:Successful Update%>'; } } else { btn.value = '<%:Replace OpenWrt Kernel%>'; } } ); btn.disabled = false; return false; } var _have_firmware = document.getElementById('_have_firmware'); var _have_kernel = document.getElementById('_have_kernel'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_upfiles")%>', status.start_check_upfiles, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_upfiles == "firmware\n" || status.start_check_upfiles == "firmware" ) { _have_firmware.style.display = 'block'; } else { _have_firmware.style.display = 'none'; } if ( status.start_check_upfiles == "kernel\n" || status.start_check_upfiles == "kernel" ) { _have_kernel.style.display = 'block'; } else { _have_kernel.style.display = 'none'; } } }); var _check_log_firmware = document.getElementById('_check_log_firmware'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_firmware")%>', status.start_check_firmware, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_firmware != "\n" && status.start_check_firmware != "" ) { _check_log_firmware.innerHTML = '<font color="blue"> '+status.start_check_firmware+'</font>'; } if ( status.start_check_firmware == "\n" || status.start_check_firmware == "" ) { _check_log_firmware.innerHTML = ''; } } }); var _check_log_kernel = document.getElementById('_check_log_kernel'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_kernel")%>', status.start_check_kernel, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_kernel != "\n" && status.start_check_kernel != "" ) { _check_log_kernel.innerHTML = '<font color="blue"> '+status.start_check_kernel+'</font>'; } if ( status.start_check_kernel == "\n" || status.start_check_kernel == "" ) { _check_log_kernel.innerHTML = ''; } } }); var _current_firmware_version = document.getElementById('_current_firmware_version'); //var _current_kernel_version = document.getElementById('_current_kernel_version'); XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "state")%>', null, function(x, status) { if ( x && x.status == 200 ) { _current_firmware_version.innerHTML = status.current_firmware_version ? "<font color=green><%:Current Version%> [ "+status.current_firmware_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; //_current_kernel_version.innerHTML = status.current_kernel_version ? "<font color=green><%:Current Version%> [ "+status.current_kernel_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; } }); //]]></script>
2929004360/ruoyi-sign
31,800
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfModelServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.constant.ProcessConfigConstants; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.domain.*; import com.ruoyi.flowable.domain.bo.WfModelBo; import com.ruoyi.flowable.domain.dto.WfMetaInfoDto; import com.ruoyi.flowable.domain.vo.WfFormVo; import com.ruoyi.flowable.domain.vo.WfModelVo; import com.ruoyi.flowable.enums.FormType; import com.ruoyi.flowable.enums.PermissionEnum; import com.ruoyi.flowable.factory.FlowServiceFactory; import com.ruoyi.flowable.mapper.WfModelMapper; import com.ruoyi.flowable.mapper.WfModelProcdefMapper; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import com.ruoyi.flowable.service.*; import com.ruoyi.flowable.utils.*; import com.ruoyi.system.api.service.ISysDeptServiceApi; import com.ruoyi.system.api.service.ISysUserServiceApi; import lombok.extern.slf4j.Slf4j; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.SequenceFlow; import org.flowable.bpmn.model.StartEvent; import org.flowable.common.engine.impl.db.SuspensionState; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.Model; import org.flowable.engine.repository.ModelQuery; import org.flowable.engine.repository.ProcessDefinition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; /** * @author fengcheng * @createTime 2022/6/21 9:11 */ @Service @Slf4j public class WfModelServiceImpl extends FlowServiceFactory implements IWfModelService { @Lazy @Autowired private IWfFormService formService; @Lazy @Autowired private IWfDeployFormService deployFormService; @Lazy @Autowired private IWfIconService wfIconService; @Lazy @Autowired private IWfModelPermissionService wfModelPermissionService; @Lazy @Autowired private IdWorker idWorker; @Lazy @Autowired private WfModelMapper wfModelMapper; @Lazy @Autowired private ISysUserServiceApi userServiceApi; @Lazy @Autowired private ISysDeptServiceApi deptServiceApi; @Lazy @Autowired private WfModelProcdefMapper wfModelProcdefMapper; @Lazy @Autowired private IWfModelProcdefService wfModelProcdefService; @Lazy @Autowired private IWfModelAssociationTemplateService wfModelAssociationTemplateService; @Lazy @Autowired private WfDeployServiceImpl wfDeployService; @Override public TableDataInfo<WfModelVo> list(WfModelBo modelBo, PageQuery pageQuery) { ModelQuery modelQuery = repositoryService.createModelQuery().latestVersion().orderByCreateTime().desc(); // 构建查询条件 if (StringUtils.isNotBlank(modelBo.getModelKey())) { modelQuery.modelKey(modelBo.getModelKey()); } if (StringUtils.isNotBlank(modelBo.getModelName())) { modelQuery.modelNameLike("%" + modelBo.getModelName() + "%"); } if (StringUtils.isNotBlank(modelBo.getCategory())) { modelQuery.modelCategory(modelBo.getCategory()); } // 执行查询 long pageTotal = modelQuery.count(); if (pageTotal <= 0) { return TableDataInfo.build(); } int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<Model> modelList = modelQuery.listPage(offset, pageQuery.getPageSize()); List<WfModelVo> modelVoList = new ArrayList<>(modelList.size()); modelList.forEach(model -> { WfModelVo modelVo = new WfModelVo(); modelVo.setModelId(model.getId()); modelVo.setModelName(model.getName()); modelVo.setModelKey(model.getKey()); modelVo.setCategory(model.getCategory()); modelVo.setCreateTime(model.getCreateTime()); modelVo.setVersion(model.getVersion()); WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); if (metaInfo != null) { modelVo.setDescription(metaInfo.getDescription()); modelVo.setFormType(metaInfo.getFormType()); modelVo.setFormId(metaInfo.getFormId()); modelVo.setFormName(metaInfo.getFormName()); modelVo.setFormCustomCreatePath(metaInfo.getFormCustomCreatePath()); modelVo.setFormCustomViewPath(metaInfo.getFormCustomViewPath()); modelVo.setIcon(metaInfo.getIcon()); } modelVoList.add(modelVo); }); Page<WfModelVo> page = new Page<>(); page.setRecords(modelVoList); page.setTotal(pageTotal); return TableDataInfo.build(page); } @Override public List<WfModelVo> list(WfModelBo modelBo) { ModelQuery modelQuery = repositoryService.createModelQuery().latestVersion().orderByCreateTime().desc(); // 构建查询条件 if (StringUtils.isNotBlank(modelBo.getModelKey())) { modelQuery.modelKey(modelBo.getModelKey()); } if (StringUtils.isNotBlank(modelBo.getModelName())) { modelQuery.modelNameLike("%" + modelBo.getModelName() + "%"); } if (StringUtils.isNotBlank(modelBo.getCategory())) { modelQuery.modelCategory(modelBo.getCategory()); } List<Model> modelList = modelQuery.list(); List<WfModelVo> modelVoList = new ArrayList<>(modelList.size()); modelList.forEach(model -> { WfModelVo modelVo = new WfModelVo(); modelVo.setModelId(model.getId()); modelVo.setModelName(model.getName()); modelVo.setModelKey(model.getKey()); modelVo.setCategory(model.getCategory()); modelVo.setCreateTime(model.getCreateTime()); modelVo.setVersion(model.getVersion()); WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); if (metaInfo != null) { modelVo.setDescription(metaInfo.getDescription()); modelVo.setFormType(metaInfo.getFormType()); modelVo.setFormId(metaInfo.getFormId()); } modelVoList.add(modelVo); }); return modelVoList; } @Override public TableDataInfo<WfModelVo> historyList(WfModelBo modelBo, PageQuery pageQuery) { ModelQuery modelQuery = repositoryService.createModelQuery().modelKey(modelBo.getModelKey()).orderByModelVersion().desc(); // 执行查询(不显示最新版,-1) long pageTotal = modelQuery.count() - 1; if (pageTotal <= 0) { return TableDataInfo.build(); } // offset+1,去掉最新版 int offset = 1 + pageQuery.getPageSize() * (pageQuery.getPageNum() - 1); List<Model> modelList = modelQuery.listPage(offset, pageQuery.getPageSize()); List<WfModelVo> modelVoList = new ArrayList<>(modelList.size()); modelList.forEach(model -> { WfModelVo modelVo = new WfModelVo(); modelVo.setModelId(model.getId()); modelVo.setModelName(model.getName()); modelVo.setModelKey(model.getKey()); modelVo.setCategory(model.getCategory()); modelVo.setCreateTime(model.getCreateTime()); modelVo.setVersion(model.getVersion()); WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); if (metaInfo != null) { modelVo.setDescription(metaInfo.getDescription()); modelVo.setFormType(metaInfo.getFormType()); modelVo.setFormId(metaInfo.getFormId()); } modelVoList.add(modelVo); }); Page<WfModelVo> page = new Page<>(); page.setRecords(modelVoList); page.setTotal(pageTotal); return TableDataInfo.build(page); } @Override public WfModelVo getModel(String modelId) { // 获取流程模型 Model model = repositoryService.getModel(modelId); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } // 获取流程图 String bpmnXml = queryBpmnXmlById(modelId); WfModelVo modelVo = new WfModelVo(); modelVo.setModelId(model.getId()); modelVo.setModelName(model.getName()); modelVo.setModelKey(model.getKey()); modelVo.setCategory(model.getCategory()); modelVo.setCreateTime(model.getCreateTime()); modelVo.setVersion(model.getVersion()); modelVo.setBpmnXml(bpmnXml); WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); if (metaInfo != null) { modelVo.setDescription(metaInfo.getDescription()); modelVo.setFormType(metaInfo.getFormType()); modelVo.setFormId(metaInfo.getFormId()); modelVo.setFormName(metaInfo.getFormName()); modelVo.setFormCustomCreatePath(metaInfo.getFormCustomCreatePath()); modelVo.setFormCustomViewPath(metaInfo.getFormCustomViewPath()); modelVo.setIcon(metaInfo.getIcon()); modelVo.setMenuId(metaInfo.getMenuId()); modelVo.setMenuName(metaInfo.getMenuName()); modelVo.setProcessConfig(metaInfo.getProcessConfig()); modelVo.setModelTemplateId(metaInfo.getModelTemplateId()); if (FormType.PROCESS.getType().equals(metaInfo.getFormType())) { WfFormVo wfFormVo = formService.queryById(metaInfo.getFormId()); modelVo.setContent(wfFormVo.getContent()); } } WfModelPermission permission = new WfModelPermission(); permission.setModelId(modelId); permission.setType(PermissionEnum.USER_PERMISSION.getCode()); List<Long> permissionIdList = new ArrayList<>(); if (!SecurityUtils.hasRole("admin")) { //获取当前登录用户 SysUser sysUser = SecurityUtils.getLoginUser().getUser(); permissionIdList = userServiceApi.listUserIdByDeptId(sysUser.getDeptId()); } modelVo.setSelectUserList(wfModelPermissionService.selectWfModelPermissionList(permission, permissionIdList)); permission.setType(PermissionEnum.DEPT_PERMISSION.getCode()); if (!SecurityUtils.hasRole("admin")) { //获取当前登录用户 SysUser sysUser = SecurityUtils.getLoginUser().getUser(); List<Long> deptList = deptServiceApi.selectBranchDeptId(sysUser.getDeptId()); deptList.add(sysUser.getDeptId()); permissionIdList = deptList; } modelVo.setSelectDeptList(wfModelPermissionService.selectWfModelPermissionList(permission, permissionIdList)); return modelVo; } @Override public String queryBpmnXmlById(String modelId) { byte[] bpmnBytes = repositoryService.getModelEditorSource(modelId); return StrUtil.utf8Str(bpmnBytes); } /** * 新增模型信息 * * @param modelBo 流程模型对象 * @return 模型id */ @Override @Transactional(rollbackFor = Exception.class) public String insertModel(WfModelBo modelBo) { // 创建一个新的模型对象 Model model = repositoryService.newModel(); // 设置模型名称 model.setName(modelBo.getModelName()); // 设置模型键 model.setKey(modelBo.getModelKey()); // 设置流程分类 model.setCategory(modelBo.getCategory()); // 构建元数据信息 String metaInfo = buildMetaInfo(new WfMetaInfoDto(), modelBo.getDescription(), modelBo.getIcon(), modelBo.getFormType(), modelBo.getFormId(), modelBo.getFormName(), modelBo.getFormCustomCreatePath(), modelBo.getFormCustomViewPath(), modelBo.getMenuId(), modelBo.getMenuName(), modelBo.getProcessConfig(), modelBo.getModelTemplateId() ); // 设置元数据信息 model.setMetaInfo(metaInfo); // 保存流程模型 repositoryService.saveModel(model); checkModel(modelBo, model.getId()); insertWfModelPermissionList(model.getId(), modelBo); if (ProcessConfigConstants.MODEL_TEMPLATE.equals(modelBo.getProcessConfig())) { WfModelAssociationTemplate wfModelAssociationTemplate = new WfModelAssociationTemplate(); wfModelAssociationTemplate.setModelId(model.getId()); wfModelAssociationTemplate.setModelTemplateId(modelBo.getModelTemplateId()); wfModelAssociationTemplateService.insertWfModelAssociationTemplate(wfModelAssociationTemplate); } return model.getId(); } /** * 新增模型权限 * * @param id * @param modelBo */ private void insertWfModelPermissionList(String id, WfModelBo modelBo) { List<WfModelPermission> permissionsList = new ArrayList<>(); List<WfModelPermission> deptList = modelBo.getSelectDeptList(); List<WfModelPermission> userList = modelBo.getSelectUserList(); if (ObjectUtil.isNotNull(deptList) && deptList.size() > 0) { for (WfModelPermission permission : deptList) { permission.setType(PermissionEnum.DEPT_PERMISSION.getCode()); permission.setModelPermissionId(String.valueOf(idWorker.nextId())); permission.setModelId(id); permission.setCreateTime(DateUtils.getNowDate()); } permissionsList.addAll(deptList); } if (ObjectUtil.isNotNull(deptList) && userList.size() > 0) { for (WfModelPermission permission : userList) { permission.setType(PermissionEnum.USER_PERMISSION.getCode()); permission.setModelPermissionId(String.valueOf(idWorker.nextId())); permission.setModelId(id); permission.setCreateTime(DateUtils.getNowDate()); } permissionsList.addAll(userList); } if (permissionsList.size() == 0) { WfModelPermission permission = new WfModelPermission(); permission.setType(PermissionEnum.USER_PERMISSION.getCode()); permission.setModelPermissionId(String.valueOf(idWorker.nextId())); permission.setModelId(id); permission.setPermissionId(SecurityUtils.getUserId()); permission.setName(SecurityUtils.getLoginUser().getUser().getNickName()); permission.setCreateTime(DateUtils.getNowDate()); permissionsList.add(permission); } wfModelPermissionService.insertWfModelPermissionList(permissionsList); } @Override @Transactional(rollbackFor = Exception.class) public void updateModel(WfModelBo modelBo) { // 根据模型Key查询模型信息 Model model = repositoryService.getModel(modelBo.getModelId()); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } model.setCategory(modelBo.getCategory()); WfMetaInfoDto metaInfoDto = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); String metaInfo = buildMetaInfo(metaInfoDto, modelBo.getDescription(), modelBo.getIcon(), modelBo.getFormType(), modelBo.getFormId(), modelBo.getFormName(), modelBo.getFormCustomCreatePath(), modelBo.getFormCustomViewPath(), modelBo.getMenuId(), modelBo.getMenuName(), modelBo.getProcessConfig(), modelBo.getModelTemplateId() ); model.setMetaInfo(metaInfo); // 保存流程模型 repositoryService.saveModel(model); checkModel(modelBo, model.getId()); wfModelPermissionService.deleteWfModelPermissionByModelId(modelBo.getModelId()); insertWfModelPermissionList(modelBo.getModelId(), modelBo); WfModelAssociationTemplate wfModelAssociationTemplate = new WfModelAssociationTemplate(); wfModelAssociationTemplate.setModelId(model.getId()); wfModelAssociationTemplate.setModelTemplateId(modelBo.getModelTemplateId()); wfModelAssociationTemplateService.deleteWfModelAssociationTemplate(wfModelAssociationTemplate); if (ProcessConfigConstants.MODEL_TEMPLATE.equals(modelBo.getProcessConfig())) { wfModelAssociationTemplateService.insertWfModelAssociationTemplate(wfModelAssociationTemplate); } } /** * 校验模型 * * @param modelBo * @param modelId */ private void checkModel(WfModelBo modelBo, String modelId) { if (ObjectUtil.isNull(modelBo.getBpmnXml())) { throw new RuntimeException("请选设计流程模型!"); } BpmnModel bpmnModel = ModelUtils.getBpmnModel(modelBo.getBpmnXml()); if (ObjectUtil.isEmpty(bpmnModel)) { throw new RuntimeException("获取模型设计失败!"); } // 获取开始节点 StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel); if (ObjectUtil.isNull(startEvent)) { throw new RuntimeException("开始节点不存在,请检查流程设计是否有误!"); } if (FormType.PROCESS.getType().equals(modelBo.getFormType())) { // 获取开始节点配置的表单Key if (StrUtil.isBlank(startEvent.getFormKey())) { throw new RuntimeException("请配置流程表单"); } } //查看开始节点的后一个任务节点出口 List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows(); if (Objects.isNull(outgoingFlows)) { throw new RuntimeException("导入失败,流程配置错误!"); } //遍历返回下一个节点信息 // for (SequenceFlow outgoingFlow : outgoingFlows) { // //类型自己判断(获取下个节点是任务节点) // FlowElement targetFlowElement = outgoingFlow.getTargetFlowElement(); // // 下个出口是用户任务,而且是要发起人节点才让保存 // if (targetFlowElement instanceof UserTask) { // if (StringUtils.equals(((UserTask) targetFlowElement).getAssignee(), "${initiator}")) { // break; // } else { // throw new RuntimeException("导入失败,流程第一个用户任务节点必须是发起人节点"); // } // } // } // 保存 BPMN XML Process process = bpmnModel.getProcesses().get(0); if (StringUtils.isEmpty(modelBo.getModelId())) { process.setName(modelBo.getModelName()); process.setId("process_" + idWorker.nextId()); } else { process.setName(modelBo.getModelName()); } repositoryService.addModelEditorSource(modelId, ModelUtils.getBpmnXml(bpmnModel)); } /** * 保存流程模型信息 * * @param modelBo 流程模型对象 */ @Override @Transactional(rollbackFor = Exception.class) public void saveModel(WfModelBo modelBo) { // 查询模型信息 Model model = repositoryService.getModel(modelBo.getModelId()); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } BpmnModel bpmnModel = ModelUtils.getBpmnModel(modelBo.getBpmnXml()); if (ObjectUtil.isEmpty(bpmnModel)) { throw new RuntimeException("获取模型设计失败!"); } // String processName = bpmnModel.getMainProcess().getName(); // 获取开始节点 StartEvent startEvent = ModelUtils.getStartEvent(bpmnModel); if (ObjectUtil.isNull(startEvent)) { throw new RuntimeException("开始节点不存在,请检查流程设计是否有误!"); } // 获取开始节点配置的表单Key if (StrUtil.isBlank(startEvent.getFormKey())) { throw new RuntimeException("请配置流程表单"); } //查看开始节点的后一个任务节点出口 List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows(); if (Objects.isNull(outgoingFlows)) { throw new RuntimeException("导入失败,流程配置错误!"); } // //遍历返回下一个节点信息 // for (SequenceFlow outgoingFlow : outgoingFlows) { // //类型自己判断(获取下个节点是任务节点) // FlowElement targetFlowElement = outgoingFlow.getTargetFlowElement(); // // 下个出口是用户任务,而且是要发起人节点才让保存 // if (targetFlowElement instanceof UserTask) { // if (StringUtils.equals(((UserTask) targetFlowElement).getAssignee(), "${initiator}")) { // break; // } else { // throw new RuntimeException("导入失败,流程第一个用户任务节点必须是发起人节点"); // } // } // } Model newModel; if (Boolean.TRUE.equals(modelBo.getNewVersion())) { newModel = repositoryService.newModel(); newModel.setName(model.getName()); newModel.setKey(model.getKey()); newModel.setCategory(model.getCategory()); newModel.setMetaInfo(model.getMetaInfo()); newModel.setVersion(model.getVersion() + 1); } else { newModel = model; // 设置流程名称 newModel.setName(model.getName()); } // 保存流程模型 repositoryService.saveModel(newModel); // 保存 BPMN XML byte[] bpmnXmlBytes = StringUtils.getBytes(modelBo.getBpmnXml(), StandardCharsets.UTF_8); repositoryService.addModelEditorSource(newModel.getId(), bpmnXmlBytes); } @Override @Transactional(rollbackFor = Exception.class) public void latestModel(String modelId) { // 获取流程模型 Model model = repositoryService.getModel(modelId); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } Integer latestVersion = repositoryService.createModelQuery().modelKey(model.getKey()).latestVersion().singleResult().getVersion(); if (model.getVersion().equals(latestVersion)) { throw new RuntimeException("当前版本已是最新版!"); } // 获取 BPMN XML byte[] bpmnBytes = repositoryService.getModelEditorSource(modelId); Model newModel = repositoryService.newModel(); newModel.setName(model.getName()); newModel.setKey(model.getKey()); newModel.setCategory(model.getCategory()); newModel.setMetaInfo(model.getMetaInfo()); newModel.setVersion(latestVersion + 1); // 保存流程模型 repositoryService.saveModel(newModel); // 保存 BPMN XML repositoryService.addModelEditorSource(newModel.getId(), bpmnBytes); } @Override @Transactional(rollbackFor = Exception.class) public void deleteByIds(Collection<String> ids) { for (String id : ids) { Model model = repositoryService.getModel(id); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } repositoryService.deleteModel(id); // 禁用流程定义 updateProcessDefinitionSuspended(model.getDeploymentId()); // 删除流程模型权限 wfModelPermissionService.deleteWfModelPermissionByModelId(id); // 删除流程部署 WfModelProcdef wfModelProcdef = new WfModelProcdef(); wfModelProcdef.setModelId(id); List<WfModelProcdef> wfModelProcdefs = wfModelProcdefService.selectWfModelProcdefList(wfModelProcdef); for (WfModelProcdef modelProcdef : wfModelProcdefs) { wfDeployService.deleteByIds(Collections.singletonList(modelProcdef.getProcdefId())); } // 删除流程模型关联 wfModelProcdefService.deleteWfModelProcdefByModelId(id); WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); WfModelAssociationTemplate wfModelAssociationTemplate = new WfModelAssociationTemplate(); wfModelAssociationTemplate.setModelId(model.getId()); if (metaInfo != null) { wfModelAssociationTemplate.setModelTemplateId(metaInfo.getModelTemplateId()); } wfModelAssociationTemplateService.deleteWfModelAssociationTemplate(wfModelAssociationTemplate); } } /** * 挂起 deploymentId 对应的流程定义 * <p> * 注意:这里一个 deploymentId 只关联一个流程定义 * * @param deploymentId 流程发布Id */ private void updateProcessDefinitionSuspended(String deploymentId) { if (StrUtil.isEmpty(deploymentId)) { return; } ProcessDefinition oldDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult(); if (oldDefinition == null) { return; } // 挂起 SuspensionState.SUSPENDED.getStateCode(); SuspensionState.SUSPENDED.getStateCode(); // suspendProcessInstances = false,进行中的任务,不进行挂起。 // 原因:只要新的流程不允许发起即可,老流程继续可以执行。 repositoryService.suspendProcessDefinitionById(oldDefinition.getId(), false, null); } @Override @Transactional(rollbackFor = Exception.class) public boolean deployModel(String modelId) { // 获取流程模型 Model model = repositoryService.getModel(modelId); if (ObjectUtil.isNull(model)) { throw new RuntimeException("流程模型不存在!"); } // 获取流程图 byte[] bpmnBytes = repositoryService.getModelEditorSource(modelId); if (ArrayUtil.isEmpty(bpmnBytes)) { throw new RuntimeException("请先设计流程图!"); } String bpmnXml = StringUtils.toEncodedString(bpmnBytes, StandardCharsets.UTF_8); BpmnModel bpmnModel = ModelUtils.getBpmnModel(bpmnXml); String processName = model.getName() + ProcessConstants.SUFFIX; WfMetaInfoDto metaInfo = JsonUtils.parseObject(model.getMetaInfo(), WfMetaInfoDto.class); // 部署流程 Deployment deployment = repositoryService.createDeployment() .name(model.getName()) .key(model.getKey()) .category(model.getCategory()) .addBytes(processName, bpmnBytes) .deploy(); String deploymentId = deployment.getId(); WfIcon wfIcon = new WfIcon(); wfIcon.setDeploymentId(deploymentId); if (metaInfo != null) { wfIcon.setIcon(metaInfo.getIcon()); } wfIconService.insertWfIcon(wfIcon); WfModelProcdef wfModelProcdef = new WfModelProcdef(); wfModelProcdef.setModelId(modelId); wfModelProcdef.setProcdefId(deploymentId); if (metaInfo != null) { wfModelProcdef.setFormType(metaInfo.getFormType()); wfModelProcdef.setFormCreatePath(metaInfo.getFormCustomCreatePath()); wfModelProcdef.setFormViewPath(metaInfo.getFormCustomViewPath()); } wfModelProcdefMapper.insertWfModelProcdef(wfModelProcdef); ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult(); // 修改流程定义的分类,便于搜索流程 repositoryService.setProcessDefinitionCategory(procDef.getId(), model.getCategory()); if (metaInfo != null) { // 保存部署表单 deployFormService.saveInternalDeployForm(deployment.getId(), bpmnModel); } return true; } /** * 查询流程模型列表 * * @param modelBo * @return */ @Override public List<WfModelVo> selectList(WfModelBo modelBo) { List<WfModelVo> list = new ArrayList<>(); List<ActReModel> actReModelList; if (SecurityUtils.hasRole("admin")) { actReModelList = wfModelMapper.selectList(modelBo); } else { SysUser sysUser = SecurityUtils.getLoginUser().getUser(); List<Long> userIdList = userServiceApi.listUserIdByDeptId(sysUser.getDeptId()); List<Long> deptIdList; deptIdList = deptServiceApi.selectBranchDeptId(sysUser.getDeptId()); deptIdList.add(sysUser.getDeptId()); actReModelList = wfModelMapper.selectListVo(modelBo, userIdList, deptIdList); } for (ActReModel actReModel : actReModelList) { JSONObject.parseObject(actReModel.getMetaInfo(), WfMetaInfoDto.class); WfModelVo modelVo = new WfModelVo(); modelVo.setModelId(actReModel.getId()); modelVo.setModelName(actReModel.getName()); modelVo.setModelKey(actReModel.getKey()); modelVo.setCategory(actReModel.getCategory()); modelVo.setCreateTime(actReModel.getCreateTime()); modelVo.setVersion(actReModel.getVersion()); WfMetaInfoDto metaInfo = JsonUtils.parseObject(actReModel.getMetaInfo(), WfMetaInfoDto.class); if (metaInfo != null) { modelVo.setDescription(metaInfo.getDescription()); modelVo.setFormType(metaInfo.getFormType()); modelVo.setFormId(metaInfo.getFormId()); modelVo.setFormName(metaInfo.getFormName()); modelVo.setFormCustomCreatePath(metaInfo.getFormCustomCreatePath()); modelVo.setFormCustomViewPath(metaInfo.getFormCustomViewPath()); modelVo.setIcon(metaInfo.getIcon()); modelVo.setMenuId(metaInfo.getMenuId()); modelVo.setMenuName(metaInfo.getMenuName()); modelVo.setProcessConfig(metaInfo.getProcessConfig()); modelVo.setModelTemplateId(metaInfo.getModelTemplateId()); } list.add(modelVo); } return list; } /** * 根据菜单id查询流程模型列表 * * @param menuId 菜单id * @return */ @Override public List<WfModelVo> getModelByMenuId(String menuId) { List<WfModelVo> wfModelVoList = selectList(new WfModelBo()); return wfModelVoList.stream().filter(modelVo -> menuId.equals(modelVo.getMenuId())).collect(Collectors.toList()); } /** * 构建模型扩展信息 * * @return */ private String buildMetaInfo(WfMetaInfoDto metaInfo, String description, String icon, String formType, String formId, String formName, String formCustomCreatePath, String formCustomViewPath, String menuId, String menuName, String processConfig, String modelTemplateId ) { if (metaInfo == null) { metaInfo = new WfMetaInfoDto(); } // 只有非空,才进行设置,避免更新时的覆盖 if (StrUtil.isNotEmpty(description)) { metaInfo.setDescription(description); } if (Objects.nonNull(formType)) { metaInfo.setFormType(formType); metaInfo.setFormId(formId); metaInfo.setFormName(formName); metaInfo.setFormCustomCreatePath(formCustomCreatePath); metaInfo.setFormCustomViewPath(formCustomViewPath); metaInfo.setIcon(icon); metaInfo.setMenuId(menuId); metaInfo.setMenuName(menuName); metaInfo.setProcessConfig(processConfig); metaInfo.setModelTemplateId(modelTemplateId); } return JsonUtils.toJsonString(metaInfo); } }
281677160/openwrt-package
7,660
luci-app-amlogic/luasrc/view/amlogic/other_check.htm
<style> .NewsTdHeight{ line-height: 20px; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="100%" colspan="2"> <p align="center"> <%:Update plugins first, then update the kernel or firmware. More options can be configured in [Plugin Settings].%> <span id="_openwrt_mainline_version"></span> </p> </td></tr> <tr><td width="35%" align="right"><input type="button" class="cbi-button cbi-button-reload" value="<%:Only update Amlogic Service%>" onclick="return b_check_plugin(this)"/></td><td width="65%" align="left"><span id="_current_plugin_version"><%:Collecting data...%></span> <span id="_check_plugin"></span></td></tr> <tr><td width="35%" align="right"><input type="button" class="cbi-button cbi-button-reload" value="<%:Update system kernel only%>" onclick="return b_check_kernel(this, 'check')"/></td><td width="65%" align="left"><span id="_current_kernel_version"><%:Collecting data...%></span> <span id="_check_kernel"></span></td></tr> <tr><td width="35%" align="right"><input type="button" class="cbi-button cbi-button-reload" value="<%:Complete system update%>" onclick="return b_check_firmware(this, 'check')"/></td><td width="65%" align="left"><span id="_current_firmware_version"><%:Collecting data...%></span> <span id="_check_firmware"></span></td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function amlogic_update(btn,amlogic_update_sel) { btn.disabled = true; btn.value = '<%:Updating...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_update")%>', { amlogic_update_sel: amlogic_update_sel }, function(x,status) { if ( x && x.status == 200 ) { if(status.rule_update_status!="0") { btn.value = '<%:Update Failed%>'; } else { btn.value = '<%:Successful Update%>'; } } else { btn.value = '<%:Update%>'; } } ); btn.disabled = false; return false; } function amlogic_kernel(btn) { btn.disabled = true; btn.value = '<%:Updating...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_kernel")%>', null, function(x, status) { if ( x && x.status == 200 ) { if(status.rule_kernel_status!="0") { btn.value = '<%:Update Failed%>'; } else { btn.value = '<%:Successful Update%>'; } } else { btn.value = '<%:Update%>'; } } ); btn.disabled = false; return false; } function amlogic_plugin(btn) { btn.disabled = true; btn.value = '<%:Updating...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_plugin")%>', null, function(x, status) { if ( x && x.status == 200 ) { if(status.rule_plugin_status!="0") { btn.value = '<%:Update Failed%>'; } else { btn.value = '<%:Successful Update%>'; } } else { btn.value = '<%:Update%>'; } } ); btn.disabled = false; return false; } function b_check_firmware(btn,firmware_options) { btn.disabled = true; btn.value = '<%:Checking...%>'; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "check_firmware")%>', { firmware_options: firmware_options }, function(x,status) { if ( x && x.status == 200 ) { if(status.check_firmware_status!="0") { btn.value = '<%:Complete system update%>'; } else { btn.value = '<%:Complete system update%>'; } } else { btn.value = '<%:Complete system update%>'; } } ); btn.disabled = false; return false; } function b_check_plugin(btn) { btn.disabled = true; btn.value = '<%:Checking...%>'; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "check_plugin")%>', null, function(x, status) { if ( x && x.status == 200 ) { btn.disabled = false; btn.value = '<%:Only update Amlogic Service%>'; } else { btn.disabled = false; btn.value = '<%:Only update Amlogic Service%>'; } return false; }); } function b_check_kernel(btn,kernel_options) { btn.disabled = true; btn.value = '<%:Checking...%>'; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "check_kernel")%>', { kernel_options: kernel_options }, function(x,status) { if ( x && x.status == 200 ) { if(status.check_kernel_status!="0") { btn.value = '<%:Update system kernel only%>'; } else { btn.value = '<%:Update system kernel only%>'; } } else { btn.value = '<%:Update system kernel only%>'; } } ); btn.disabled = false; return false; } var _check_firmware = document.getElementById('_check_firmware'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_firmware")%>', status.start_check_firmware, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_firmware != "\n" && status.start_check_firmware != "" ) { _check_firmware.innerHTML = '<font color="blue"> '+status.start_check_firmware+'</font>'; } if ( status.start_check_firmware == "\n" || status.start_check_firmware == "" ) { _check_firmware.innerHTML = ''; } } }); var _check_plugin = document.getElementById('_check_plugin'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_plugin")%>', status.start_check_plugin, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_plugin != "\n" && status.start_check_plugin != "" ) { _check_plugin.innerHTML = '<font color="blue"> '+status.start_check_plugin+'</font>'; } if ( status.start_check_plugin == "\n" || status.start_check_plugin == "" ) { _check_plugin.innerHTML = ''; } } }); var _check_kernel = document.getElementById('_check_kernel'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_kernel")%>', status.start_check_kernel, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_kernel != "\n" && status.start_check_kernel != "" ) { _check_kernel.innerHTML = '<font color="blue"> '+status.start_check_kernel+'</font>'; } if ( status.start_check_kernel == "\n" || status.start_check_kernel == "" ) { _check_kernel.innerHTML = ''; } } }); var _current_firmware_version = document.getElementById('_current_firmware_version'); var _current_plugin_version = document.getElementById('_current_plugin_version'); var _current_kernel_version = document.getElementById('_current_kernel_version'); var _openwrt_mainline_version = document.getElementById('_openwrt_mainline_version'); XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "state")%>', null, function(x, status) { if ( x && x.status == 200 ) { _current_firmware_version.innerHTML = status.current_firmware_version ? "<font color=green><%:Current Version%> [ "+status.current_firmware_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; _current_plugin_version.innerHTML = status.current_plugin_version ? "<font color=green><%:Current Version%> [ "+status.current_plugin_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; _current_kernel_version.innerHTML = status.current_kernel_version ? "<font color=green><%:Current Version%> [ "+status.current_kernel_version+" ] </font>" : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; _openwrt_mainline_version.innerHTML = status.current_kernel_branch ? " [ "+status.current_kernel_branch+".y ] " : "[ "+"<%:Invalid value.%>"+" ]"; } }); //]]></script>
281677160/openwrt-package
1,764
luci-app-amlogic/luasrc/view/amlogic/other_poweroff.htm
<style> .NewsTdHeight{ line-height:32px; } .imgLeft{ float:left; margin-right:10px; vertical-align:middle; } .contentRight{ align-items: center; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="100%" align="left"> <input class="cbi-button cbi-button-remove" type="button" value="<%:Perform PowerOff%>" onclick="poweroff(this)" /> <p style="display:none"> <img id="img_loading" style="display:block" src="<%=resource%>/amlogic/loading.gif" alt="<%:Loading%>" class="imgLeft" /> <img id="img_poweroff" style="display:none" src="<%=resource%>/amlogic/poweroff.png" alt="<%:PowerOff%>" class="imgLeft" /> <span id="msg_poweroff" class="contentRight"><%:Device is shutting down...%></span> </p> </td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function status_check() { var time = 5; var img_loading = document.getElementById("img_loading"); var img_poweroff = document.getElementById("img_poweroff"); var msg = document.getElementById("msg_poweroff"); var set = setInterval(function() { time--; msg.innerHTML = "<%:Waiting for the device to shut down...%>"; if(time === 0) { img_loading.style.display = 'none'; img_poweroff.style.display = 'block'; msg.innerHTML = "<%:The device has been turned off%>"; clearInterval(set); } }, 1000); } function poweroff(btn) { if (confirm('<%:Are you sure you want to shut down?%>') != true) { return false; } btn.style.display = 'none'; document.getElementById('msg_poweroff').parentNode.style.display = 'block'; (new XHR()).post('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_poweroff")%>', { token: '<%=token%>' }, status_check); } //]]></script>
2929004360/ruoyi-sign
68,555
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/impl/WfTaskServiceImpl.java
package com.ruoyi.flowable.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.google.common.collect.Lists; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.enums.FlowMenuEnum; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.constant.TaskConstants; import com.ruoyi.flowable.domain.msg.MessageSendWhenTaskCreatedReq; import com.ruoyi.flowable.domain.vo.WfUserTaskVo; import com.ruoyi.flowable.enums.FlowComment; import com.ruoyi.flowable.factory.FlowServiceFactory; import com.ruoyi.flowable.flow.CustomProcessDiagramGenerator; import com.ruoyi.flowable.flow.FlowableUtils; import com.ruoyi.flowable.handler.BusinessFormDataHandler; import com.ruoyi.flowable.mapper.FlowTaskMapper; import com.ruoyi.flowable.service.IWfCopyService; import com.ruoyi.flowable.service.IWfTaskService; import com.ruoyi.flowable.subscription.ApprovalResultTemplate; import com.ruoyi.flowable.subscription.PendingApprovalTemplate; import com.ruoyi.flowable.utils.*; import com.ruoyi.system.api.service.ISysConfigServiceApi; import com.ruoyi.system.api.service.ISysUserServiceApi; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; import org.apache.commons.collections4.CollectionUtils; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.bpmn.model.Process; import org.flowable.bpmn.model.*; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.FlowableObjectNotFoundException; import org.flowable.common.engine.impl.identity.Authentication; import org.flowable.engine.ProcessEngineConfiguration; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior; import org.flowable.engine.impl.bpmn.behavior.SequentialMultiInstanceBehavior; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ChangeActivityStateBuilder; import org.flowable.engine.runtime.Execution; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.identitylink.api.IdentityLink; import org.flowable.identitylink.api.IdentityLinkType; import org.flowable.image.ProcessDiagramGenerator; import org.flowable.task.api.DelegationState; import org.flowable.task.api.Task; import org.flowable.task.api.history.HistoricTaskInstance; import org.flowable.task.service.impl.persistence.entity.TaskEntity; import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * @author fengcheng */ @RequiredArgsConstructor @Service @Slf4j @Transactional(rollbackFor = Exception.class) public class WfTaskServiceImpl extends FlowServiceFactory implements IWfTaskService { private final ISysUserServiceApi userServiceApi; private final IWfCopyService copyService; private final FlowTaskMapper flowTaskMapper; private final BusinessFormDataHandler businessFormDataHandler; private final PendingApprovalTemplate pendingApprovalTemplate; private final ApprovalResultTemplate approvalResultTemplate; private final ISysUserServiceApi sysUserServiceApi; private final ISysConfigServiceApi sysConfigServiceApi; /** * 完成任务 * * @param taskBo 请求实体参数 */ @Transactional(rollbackFor = Exception.class) @Override public void complete(WfTaskBo taskBo) { Task task = taskService.createTaskQuery().taskId(taskBo.getTaskId()).singleResult(); TaskEntity taskEntity = (TaskEntity) taskService.createTaskQuery().taskId(taskBo.getTaskId()).singleResult(); if (Objects.isNull(task)) { throw new ServiceException("任务不存在"); } // 获取 bpmn 模型 BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId()); if (DelegationState.PENDING.equals(task.getDelegationState())) { if (ObjectUtil.isNotNull(taskBo.getParentTaskId()) && !StrUtil.isEmpty(taskBo.getParentTaskId())) { taskService.addComment(taskBo.getParentTaskId(), taskBo.getProcInsId(), FlowComment.DELEGATE.getType(), SecurityUtils.getLoginUser().getUser().getNickName() + "在[" + task.getName() + "]节点加签委派原因:" + taskBo.getComment()); } else { taskService.addComment(taskBo.getTaskId(), taskBo.getProcInsId(), FlowComment.DELEGATE.getType(), taskBo.getComment()); } taskService.resolveTask(taskBo.getTaskId()); } else { if (ObjectUtil.isNotNull(taskBo.getParentTaskId()) && !StrUtil.isEmpty(taskBo.getParentTaskId())) { taskService.addComment(taskBo.getParentTaskId(), taskBo.getProcInsId(), FlowComment.NORMAL.getType(), SecurityUtils.getLoginUser().getUser().getNickName() + "在[" + task.getName() + "]节点加签审批通过原因:" + taskBo.getComment()); } else { taskService.addComment(taskBo.getTaskId(), taskBo.getProcInsId(), FlowComment.NORMAL.getType(), taskBo.getComment()); } taskService.setAssignee(taskBo.getTaskId(), String.valueOf(SecurityUtils.getUserId())); if (ObjectUtil.isNotEmpty(taskBo.getVariables())) { // 获取模型信息 String localScopeValue = ModelUtils.getUserTaskAttributeValue(bpmnModel, task.getTaskDefinitionKey(), ProcessConstants.PROCESS_FORM_LOCAL_SCOPE); boolean localScope = Convert.toBool(localScopeValue, false); taskService.complete(taskBo.getTaskId(), taskBo.getVariables(), localScope); String key = sysConfigServiceApi.selectConfigByKey("sys.wechat.notice"); if (Boolean.parseBoolean(key)) { // 发送微信通知 sendingCompleteWxNotice(taskEntity, taskBo); } } else { taskService.complete(taskBo.getTaskId()); String key = sysConfigServiceApi.selectConfigByKey("sys.wechat.notice"); if (Boolean.parseBoolean(key)) { // 发送微信通知 sendingCompleteWxNotice(taskEntity, taskBo); } } } // 设置任务节点名称 taskBo.setTaskName(task.getName()); // 处理下一级接收人 if (ObjectUtil.isNotEmpty(taskBo.getNextApproval())) { this.assignNextApproval(bpmnModel, taskBo.getProcInsId(), taskBo.getNextApproval()); } // 处理下一级审批人 if (StringUtils.isNotBlank(taskBo.getNextUserIds())) { this.assignNextUsers(bpmnModel, taskBo.getProcInsId(), taskBo.getNextUserIds()); } //加签处理 addSignForComplete(taskBo, taskEntity); // 处理抄送用户 if (!copyService.makeCopy(taskBo)) { throw new RuntimeException("抄送任务失败"); } // 获取流程实例 HistoricProcessInstance historicProcIns = historyService.createHistoricProcessInstanceQuery().processInstanceId(taskBo.getProcInsId()).includeProcessVariables().singleResult(); // 处理业务表单数据 businessFormDataHandler.setDataHandle(taskBo, historicProcIns); } /** * 发送审批完成微信通知 * * @param taskEntity * @param taskBo */ private void sendingCompleteWxNotice(TaskEntity taskEntity, WfTaskBo taskBo) { String procInsId = taskEntity.getProcessInstanceId(); HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).singleResult(); SysUser startUser = userServiceApi.selectUserById(Long.valueOf(historicProcessInstance.getStartUserId())); String approvalResult = "已通过"; String approver = SecurityUtils.getLoginUser().getUser().getNickName(); HashMap<String, Object> map = (HashMap<String, Object>) taskEntity.getOriginalPersistentState(); String name = map.get("name").toString(); String comment = taskBo.getComment(); String approvalTime = DateUtils.getTime(); try { approvalResultTemplate.sending(startUser.getOpenid(), approver, approvalResult, comment, approvalTime, "审批节点:" + name); } catch (WxErrorException e) { System.out.println(e.getMessage()); } } /** * 指派下一任务接收人 * * @param bpmnModel bpmn模型 * @param processInsId 流程实例id * @param userIds 用户ids 这个实际上换成userNames了 */ private void assignNextApproval(BpmnModel bpmnModel, String processInsId, String userIds) { // 获取所有节点信息 List<Task> list = taskService.createTaskQuery().processInstanceId(processInsId).list(); if (list.size() == 0) { return; } Queue<String> assignIds = CollUtil.newLinkedList(userIds.split(",")); if (list.size() == assignIds.size()) { for (Task task : list) { taskService.setAssignee(task.getId(), assignIds.poll()); } return; } } /** * 流程审批处理加签任务 * * @param taskVo * @param taskEntity */ void addSignForComplete(WfTaskBo taskVo, TaskEntity taskEntity) { //查看当前任务是存在 if (taskEntity == null) { throw new FlowableException("该任务id对应任务不存在!"); } //处理加签父任务 String parentTaskId = taskEntity.getParentTaskId(); if (StringUtils.isNotBlank(parentTaskId)) { int subTaskCount = flowTaskMapper.querySubTaskByParentTaskId(parentTaskId); //如果没有其他子任务 if (subTaskCount == 0) { Task task = processEngine.getTaskService().createTaskQuery().taskId(parentTaskId).singleResult(); //处理前后加签的任务 processEngine.getTaskService().resolveTask(parentTaskId); if ("after".equals(task.getScopeType())) { processEngine.getTaskService().complete(parentTaskId); } } } } /** * 驳回任务 * * @param taskBo */ @Override @Transactional(rollbackFor = Exception.class) public void taskReject(WfTaskBo taskBo) { // 当前任务 task Task task = taskService.createTaskQuery().taskId(taskBo.getTaskId()).singleResult(); if (ObjectUtil.isNull(task)) { throw new RuntimeException("获取任务信息异常!"); } if (task.isSuspended()) { throw new RuntimeException("任务处于挂起状态"); } // 获取流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(taskBo.getProcInsId()).singleResult(); if (processInstance == null) { throw new RuntimeException("流程实例不存在,请确认!"); } // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); // 获取所有节点信息 Process process = repositoryService.getBpmnModel(processDefinition.getId()).getProcesses().get(0); // 获取全部节点列表,包含子节点 Collection<FlowElement> allElements = FlowableUtils.getAllElements(process.getFlowElements(), null); // 获取当前任务节点元素 FlowElement source = null; if (allElements != null) { for (FlowElement flowElement : allElements) { // 类型为用户节点 if (flowElement.getId().equals(task.getTaskDefinitionKey())) { // 获取节点信息 source = flowElement; } } } // 目的获取所有跳转到的节点 targetIds // 获取当前节点的所有父级用户任务节点 // 深度优先算法思想:延边迭代深入 List<UserTask> parentUserTaskList = FlowableUtils.iteratorFindParentUserTasks(source, null, null); if (parentUserTaskList == null || parentUserTaskList.size() == 0) { throw new RuntimeException("当前节点为初始任务节点,不能驳回"); } // 获取活动 ID 即节点 Key List<String> parentUserTaskKeyList = new ArrayList<>(); parentUserTaskList.forEach(item -> parentUserTaskKeyList.add(item.getId())); // 获取全部历史节点活动实例,即已经走过的节点历史,数据采用开始时间升序 List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery().processInstanceId(task.getProcessInstanceId()).orderByHistoricTaskInstanceStartTime().asc().list(); // 数据清洗,将回滚导致的脏数据清洗掉 List<String> lastHistoricTaskInstanceList = null; if (allElements != null) { lastHistoricTaskInstanceList = FlowableUtils.historicTaskInstanceClean(allElements, historicTaskInstanceList); } // 此时历史任务实例为倒序,获取最后走的节点 List<String> targetIds = new ArrayList<>(); // 循环结束标识,遇到当前目标节点的次数 int number = 0; StringBuilder parentHistoricTaskKey = new StringBuilder(); for (String historicTaskInstanceKey : lastHistoricTaskInstanceList) { // 当会签时候会出现特殊的,连续都是同一个节点历史数据的情况,这种时候跳过 if (parentHistoricTaskKey.toString().equals(historicTaskInstanceKey)) { continue; } parentHistoricTaskKey = new StringBuilder(historicTaskInstanceKey); if (historicTaskInstanceKey.equals(task.getTaskDefinitionKey())) { number++; } // 在数据清洗后,历史节点就是唯一一条从起始到当前节点的历史记录,理论上每个点只会出现一次 // 在流程中如果出现循环,那么每次循环中间的点也只会出现一次,再出现就是下次循环 // number == 1,第一次遇到当前节点 // number == 2,第二次遇到,代表最后一次的循环范围 if (number == 2) { break; } // 如果当前历史节点,属于父级的节点,说明最后一次经过了这个点,需要退回这个点 if (parentUserTaskKeyList.contains(historicTaskInstanceKey)) { targetIds.add(historicTaskInstanceKey); } } // 目的获取所有需要被跳转的节点 currentIds // 取其中一个父级任务,因为后续要么存在公共网关,要么就是串行公共线路 UserTask oneUserTask = parentUserTaskList.get(0); // 获取所有正常进行的任务节点 Key,这些任务不能直接使用,需要找出其中需要驳回的任务 List<Task> runTaskList = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).list(); List<String> runTaskKeyList = new ArrayList<>(); runTaskList.forEach(item -> runTaskKeyList.add(item.getTaskDefinitionKey())); // 需驳回任务列表 List<String> currentIds = new ArrayList<>(); // 通过父级网关的出口连线,结合 runTaskList 比对,获取需要驳回的任务 List<UserTask> currentUserTaskList = FlowableUtils.iteratorFindChildUserTasks(oneUserTask, runTaskKeyList, null, null); currentUserTaskList.forEach(item -> currentIds.add(item.getId())); // 规定:并行网关之前节点必须需存在唯一用户任务节点,如果出现多个任务节点,则并行网关节点默认为结束节点,原因为不考虑多对多情况 if (targetIds.size() > 1 && currentIds.size() > 1) { throw new RuntimeException("任务出现多对多情况,无法驳回"); } // 循环获取那些需要被撤回的节点的ID,用来设置驳回原因 List<String> currentTaskIds = new ArrayList<>(); currentIds.forEach(currentId -> runTaskList.forEach(runTask -> { if (currentId.equals(runTask.getTaskDefinitionKey())) { currentTaskIds.add(runTask.getId()); } })); // 设置驳回意见 currentTaskIds.forEach(item -> { if (ObjectUtil.isNotNull(taskBo.getParentTaskId())) { taskService.addComment(taskBo.getParentTaskId(), task.getProcessInstanceId(), FlowComment.REJECT.getType(), taskBo.getComment()); } else { taskService.addComment(item, task.getProcessInstanceId(), FlowComment.REJECT.getType(), taskBo.getComment()); } }); try { // 设置处理人 taskService.setAssignee(task.getId(), TaskUtils.getUserId()); // 如果父级任务多于 1 个,说明当前节点不是并行节点,原因为不考虑多对多情况 if (targetIds.size() > 1) { // 1 对 多任务跳转,currentIds 当前节点(1),targetIds 跳转到的节点(多) runtimeService.createChangeActivityStateBuilder().processInstanceId(task.getProcessInstanceId()).moveSingleActivityIdToActivityIds(currentIds.get(0), targetIds).changeState(); } // 如果父级任务只有一个,因此当前任务可能为网关中的任务 if (targetIds.size() == 1) { // 1 对 1 或 多 对 1 情况,currentIds 当前要跳转的节点列表(1或多),targetIds.get(0) 跳转到的节点(1) runtimeService.createChangeActivityStateBuilder().processInstanceId(task.getProcessInstanceId()).moveActivityIdsToSingleActivityId(currentIds, targetIds.get(0)).changeState(); } //驳回到目标节点 List<Task> listTask = taskService.createTaskQuery().processInstanceId(taskBo.getProcInsId()).active().list(); if (listTask.size() == 1) { Task targetTask = listTask.get(0); FlowElement targetElement = null; if (allElements != null) { for (FlowElement flowElement : allElements) { // 类型为用户节点 if (flowElement.getId().equals(targetTask.getTaskDefinitionKey())) { // 获取节点信息 targetElement = flowElement; } } } // 流程发起人 String startUserId = processInstance.getStartUserId(); if (targetElement != null) { UserTask targetUserTask = (UserTask) targetElement; if (targetUserTask.getAssignee() != null && StrUtil.equals(targetUserTask.getAssignee().toString(), "${INITIATOR}")) {//是否为发起人节点 //开始节点 设置处理人为申请人 taskService.setAssignee(targetTask.getId(), startUserId); } else { List<SysUser> sysUserFromTask = getUserFromTask(targetUserTask, startUserId); List<Long> collectUserIdList = sysUserFromTask.stream().filter(Objects::nonNull).map(SysUser::getUserId).filter(Objects::nonNull).collect(Collectors.toList()); //collect_username转换成realname List<String> newusername = new ArrayList<String>(); for (Long oldUser : collectUserIdList) { SysUser sysUser = userServiceApi.selectUserById(oldUser); newusername.add(sysUser.getNickName()); } // 删除后重写 for (Long oldUser : collectUserIdList) { taskService.deleteCandidateUser(targetTask.getId(), String.valueOf(oldUser)); } for (Long oldUser : collectUserIdList) { taskService.addCandidateUser(targetTask.getId(), String.valueOf(oldUser)); } if (collectUserIdList.size() == 1) { targetTask.setAssignee(newusername.get(0).toString()); taskService.addUserIdentityLink(targetTask.getId(), collectUserIdList.get(0).toString(), IdentityLinkType.ASSIGNEE); } else if (collectUserIdList.size() > 1) { List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().activityId(targetTask.getTaskDefinitionKey()).orderByHistoricActivityInstanceStartTime().desc().list(); for (HistoricActivityInstance historicActivityInstance : list) { if (StrUtil.isNotBlank(historicActivityInstance.getAssignee())) { targetTask.setAssignee(historicActivityInstance.getAssignee()); taskService.addUserIdentityLink(targetTask.getId(), historicActivityInstance.getAssignee(), IdentityLinkType.ASSIGNEE); break; } } } } } } else if (listTask.size() > 1) {//多任务 String startUserId = processInstance.getStartUserId(); String definitionld = runtimeService.createProcessInstanceQuery().processInstanceId(listTask.get(0).getProcessInstanceId()).singleResult().getProcessDefinitionId(); //获取bpm(模型)对象 BpmnModel bpmnModel = repositoryService.getBpmnModel(definitionld); //通过节点定义key获取当前节点 FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(listTask.get(0).getTaskDefinitionKey()); if (Objects.nonNull(flowNode)) { if (flowNode instanceof UserTask) {//当前节点是用户任务 UserTask userTask = (UserTask) flowNode; MultiInstanceLoopCharacteristics multiInstance = userTask.getLoopCharacteristics(); if (Objects.nonNull(multiInstance) && !multiInstance.isSequential()) {//当前节点是会签而且是并发的话 List<SysUser> sysUserFromTask = getUserFromTask(userTask, startUserId); List<Long> userlist = sysUserFromTask.stream().filter(Objects::nonNull).filter(item -> item.getUserId() != null).map(SysUser::getUserId).collect(Collectors.toList()); int i = 0; for (Task nexttask : listTask) { String assignee = userlist.get(i).toString(); taskService.setAssignee(nexttask.getId(), assignee); i++; } } } } } } catch (FlowableObjectNotFoundException e) { throw new RuntimeException("未找到流程实例,流程可能已发生变化"); } catch (FlowableException e) { throw new RuntimeException("无法取消或开始活动"); } } public List<SysUser> getUserFromTask(UserTask userTask, String startUserId) { String assignee = userTask.getAssignee(); if (StrUtil.isNotBlank(assignee) && !Objects.equals(assignee, "null") && !Objects.equals(assignee, "${assignee}")) { // 指定单人 if (StringUtils.equalsAnyIgnoreCase(assignee, "${INITIATOR}")) {//对发起人做特殊处理 SysUser sysUser = new SysUser(); sysUser.setUserId(Long.valueOf(startUserId)); return Lists.newArrayList(sysUser); } else { SysUser userByUsername = userServiceApi.selectUserById(Long.parseLong(assignee)); return Lists.newArrayList(userByUsername); } } List<String> candidateUsers = userTask.getCandidateUsers(); if (CollUtil.isNotEmpty(candidateUsers)) { // 指定多人 List<SysUser> list = userServiceApi.getAllUser(); return list.stream().filter(o -> candidateUsers.contains(String.valueOf(o.getUserId()))).collect(Collectors.toList()); } List<String> candidateGroups = userTask.getCandidateGroups(); if (CollUtil.isNotEmpty(candidateGroups)) { // 指定多组 List<SysUser> userList = Lists.newArrayList(); for (String candidateGroup : candidateGroups) { List<SysUser> usersByRoleId = userServiceApi.getUserListByRoleId(candidateGroup); userList.addAll(usersByRoleId); } return userList; } return Lists.newArrayList(); } /** * 退回任务 * * @param bo 请求实体参数 */ @Transactional(rollbackFor = Exception.class) @Override public void taskReturn(WfTaskBo bo) { // 当前任务 task Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); if (ObjectUtil.isNull(task)) { throw new RuntimeException("获取任务信息异常!"); } if (task.isSuspended()) { throw new RuntimeException("任务处于挂起状态"); } // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); // 获取流程模型信息 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); // 获取当前任务节点元素 FlowElement source = ModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey()); // 获取跳转的节点元素 FlowElement target = ModelUtils.getFlowElementById(bpmnModel, bo.getTargetKey()); // 从当前节点向前扫描,判断当前节点与目标节点是否属于串行,若目标节点是在并行网关上或非同一路线上,不可跳转 boolean isSequential = ModelUtils.isSequentialReachable(source, target, new HashSet<>()); if (!isSequential) { throw new RuntimeException("当前节点相对于目标节点,不属于串行关系,无法回退"); } // 获取所有正常进行的任务节点 Key,这些任务不能直接使用,需要找出其中需要撤回的任务 List<Task> runTaskList = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).list(); List<String> runTaskKeyList = new ArrayList<>(); runTaskList.forEach(item -> runTaskKeyList.add(item.getTaskDefinitionKey())); // 需退回任务列表 List<String> currentIds = new ArrayList<>(); // 通过父级网关的出口连线,结合 runTaskList 比对,获取需要撤回的任务 List<UserTask> currentUserTaskList = FlowableUtils.iteratorFindChildUserTasks(target, runTaskKeyList, null, null); currentUserTaskList.forEach(item -> currentIds.add(item.getId())); // 循环获取那些需要被撤回的节点的ID,用来设置驳回原因 List<String> currentTaskIds = new ArrayList<>(); currentIds.forEach(currentId -> runTaskList.forEach(runTask -> { if (currentId.equals(runTask.getTaskDefinitionKey())) { currentTaskIds.add(runTask.getId()); } })); identityService.setAuthenticatedUserId(TaskUtils.getUserId()); // 设置回退意见 for (String currentTaskId : currentTaskIds) { if (ObjectUtil.isNotNull(bo.getParentTaskId())) { taskService.addComment(bo.getParentTaskId(), task.getProcessInstanceId(), FlowComment.REBACK.getType(), bo.getComment()); } else { taskService.addComment(currentTaskId, task.getProcessInstanceId(), FlowComment.REBACK.getType(), bo.getComment()); } } try { // 1 对 1 或 多 对 1 情况,currentIds 当前要跳转的节点列表(1或多),targetKey 跳转到的节点(1) runtimeService.createChangeActivityStateBuilder().processInstanceId(task.getProcessInstanceId()).moveActivityIdsToSingleActivityId(currentIds, bo.getTargetKey()).changeState(); } catch (FlowableObjectNotFoundException e) { throw new RuntimeException("未找到流程实例,流程可能已发生变化"); } catch (FlowableException e) { throw new RuntimeException("无法取消或开始活动"); } // 设置任务节点名称 bo.setTaskName(task.getName()); // 处理抄送用户 if (!copyService.makeCopy(bo)) { throw new RuntimeException("抄送任务失败"); } } /** * 获取所有可回退的节点 * * @param bo * @return */ @Override public List<FlowElement> findReturnTaskList(WfTaskBo bo) { // 当前任务 task Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); // 获取流程模型信息 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); // 查询历史节点实例 List<HistoricActivityInstance> activityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(task.getProcessInstanceId()).activityType(BpmnXMLConstants.ELEMENT_TASK_USER).finished().orderByHistoricActivityInstanceEndTime().asc().list(); List<String> activityIdList = activityInstanceList.stream().map(HistoricActivityInstance::getActivityId).filter(activityId -> !StringUtils.equals(activityId, task.getTaskDefinitionKey())).distinct().collect(Collectors.toList()); // 获取当前任务节点元素 FlowElement source = ModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey()); List<FlowElement> elementList = new ArrayList<>(); for (String activityId : activityIdList) { FlowElement target = ModelUtils.getFlowElementById(bpmnModel, activityId); boolean isSequential = ModelUtils.isSequentialReachable(source, target, new HashSet<>()); if (isSequential) { elementList.add(target); } } return elementList; } /** * 删除任务 * * @param bo 请求实体参数 */ @Override public void deleteTask(WfTaskBo bo) { // todo 待确认删除任务是物理删除任务 还是逻辑删除,让这个任务直接通过? identityService.setAuthenticatedUserId(TaskUtils.getUserId()); taskService.deleteTask(bo.getTaskId(), bo.getComment()); } /** * 认领/签收任务 * * @param taskBo 请求实体参数 */ @Override @Transactional(rollbackFor = Exception.class) public void claim(WfTaskBo taskBo) { Task task = taskService.createTaskQuery().taskId(taskBo.getTaskId()).singleResult(); if (Objects.isNull(task)) { throw new ServiceException("任务不存在"); } taskService.claim(taskBo.getTaskId(), TaskUtils.getUserId()); } /** * 取消认领/签收任务 * * @param bo 请求实体参数 */ @Override @Transactional(rollbackFor = Exception.class) public void unClaim(WfTaskBo bo) { taskService.unclaim(bo.getTaskId()); } /** * 委派任务 * * @param bo 请求实体参数 */ @Override @Transactional(rollbackFor = Exception.class) public void delegateTask(WfTaskBo bo) { // 当前任务 task Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); if (ObjectUtil.isEmpty(task)) { throw new ServiceException("获取任务失败!"); } StringBuilder commentBuilder = new StringBuilder(SecurityUtils.getLoginUser().getUser().getNickName()).append("->"); SysUser sysUser = userServiceApi.selectUserById(Long.parseLong(bo.getUserId())); String nickName = sysUser.getNickName(); if (StringUtils.isNotBlank(nickName)) { commentBuilder.append(nickName); } else { commentBuilder.append(bo.getUserId()); } if (StringUtils.isNotBlank(bo.getComment())) { commentBuilder.append(": ").append(bo.getComment()); } identityService.setAuthenticatedUserId(TaskUtils.getUserId()); // 添加审批意见 if (ObjectUtil.isNotNull(bo.getParentTaskId())) { taskService.addComment(bo.getParentTaskId(), task.getProcessInstanceId(), FlowComment.DELEGATE.getType(), commentBuilder.toString()); } else { taskService.addComment(bo.getTaskId(), task.getProcessInstanceId(), FlowComment.DELEGATE.getType(), commentBuilder.toString()); } // 设置办理人为当前登录人 taskService.setOwner(bo.getTaskId(), TaskUtils.getUserId()); // 执行委派 taskService.delegateTask(bo.getTaskId(), bo.getUserId()); // 设置任务节点名称 bo.setTaskName(task.getName()); // 处理抄送用户 if (!copyService.makeCopy(bo)) { throw new RuntimeException("抄送任务失败"); } } /** * 转办任务 * * @param bo 请求实体参数 */ @Override @Transactional(rollbackFor = Exception.class) public void transferTask(WfTaskBo bo) { // 当前任务 task Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); if (ObjectUtil.isEmpty(task)) { throw new ServiceException("获取任务失败!"); } StringBuilder commentBuilder = new StringBuilder(SecurityUtils.getLoginUser().getUser().getNickName()).append("->"); SysUser sysUser = userServiceApi.selectUserById(Long.parseLong(bo.getUserId())); String nickName = sysUser.getNickName(); if (StringUtils.isNotBlank(nickName)) { commentBuilder.append(nickName); } else { commentBuilder.append(bo.getUserId()); } if (StringUtils.isNotBlank(bo.getComment())) { commentBuilder.append(": ").append(bo.getComment()); } identityService.setAuthenticatedUserId(TaskUtils.getUserId()); // 添加审批意见 if (ObjectUtil.isNotNull(bo.getParentTaskId())) { taskService.addComment(bo.getParentTaskId(), task.getProcessInstanceId(), FlowComment.TRANSFER.getType(), commentBuilder.toString()); } else { taskService.addComment(bo.getTaskId(), task.getProcessInstanceId(), FlowComment.TRANSFER.getType(), commentBuilder.toString()); } // 设置拥有者为当前登录人 taskService.setOwner(bo.getTaskId(), TaskUtils.getUserId()); // 转办任务 taskService.setAssignee(bo.getTaskId(), bo.getUserId()); // 设置任务节点名称 bo.setTaskName(task.getName()); // 处理抄送用户 if (!copyService.makeCopy(bo)) { throw new RuntimeException("抄送任务失败"); } } /** * 取消申请 * * @param bo * @return */ @Override public void stopProcess(WfTaskBo bo) { List<Task> task = taskService.createTaskQuery().processInstanceId(bo.getProcInsId()).list(); if (CollectionUtils.isEmpty(task)) { throw new RuntimeException("流程未启动或已执行完成,取消申请失败"); } // 创建流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(bo.getProcInsId()).singleResult(); // 获取流程模型 BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId()); if (Objects.nonNull(bpmnModel)) { // 获取主流程 Process process = bpmnModel.getMainProcess(); // 获取结束节点 List<EndEvent> endNodes = process.findFlowElementsOfType(EndEvent.class, false); if (CollectionUtils.isNotEmpty(endNodes)) { // 设置当前用户为认证用户 Authentication.setAuthenticatedUserId(TaskUtils.getUserId()); // 添加流程评论 taskService.addComment(task.get(0).getId(), processInstance.getProcessInstanceId(), FlowComment.STOP.getType(), StringUtils.isBlank(bo.getComment()) ? "取消申请" : bo.getComment()); // 获取最后一个结束节点 String endId = endNodes.get(0).getId(); // 获取当前流程执行 List<Execution> executions = runtimeService.createExecutionQuery().parentId(processInstance.getProcessInstanceId()).list(); // 存储执行ID List<String> executionIds = new ArrayList<>(); executions.forEach(execution -> executionIds.add(execution.getId())); runtimeService.setVariable(processInstance.getProcessInstanceId(), ProcessConstants.PROCESS_STATUS_KEY, ProcessStatus.CANCELED.getStatus()); // 变更流程为已结束状态 runtimeService.createChangeActivityStateBuilder().moveExecutionsToSingleActivityId(executionIds, endId).changeState(); } } } /** * 撤回流程 * * @param taskBo 请求实体参数 */ @Override @Transactional(rollbackFor = Exception.class) public void revokeProcess(WfTaskBo taskBo) { String procInsId = taskBo.getProcInsId(); String taskId = taskBo.getTaskId(); // 校验流程是否结束 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).active().singleResult(); if (ObjectUtil.isNull(processInstance)) { throw new RuntimeException("流程已结束或已挂起,无法执行撤回操作"); } // 获取待撤回任务实例 HistoricTaskInstance currTaskIns = historyService.createHistoricTaskInstanceQuery().taskId(taskId).taskAssignee(TaskUtils.getUserId()).singleResult(); if (ObjectUtil.isNull(currTaskIns)) { throw new RuntimeException("当前任务不存在,无法执行撤回操作"); } // 获取 bpmn 模型 BpmnModel bpmnModel = repositoryService.getBpmnModel(currTaskIns.getProcessDefinitionId()); UserTask currUserTask = ModelUtils.getUserTaskByKey(bpmnModel, currTaskIns.getTaskDefinitionKey()); // 查找下一级用户任务列表 List<UserTask> nextUserTaskList = ModelUtils.findNextUserTasks(currUserTask); List<String> nextUserTaskKeys = nextUserTaskList.stream().map(UserTask::getId).collect(Collectors.toList()); // 获取当前节点之后已完成的流程历史节点 List<HistoricTaskInstance> finishedTaskInsList = historyService.createHistoricTaskInstanceQuery().processInstanceId(procInsId).taskCreatedAfter(currTaskIns.getEndTime()).finished().list(); for (HistoricTaskInstance finishedTaskInstance : finishedTaskInsList) { // 检查已完成流程历史节点是否存在下一级中 if (CollUtil.contains(nextUserTaskKeys, finishedTaskInstance.getTaskDefinitionKey())) { throw new RuntimeException("下一流程已处理,无法执行撤回操作"); } } // 获取所有激活的任务节点,找到需要撤回的任务 List<Task> activateTaskList = taskService.createTaskQuery().processInstanceId(procInsId).list(); List<String> revokeExecutionIds = new ArrayList<>(); identityService.setAuthenticatedUserId(TaskUtils.getUserId()); for (Task task : activateTaskList) { // 检查激活的任务节点是否存在下一级中,如果存在,则加入到需要撤回的节点 if (CollUtil.contains(nextUserTaskKeys, task.getTaskDefinitionKey())) { // 添加撤回审批信息 taskService.setAssignee(task.getId(), TaskUtils.getUserId()); taskService.addComment(task.getId(), task.getProcessInstanceId(), FlowComment.REVOKE.getType(), SecurityUtils.getLoginUser().getUser().getNickName() + "撤回流程审批"); revokeExecutionIds.add(task.getExecutionId()); } } try { ChangeActivityStateBuilder changeActivityStateBuilder = runtimeService.createChangeActivityStateBuilder().processInstanceId(procInsId).moveExecutionsToSingleActivityId(revokeExecutionIds, currTaskIns.getTaskDefinitionKey()); changeActivityStateBuilder.changeState(); } catch (FlowableObjectNotFoundException e) { throw new RuntimeException("未找到流程实例,流程可能已发生变化"); } catch (FlowableException e) { throw new RuntimeException("执行撤回操作失败"); } catch (Exception e) { throw new RuntimeException("已经撤回"); } } /** * 获取流程过程图 * * @param processId * @return */ @Override public InputStream diagram(String processId) { String processDefinitionId; // 获取当前的流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult(); // 如果流程已经结束,则得到结束节点 if (Objects.isNull(processInstance)) { HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult(); processDefinitionId = pi.getProcessDefinitionId(); } else {// 如果流程没有结束,则取当前活动节点 // 根据流程实例ID获得当前处于活动状态的ActivityId合集 ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult(); processDefinitionId = pi.getProcessDefinitionId(); } // 获得活动的节点 List<HistoricActivityInstance> highLightedFlowList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId).orderByHistoricActivityInstanceStartTime().asc().list(); List<String> highLightedFlows = new ArrayList<>(); List<String> highLightedNodes = new ArrayList<>(); //高亮线 for (HistoricActivityInstance tempActivity : highLightedFlowList) { if ("sequenceFlow".equals(tempActivity.getActivityType())) { //高亮线 highLightedFlows.add(tempActivity.getActivityId()); } else { //高亮节点 highLightedNodes.add(tempActivity.getActivityId()); } } //获取流程图 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId); ProcessEngineConfiguration configuration = processEngine.getProcessEngineConfiguration(); //获取自定义图片生成器 ProcessDiagramGenerator diagramGenerator = new CustomProcessDiagramGenerator(); return diagramGenerator.generateDiagram(bpmnModel, "png", highLightedNodes, highLightedFlows, configuration.getActivityFontName(), configuration.getLabelFontName(), configuration.getAnnotationFontName(), configuration.getClassLoader(), 1.0, true); } /** * 获取流程变量 * * @param taskId 任务ID * @return 流程变量 */ @Override public Map<String, Object> getProcessVariables(String taskId) { HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().includeProcessVariables().finished().taskId(taskId).singleResult(); if (Objects.nonNull(historicTaskInstance)) { return historicTaskInstance.getProcessVariables(); } return taskService.getVariables(taskId); } /** * 启动第一个任务 * * @param processInstance 流程实例 * @param variables 流程参数 */ @Override public void startFirstTask(ProcessInstance processInstance, Map<String, Object> variables) { // 若第一个用户任务为发起人,则自动完成任务 // 获取指定流程实例ID的任务列表 List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).list(); // 如果任务列表不为空 if (CollUtil.isNotEmpty(tasks)) { // 获取发起人ID String userIdStr = (String) variables.get(TaskConstants.PROCESS_INITIATOR); // 设置当前登录用户 identityService.setAuthenticatedUserId(TaskUtils.getUserId()); // 遍历任务列表 for (Task task : tasks) { // 如果任务assignee为发起人ID if (StrUtil.equals(task.getAssignee(), userIdStr)) { // 添加流程评论 taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), SecurityUtils.getLoginUser().getUser().getNickName() + "发起流程申请"); // 完成任务 taskService.complete(task.getId(), variables); } } } } /** * 加签任务 * * @param bo */ @Override public void addSignTask(WfTaskBo bo) { //登录用户 String userName = String.valueOf(SecurityUtils.getUserId()); String nickName = SecurityUtils.getLoginUser().getUser().getNickName(); String[] userIds = bo.getAddSignUsers().split(","); List<SysUser> sysUserList = userServiceApi.selectSysUserByUserIdList(Arrays.stream(userIds).mapToLong(Long::parseLong).toArray()); String nick = StrUtil.join(",", sysUserList.stream().map(SysUser::getNickName).collect(Collectors.toList())); TaskEntityImpl taskEntity = (TaskEntityImpl) taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); if (taskEntity != null) { if (StringUtils.equalsIgnoreCase(bo.getAddSignType(), "0")) { addTasksBefore(bo, taskEntity, userName, new HashSet<String>(Arrays.asList(userIds)), nickName + "在[" + taskEntity.getName() + "]节点前加签,加签人员【" + nick + "】原因:" + bo.getComment()); } else { addTasksAfter(bo, taskEntity, userName, new HashSet<String>(Arrays.asList(userIds)), nickName + "在[" + taskEntity.getName() + "]节点后加签,加签人员【" + nick + "】原因:" + bo.getComment()); } } else { Assert.notNull("不存在任务实例,请确认!"); } } /** * 多实例加签任务 * * @param bo */ @Override public void multiInstanceAddSign(WfTaskBo bo) { //校验任务是否存在 Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); //流程定义id String processDefinitionId = task.getProcessDefinitionId(); //流程实例id String processInstanceId = task.getProcessInstanceId(); //当前活动节点id String currentActId = task.getTaskDefinitionKey(); //当前活动节点名称(任务名称) String currentActName = task.getName(); //多实例用户任务节点的元素变量名 String multiInstanceActAssigneeParam = getMultiInstanceActAssigneeParam(processDefinitionId, currentActId); //如果元素变量名为空则表示该节点不是会签节点 if (ObjectUtil.isEmpty(multiInstanceActAssigneeParam)) { throw new FlowableException("加签失败,该任务不是会签(或签)任务或节点配置错误"); } //加签人的姓名 List<String> assigneeNameList = CollectionUtil.newArrayList(); String[] userIds = bo.getAddSignUsers().split(","); List<String> assigneeList = new ArrayList<String>(); assigneeList = Arrays.asList(userIds); //遍历要加签的人 assigneeList.forEach(assignee -> { //获取加签人名称 String assigneeName = userServiceApi.selectUserById(Long.valueOf(assignee)).getNickName(); assigneeNameList.add(assigneeName); //定义参数 Map<String, Object> assigneeVariables = new HashMap<String, Object>(16); //根据获取的变量名加参数 assigneeVariables.put(multiInstanceActAssigneeParam, assignee); //执行加签操作 try { runtimeService.addMultiInstanceExecution(currentActId, processInstanceId, assigneeVariables); } catch (FlowableException e) { //抛异常加签失败 throw new FlowableException("加签失败,该任务不是会签(或签)任务或节点配置错误"); } catch (Exception e) { //否则的话,可能出现服务器内部异常 throw new FlowableException("服务器出现异常,请联系管理员"); } }); //当前办理人姓名 String name = SecurityUtils.getLoginUser().getUser().getNickName(); //添加加签意见 String type = FlowComment.DSLJQ.getType(); if (ObjectUtil.isNotNull(bo.getParentTaskId())) { List<SysUser> sysUserList = userServiceApi.selectSysUserByUserIdList(Arrays.stream(userIds).mapToLong(Long::parseLong).toArray()); String nick = StrUtil.join(",", sysUserList.stream().map(SysUser::getNickName).collect(Collectors.toList())); taskService.addComment(task.getParentTaskId(), processInstanceId, type, name + "加签原因加签人员【" + nick + "】:" + bo.getComment()); } else { taskService.addComment(task.getId(), processInstanceId, type, name + "加签原因:" + bo.getComment()); } } /** * 收回流程,收回后发起人可以重新编辑表单发起流程,对于自定义业务就是原有任务都删除,重新进行申请 * * @param bo * @return */ @Override @Transactional(rollbackFor = Exception.class) public R recallProcess(WfTaskBo bo) { // 当前任务 listtask List<Task> listtask = taskService.createTaskQuery().processInstanceId(bo.getProcInsId()).active().list(); if (listtask == null || listtask.size() == 0) { throw new FlowableException("流程未启动或已执行完成,无法收回"); } if (taskService.createTaskQuery().taskId(listtask.get(0).getId()).singleResult().isSuspended()) { throw new FlowableException("任务处于挂起状态"); } String processInstanceId = listtask.get(0).getProcessInstanceId(); // 获取所有历史任务(按创建时间升序) List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).orderByTaskCreateTime().asc().list(); if (CollectionUtil.isEmpty(hisTaskList) || hisTaskList.size() < 2) { log.error("当前流程 【{}】 审批节点 【{}】正在初始节点无法收回", processInstanceId, listtask.get(0).getName()); throw new FlowableException(String.format("当前流程 【%s】 审批节点【%s】正在初始节点无法收回", processInstanceId, listtask.get(0).getName())); } // 第一个任务 HistoricTaskInstance startTask = hisTaskList.get(0); //若操作用户不是发起人,不能收回 if (!StringUtils.equalsAnyIgnoreCase(String.valueOf(SecurityUtils.getUserId()), startTask.getAssignee())) { throw new FlowableException("操作用户不是发起人,不能收回"); } // 当前任务 HistoricTaskInstance currentTask = hisTaskList.get(hisTaskList.size() - 1); BpmnModel bpmnModel = repositoryService.getBpmnModel(listtask.get(0).getProcessDefinitionId()); // 获取第一个活动节点 FlowNode startFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(startTask.getTaskDefinitionKey()); // 获取当前活动节点 FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentTask.getTaskDefinitionKey()); UserTask startUserTask = (UserTask) startFlowNode; UserTask currentUserTask = (UserTask) currentFlowNode; if (startUserTask.getId().equals(currentUserTask.getId())) { throw new RuntimeException("当前节点是已是最初节点,无法收回"); } // 临时保存当前活动的原始方向 List<SequenceFlow> originalSequenceFlowList = new ArrayList<>(currentFlowNode.getOutgoingFlows()); // 清理活动方向 currentFlowNode.getOutgoingFlows().clear(); // 建立新方向 SequenceFlow newSequenceFlow = new SequenceFlow(); newSequenceFlow.setId("newSequenceFlowId"); newSequenceFlow.setSourceFlowElement(currentFlowNode); newSequenceFlow.setTargetFlowElement(startFlowNode); List<SequenceFlow> newSequenceFlowList = new ArrayList<>(); newSequenceFlowList.add(newSequenceFlow); // 当前节点指向新的方向 currentFlowNode.setOutgoingFlows(newSequenceFlowList); // 完成当前任务 for (Task task : listtask) { taskService.addComment(task.getId(), listtask.get(0).getProcessInstanceId(), FlowComment.RECALL.getType(), "发起人收回"); taskService.setAssignee(task.getId(), startTask.getAssignee()); taskService.complete(task.getId()); } // 重新查询当前任务 Task nextTask = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); if (ObjectUtil.isNotNull(nextTask)) { taskService.setAssignee(nextTask.getId(), startTask.getAssignee()); // taskService.complete(nextTask.getId());;//跳过流程发起节点 } // 恢复原始方向 currentFlowNode.setOutgoingFlows(originalSequenceFlowList); return R.ok("发起人收回成功"); } /** * 拒绝任务 * * @param taskBo */ @Override public void taskRefuse(WfTaskBo taskBo) { // 当前任务 task TaskEntityImpl task = (TaskEntityImpl) taskService.createTaskQuery().taskId(taskBo.getTaskId()).singleResult(); if (ObjectUtil.isNull(task)) { throw new RuntimeException("获取任务信息异常!"); } if (task.isSuspended()) { throw new RuntimeException("任务处于挂起状态"); } // 获取流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(taskBo.getProcInsId()).singleResult(); if (processInstance == null) { throw new RuntimeException("流程实例不存在,请确认!"); } // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); // 添加审批意见 if (ObjectUtil.isNotNull(taskBo.getParentTaskId()) && !StrUtil.isEmpty(taskBo.getParentTaskId())) { taskService.addComment(taskBo.getParentTaskId(), taskBo.getProcInsId(), FlowComment.REFUSE.getType(), taskBo.getComment()); } else { taskService.addComment(taskBo.getTaskId(), taskBo.getProcInsId(), FlowComment.REFUSE.getType(), taskBo.getComment()); } // 设置流程状态为已终结 runtimeService.setVariable(processInstance.getId(), ProcessConstants.PROCESS_STATUS_KEY, ProcessStatus.TERMINATED.getStatus()); // 获取所有节点信息 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); EndEvent endEvent = ModelUtils.getEndEvent(bpmnModel); // 终止流程 List<Execution> executions = runtimeService.createExecutionQuery().parentId(task.getProcessInstanceId()).list(); List<String> executionIds = executions.stream().map(Execution::getId).collect(Collectors.toList()); runtimeService.createChangeActivityStateBuilder().processInstanceId(task.getProcessInstanceId()).moveExecutionsToSingleActivityId(executionIds, endEvent.getId()).changeState(); String key = sysConfigServiceApi.selectConfigByKey("sys.wechat.notice"); if (Boolean.parseBoolean(key)) { // 发送微信通知 sendingCompleteWxNotice(task, taskBo); } // 处理抄送用户 if (!copyService.makeCopy(taskBo)) { throw new RuntimeException("抄送任务失败"); } } /** * 发送任务拒绝微信通知 * * @param task * @param taskBo */ private void sendingTaskRefuseWxNotice(TaskEntityImpl task, WfTaskBo taskBo) { String procInsId = task.getProcessInstanceId(); HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).singleResult(); SysUser startUser = userServiceApi.selectUserById(Long.valueOf(historicProcessInstance.getStartUserId())); String approvalResult = "已终止"; String approver = SecurityUtils.getLoginUser().getUser().getNickName(); HashMap<String, Object> map = (HashMap<String, Object>) task.getOriginalPersistentState(); String name = map.get("name").toString(); String comment = taskBo.getComment(); String approvalTime = DateUtils.getTime(); try { approvalResultTemplate.sending(startUser.getOpenid(), approver, approvalResult, comment, approvalTime, "审批节点:" + name); } catch (WxErrorException e) { System.out.println(e.getMessage()); } } /** * 跳转任务 * * @param bo */ @Override public void taskJump(WfTaskBo bo) { //校验任务是否存在 Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); //当前节点id String currentActId = task.getTaskDefinitionKey(); //获取流程实例id String processInstanceId = task.getProcessInstanceId(); //当前活动节点名称(任务名称) String currentActName = task.getName(); //获取当前操作人姓名 String name = SecurityUtils.getLoginUser().getUser().getNickName(); String type = FlowComment.JUMP.getType(); //添加跳转意见 name + "将任务跳转到【" + targetActName + "】,跳转原因:" + comment + ";"; if (ObjectUtil.isNotNull(bo.getParentTaskId())) { taskService.addComment(task.getParentTaskId(), processInstanceId, type, "当前任务[" + currentActName + "]由" + name + "跳转到[" + bo.getTargetActName() + "],跳转原因:" + bo.getComment()); } else { taskService.addComment(task.getId(), processInstanceId, type, "当前任务[" + currentActName + "]由" + name + "跳转到[" + bo.getTargetActName() + "],跳转原因:" + bo.getComment()); } // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); // 获取流程模型信息 BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); // 获取当前任务节点元素 FlowElement source = ModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey()); // 获取跳转的节点元素 FlowElement target = ModelUtils.getFlowElementById(bpmnModel, bo.getTargetActId()); // 从当前节点向前扫描,判断当前节点与目标节点是否属于串行,若目标节点是在并行网关上或非同一路线上,不可跳转 boolean isSequential = ModelUtils.isSequentialReachable(source, target, new HashSet<>()); if (!isSequential) { throw new RuntimeException("当前节点相对于目标节点,不属于串行关系,无法回退"); } //执行跳转操作 runtimeService.createChangeActivityStateBuilder().processInstanceId(processInstanceId).moveActivityIdTo(currentActId, bo.getTargetActId()).changeState(); } /** * 用户任务列表,作为跳转任务使用 * * @param bo * @return */ @Override public R userTaskList(WfTaskBo bo) { List<WfUserTaskVo> resultList = new ArrayList<WfUserTaskVo>(); // 当前任务 task Task task = taskService.createTaskQuery().taskId(bo.getTaskId()).singleResult(); // 获取流程定义信息 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult(); //根据流程定义获取deployment String deploymentId = processDefinition.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (ObjectUtil.isEmpty(deployment)) { throw new FlowableException("流程还没布置"); } //获取bpmnModel并转为modelNode BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); //获取主流程 Process mainProcess = bpmnModel.getMainProcess(); //获取用户任务节点类型,深入子流程 mainProcess.findFlowElementsOfType(UserTask.class, true).forEach(userTask -> { // 判断不是发起人 if (!"${initiator}".equals(userTask.getAssignee())) { WfUserTaskVo userTaskResult = new WfUserTaskVo(); userTaskResult.setId(userTask.getId()); userTaskResult.setProcessDefinitionId(processDefinition.getId()); userTaskResult.setName(userTask.getName()); resultList.add(userTaskResult); } }); return R.ok(resultList); } /** * 监听任务创建事件 * * @param task 任务实体 */ @Override @Transactional(rollbackFor = Exception.class) public void updateTaskStatusWhenCreated(Task task) { // 获取指定任务审批人 List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId()); Map<String, Object> variables = taskService.getVariables(task.getId()); if (ObjectUtil.isNull(variables.get("businessProcessType"))) { return; } String businessProcessType = variables.get("businessProcessType").toString(); // 遍历 identityLinksForTask 中的 IdentityLink 对象 for (IdentityLink identityLink : identityLinksForTask) { // 如果 IdentityLink 的类型是 Candidate if (IdentityLinkType.CANDIDATE.equals(identityLink.getType())) { } } } private void sending(String openid, Map<String, Object> variables) { // 发送微信订阅消息 try { pendingApprovalTemplate.sending(openid, variables.get("deptName").toString(), variables.get("userName").toString(), RiskAreaUtils.getHazardAreaNameByData(variables.get("riskArea").toString()), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, (Date) variables.get("createTime")), "进行中" ); } catch (WxErrorException e) { System.out.println(e.getMessage()); } } private MessageSendWhenTaskCreatedReq convert(ProcessInstance processInstance, SysUser user, Task task) { MessageSendWhenTaskCreatedReq reqDTO = new MessageSendWhenTaskCreatedReq(); reqDTO.setProcessInstanceId(processInstance.getProcessInstanceId()); reqDTO.setProcessInstanceName(processInstance.getName()); reqDTO.setStartUserId(user.getUserId()); reqDTO.setStartUserNickname(user.getNickName()); reqDTO.setTaskId(task.getId()); reqDTO.setTaskName(task.getName()); reqDTO.setAssigneeUserId(NumberUtils.parseLong(task.getAssignee())); return reqDTO; } /** * 任务前加签 (如果多次加签只能显示第一次前加签的处理人来处理任务) * 多个加签人处理完毕任务之后又流到自己这里 * * @param bo 流程实例id * @param assignee 受让人 * @param description 描述 * @param assignees 被加签人 */ private void addTasksBefore(WfTaskBo bo, TaskEntityImpl taskEntity, String assignee, Set<String> assignees, String description) { addTask(bo, taskEntity, assignee, assignees, description, Boolean.FALSE); } /** * 任务后加签(加签人自己自动审批完毕加签多个人处理任务) * * @param bo 流程实例id * @param assignee 受让人 * @param description 描述 * @param assignees 被加签人 */ private void addTasksAfter(WfTaskBo bo, TaskEntityImpl taskEntity, String assignee, Set<String> assignees, String description) { addTask(bo, taskEntity, assignee, assignees, description, Boolean.TRUE); } /** * 创建加签任务 * * @param bo * @param taskEntity * @param assignee * @param assignees * @param description * @param flag */ @Transactional(rollbackFor = Exception.class) public void addTask(WfTaskBo bo, TaskEntityImpl taskEntity, String assignee, Set<String> assignees, String description, Boolean flag) { Assert.notNull(taskEntity, String.format("分配人 [%s] 没有待处理任务", assignee)); //如果是加签再加签 String parentTaskId = taskEntity.getParentTaskId(); if (StrUtil.isBlank(parentTaskId)) { taskEntity.setOwner(assignee); taskEntity.setAssignee(null); taskEntity.setCountEnabled(true); if (flag) { taskEntity.setScopeType("after"); } else { taskEntity.setScopeType("before"); } // 设置任务为空执行者 taskService.saveTask(taskEntity); } //添加加签数据 this.createSignSubTasks(assignee, assignees, taskEntity); //添加审批意见 String type = flag ? FlowComment.HJQ.getType() : FlowComment.QJQ.getType(); taskService.addComment(taskEntity.getId(), bo.getProcInsId(), type, description); } /** * 创建加签子任务 * * @param assignees 被加签人 * @param assignee 加签人 * @param taskEntity 父任务 */ private void createSignSubTasks(String assignee, Set<String> assignees, TaskEntity taskEntity) { if (CollectionUtil.isNotEmpty(assignees)) { //1.创建被加签人的任务列表 assignees.forEach(userId -> { if (StrUtil.isNotBlank(userId)) { this.createSubTask(taskEntity, taskEntity.getId(), userId); } }); String parentTaskId = taskEntity.getParentTaskId(); if (StrUtil.isBlank(parentTaskId)) { parentTaskId = taskEntity.getId(); } String finalParentTaskId = parentTaskId; //2.创建加签人的任务并执行完毕 String taskId = taskEntity.getId(); if (StrUtil.isBlank(taskEntity.getParentTaskId())) { Task task = this.createSubTask(taskEntity, finalParentTaskId, assignee); taskId = task.getId(); } Task taskInfo = taskService.createTaskQuery().taskId(taskId).singleResult(); if (ObjectUtil.isNotNull(taskInfo)) { taskService.complete(taskId); } //如果是候选人,需要删除运行时候选不中的数据。 long candidateCount = taskService.createTaskQuery().taskId(parentTaskId).taskCandidateUser(assignee).count(); if (candidateCount > 0) { taskService.deleteCandidateUser(parentTaskId, assignee); } } } /** * 创建子任务 * * @param ptask 创建子任务 * @param assignee 子任务的执行人 * @return */ TaskEntity createSubTask(TaskEntity ptask, String ptaskId, String assignee) { TaskEntity task = null; if (ptask != null) { //1.生成子任务 task = (TaskEntity) taskService.newTask(UUID.randomUUID() + ""); task.setCategory(ptask.getCategory()); task.setDescription(ptask.getDescription()); task.setTenantId(ptask.getTenantId()); task.setAssignee(assignee); task.setName(ptask.getName()); task.setParentTaskId(ptaskId); task.setProcessDefinitionId(ptask.getProcessDefinitionId()); task.setProcessInstanceId(ptask.getProcessInstanceId()); task.setTaskDefinitionKey(ptask.getTaskDefinitionKey()); task.setTaskDefinitionId(ptask.getTaskDefinitionId()); task.setPriority(ptask.getPriority()); task.setCreateTime(new Date()); taskService.saveTask(task); } return task; } /** * 指派下一任务审批人 * * @param bpmnModel bpmn模型 * @param processInsId 流程实例id * @param userIds 用户ids */ private void assignNextUsers(BpmnModel bpmnModel, String processInsId, String userIds) { // 获取所有节点信息 List<Task> list = taskService.createTaskQuery().processInstanceId(processInsId).list(); if (list.size() == 0) { return; } Queue<String> assignIds = CollUtil.newLinkedList(userIds.split(",")); if (list.size() == assignIds.size()) { for (Task task : list) { taskService.setAssignee(task.getId(), assignIds.poll()); } return; } // 优先处理非多实例任务 Iterator<Task> iterator = list.iterator(); while (iterator.hasNext()) { Task task = iterator.next(); if (!ModelUtils.isMultiInstance(bpmnModel, task.getTaskDefinitionKey())) { if (!assignIds.isEmpty()) { taskService.setAssignee(task.getId(), assignIds.poll()); } iterator.remove(); } } // 若存在多实例任务,则进行动态加减签 if (CollUtil.isNotEmpty(list)) { if (assignIds.isEmpty()) { // 动态减签 for (Task task : list) { runtimeService.deleteMultiInstanceExecution(task.getExecutionId(), true); } } else { // 动态加签 for (String assignId : assignIds) { Map<String, Object> assignVariables = Collections.singletonMap(BpmnXMLConstants.ATTRIBUTE_TASK_USER_ASSIGNEE, assignId); runtimeService.addMultiInstanceExecution(list.get(0).getTaskDefinitionKey(), list.get(0).getProcessInstanceId(), assignVariables); } } } } /** * 获取多实例节点审批人参数 * * @param processDefinitionId * @param actId * @return */ public String getMultiInstanceActAssigneeParam(String processDefinitionId, String actId) { AtomicReference<String> resultParam = new AtomicReference<>(); ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult(); //获取bpmnModel并转为modelNode BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId()); //获取主流程 Process mainProcess = bpmnModel.getMainProcess(); //获取用户任务节点类型,深入子流程 mainProcess.findFlowElementsOfType(UserTask.class, true).forEach(userTask -> { String userTaskId = userTask.getId(); if (userTaskId.equals(actId)) { Object behavior = userTask.getBehavior(); if (ObjectUtil.isNotNull(behavior)) { //并行多实例节点 if (behavior instanceof ParallelMultiInstanceBehavior) { ParallelMultiInstanceBehavior parallelMultiInstanceBehavior = (ParallelMultiInstanceBehavior) behavior; String collectionElementVariable = parallelMultiInstanceBehavior.getCollectionElementVariable(); if (ObjectUtil.isNotEmpty(collectionElementVariable)) { resultParam.set(collectionElementVariable); } } //串行多实例节点 if (behavior instanceof SequentialMultiInstanceBehavior) { SequentialMultiInstanceBehavior sequentialMultiInstanceBehavior = (SequentialMultiInstanceBehavior) behavior; String collectionElementVariable = sequentialMultiInstanceBehavior.getCollectionElementVariable(); if (ObjectUtil.isNotEmpty(collectionElementVariable)) { resultParam.set(collectionElementVariable); } } } } }); return resultParam.get(); } }
281677160/openwrt-package
5,391
luci-app-amlogic/luasrc/view/amlogic/other_install.htm
<style> .NewsTdHeight{ line-height:20px; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="35%" align="right"><%:Select the device model:%></td> <td width="65%" align="left"> <select name="amlogic_soc" id="amlogic_soc" style="width:auto" onchange="sel_dtb_input(this.options[this.selectedIndex].value)"> <option value="0"><%:Select List%></option> <option value="99"><%:Enter the dtb file name%></option> </select> </td> </tr> <tr id="tr_sel_dtb" style="display:none;"><td width="30%" align="right"><%:Enter the dtb file name:%></td><td width="70%" align="left"><input class="cbi-input-file" style="width: 235px" type="text" id="amlogic_dtb" name="amlogic_dtb" /></td></tr> <tr id="tr_sel_soc" style="display:none;"><td width="30%" align="right"><%:Enter the soc name:%></td><td width="70%" align="left"><input class="cbi-input-file" style="width: 235px" type="text" id="amlogic_socname" name="amlogic_socname" /></td></tr> <tr id="tr_sel_uboot" style="display:none;"><td width="30%" align="right"><%:Enter the uboot_overload name:%></td><td width="70%" align="left"><input class="cbi-input-file" style="width: 235px" type="text" id="amlogic_uboot" name="amlogic_uboot" /></td></tr> <tr> <td width="30%" align="right"><%:Install OpenWrt:%></td> <td width="70%" align="left"> <input type="button" class="cbi-button cbi-button-reload" value="<%:Install%>" onclick="return amlogic_install(this, '<%=self:cfgvalue(section)%>')"/> <span id="_check_install"></span> </td> </tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ // Show custom dtb input box function sel_dtb_input(soc_value){ if ( soc_value == "99" ) { document.getElementById('tr_sel_dtb').style = ''; document.getElementById('tr_sel_soc').style = ''; document.getElementById('tr_sel_uboot').style = ''; } else { document.getElementById('tr_sel_dtb').style = 'display:none;'; document.getElementById('tr_sel_soc').style = 'display:none;'; document.getElementById('tr_sel_uboot').style = 'display:none;'; } } // Show the status of the install button function amlogic_install(btn,amlogic_install_sel) { var amlogic_soc_id = document.getElementById('amlogic_soc'); var amlogic_soc_index = amlogic_soc_id.selectedIndex; var amlogic_soc_value = amlogic_soc_id.options[amlogic_soc_index].value; var amlogic_soc_text = amlogic_soc_id.options[amlogic_soc_index].text; var amlogic_dtb_id = document.getElementById('amlogic_dtb'); var amlogic_dtb_value = amlogic_dtb_id.value; var amlogic_soc_name = document.getElementById('amlogic_socname'); var amlogic_socname_value = amlogic_socname.value; var amlogic_ubootname = document.getElementById('amlogic_uboot'); var amlogic_ubootname_value = amlogic_ubootname.value; var amlogic_confirm_info = amlogic_soc_text; if (confirm('<%:You have chosen:%>' + amlogic_confirm_info + ', <%:Start install?%>') != true) { return false; } btn.disabled = true; btn.value = '<%:Installing...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_amlogic_install")%>', { amlogic_install_sel: amlogic_soc_value + '@' + amlogic_dtb_value + ':' + amlogic_socname_value + ':' + amlogic_ubootname_value }, function(x,status) { if ( x && x.status == 200 ) { if(status.rule_install_status!="0") { btn.value = '<%:Install Failed%>'; } else { btn.value = '<%:Successful Install%>'; } } else { btn.value = '<%:Install%>'; } } ); btn.disabled = false; return false; } // Read openwrt install log var start_check_install = document.getElementById('_check_install'); XHR.poll(1, '<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_check_install")%>', status.start_check_install, function(x, status) { if ( x && x.status == 200 ) { if ( status.start_check_install != "\n" && status.start_check_install != "" ) { start_check_install.innerHTML = '<font color="blue"> '+status.start_check_install+'</font>'; } if ( status.start_check_install == "\n" || status.start_check_install == "" ) { start_check_install.innerHTML = ''; } } }); // Show external modal database: /etc/model_database.txt var mymodel_arrlen = 0; var _option_codes = '<option value="0"><%:Select List%></option>'; var _check_my_amlogic_soc = document.getElementById('amlogic_soc'); XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_model_database")%>', null, function(x, status) { if ( x && x.status == 200 ) { if ( status.my_model_database != "" ) { let userModelList = status.my_model_database; var user_arry = userModelList.split('@@@'); var mymodel_arrlen = user_arry.length - 1; for ( j = 0; j < mymodel_arrlen; j++ ) { my_box_mode = user_arry[j].split('###'); my_box_mode_id = my_box_mode[0]; my_box_mode_name = my_box_mode[1]; if ( my_box_mode_id != "" && my_box_mode_name != "" ) { _option_codes = _option_codes + '<option value="' + my_box_mode_id + '">[ ' + my_box_mode_id + ' ] ' + my_box_mode_name.replace(/~/g, " ") + '</option>'; } } } } _option_codes = _option_codes + '<option value="99"><%:Enter the dtb file name%></option>'; _check_my_amlogic_soc.innerHTML = _option_codes; }); //]]></script>
2929004360/ruoyi-sign
1,012
ruoyi-flowable/src/main/java/com/ruoyi/flowable/api/impl/IWfProcessServiceApiImpl.java
package com.ruoyi.flowable.api.impl; import com.ruoyi.flowable.api.service.IWfProcessServiceApi; import com.ruoyi.flowable.service.IWfProcessService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Map; /** * 流程服务api接口处理 * * @author fengcheng * @createTime 2022/3/24 18:57 */ @RequiredArgsConstructor @Service public class IWfProcessServiceApiImpl implements IWfProcessServiceApi { private final IWfProcessService processService; /** * 启动流程 * * @param definitionId * @param beanToMap * @return */ @Override public String startProcessByDefId(String definitionId, Map<String, Object> beanToMap) { return processService.startProcessByDefId(definitionId, beanToMap).getProcessInstanceId(); } /** * 删除流程实例 * * @param instanceIds */ @Override public void deleteProcessByIds(String[] instanceIds) { processService.deleteProcessByIds(instanceIds); } }
2929004360/ruoyi-sign
1,102
ruoyi-flowable/src/main/java/com/ruoyi/flowable/api/impl/IWfBusinessProcessServiceApiImpl.java
package com.ruoyi.flowable.api.impl; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.api.service.IWfBusinessProcessServiceApi; import com.ruoyi.flowable.service.IWfBusinessProcessService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; /** * 业务api流程Service业务层处理 * * @author fengcheng * @date 2024-07-15 */ @RequiredArgsConstructor @Service public class IWfBusinessProcessServiceApiImpl implements IWfBusinessProcessServiceApi { private final IWfBusinessProcessService wfBusinessProcessService; /** * 插入业务流程 * * @param wfBusinessProcess */ @Override public void insertWfBusinessProcess(WfBusinessProcess wfBusinessProcess) { wfBusinessProcessService.insertWfBusinessProcess(wfBusinessProcess); } /** * 删除业务流程 * * @param businessId * @param type */ @Override public void deleteWfBusinessProcessByBusinessId(String businessId, String type) { wfBusinessProcessService.deleteWfBusinessProcessByBusinessId(businessId, type); } }
281677160/openwrt-package
1,757
luci-app-amlogic/luasrc/view/amlogic/other_kvm.htm
<style> .NewsTdHeight{ line-height:32px; } .imgLeft{ float:left; margin-right:10px; vertical-align:middle; } .contentRight{ align-items: center; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td width="100%" align="left"> <input class="cbi-button cbi-button-save" type="button" value="<%:Switch System%>" onclick="switchopenwrt(this)" /> <p style="display:none"> <img id="img_loading" style="display:block" src="<%=resource%>/amlogic/loading.gif" alt="<%:Loading%>" class="imgLeft" /> <img id="img_switch" style="display:none" src="<%=resource%>/amlogic/switch.png" alt="<%:PowerOff%>" class="imgLeft" /> <span id="msg_switch" class="contentRight"><%:System is switching...%></span> </p> </td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function status_check() { var time = 5; var img_loading = document.getElementById("img_loading"); var img_switch = document.getElementById("img_switch"); var msg = document.getElementById("msg_switch"); var set = setInterval(function() { time--; msg.innerHTML = "<%:Waiting for system switching...%>"; if(time === 0) { img_loading.style.display = 'none'; img_switch.style.display = 'block'; msg.innerHTML = "<%:System switchover succeeded, restarting...%>"; clearInterval(set); } }, 1000); } function switchopenwrt(btn) { if (confirm('<%:Are you sure you want to switch systems?%>') != true) { return false; } btn.style.display = 'none'; document.getElementById('msg_switch').parentNode.style.display = 'block'; (new XHR()).post('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_switch")%>', { token: '<%=token%>' }, status_check); } //]]></script>
281677160/openwrt-package
4,475
luci-app-amlogic/luasrc/view/amlogic/other_snapshot.htm
<style> .NewsTdHeight{ line-height:20px; } .SnapshotsTitHeight{ line-height:40px; text-align: center; } .list{ display: flex; flex-wrap: wrap; justify-content: space-between; text-align: center; position: relative; width: 100%; background-color: #FFF; } .item{ border: 1px solid #CACACA; color: #888; font-size: 14px; width: 150px; height: 130px; margin:8px; text-align: center; align-items:center; } .item:hover{background:#e5f3f6;} .item:not(:nth-child(3n)){ content: ""; width: 150px; } .list:after { content: ""; width: 150px; } </style> <div class="list" id="_check_snapshot"> <%:Collecting data...%> </div> <script type="text/javascript">//<![CDATA[ // Delete snapshot function function delete_snapshot(btn,snapshot_delete_sel) { if (confirm('<%:You selected a snapshot:%> [ ' + snapshot_delete_sel + ' ] , <%:Confirm delete?%>') != true) { return false; } btn.disabled = true; btn.value = '<%:Deleting...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_snapshot_delete")%>', { snapshot_delete_sel: snapshot_delete_sel }, function(x,status) { if ( x && x.status == 200 ) { if(status.rule_delete_status!="0") { btn.value = '<%:Delete Failed%>'; } else { btn.value = '<%:Successfully Deleted%>'; } } else { btn.value = '<%:Delete Snapshot%>'; } } ); var sdiv = 'snapshots_div_' + snapshot_delete_sel; document.getElementById(sdiv).style.display = 'none'; btn.disabled = false; return false; } // Restore snapshot function function restore_snapshot(btn,snapshot_restore_sel) { if (confirm('<%:You selected a snapshot:%> [ ' + snapshot_restore_sel + ' ] , <%:Confirm recovery and restart OpenWrt?%>') != true) { return false; } btn.disabled = true; btn.value = '<%:Restoring...%> '; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_snapshot_restore")%>', { snapshot_restore_sel: snapshot_restore_sel }, function(x,status) { if ( x && x.status == 200 ) { if(status.rule_restore_status!="0") { btn.value = '<%:Restore Failed%>'; } else { btn.value = '<%:Successfully Restored%>'; } } else { btn.value = '<%:Restore Snapshot%>'; } } ); btn.disabled = false; return false; } // Show current snapshot list mycars_arrlen = 0; _no_snapshots = "<%:Currently OpenWrt does not support the snapshot function.%>"; _no_snapshots = _no_snapshots + "<%:Please use this plugin to reinstall or upgrade OpenWrt to enable the snapshot function.%>"; var _check_snapshot = document.getElementById('_check_snapshot'); XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_snapshot_list")%>', null, function(x, status) { if ( x && x.status == 200 ) { let userArer = status.current_snapshot; let user_arer_clear = userArer.replace(/\.snapshots\//g, ""); let trimstr = user_arer_clear.replace(/(^\s*)|(\s*$)/g, ""); let user_arer = trimstr.replace(/\s+/g, ","); var mycars = user_arer.split(','); var mycars_arrlen = mycars.length; _div_codes = "" _snapshots_tit = "" for ( j = 0; j < mycars_arrlen; j++ ) { if ( mycars[j] == "etc-000" ) { _snapshots_tit = "<%:Initialize Snapshot%>"; } else if ( mycars[j] == "etc-001" ) { _snapshots_tit = "<%:Update Snapshot%>"; } else { _snapshots_tit = mycars[j]; } _div_codes = _div_codes + '<div class="item" id="snapshots_div_' + mycars[j] + '">'; _div_codes = _div_codes + '<div class="SnapshotsTitHeight">' + _snapshots_tit + '</div>' _div_codes = _div_codes + '<div class="SnapshotsTitHeight"><input type="button" class="cbi-button cbi-button-apply" value="<%:Restore Snap%>" onclick="return restore_snapshot(this, \'' + mycars[j] + '\')"/></div>' if ( mycars[j] != "etc-000" && mycars[j] != "etc-001" ) { _div_codes = _div_codes + '<div class="SnapshotsTitHeight"><input type="button" class="cbi-button cbi-button-remove" value="<%:Delete Snap%>" onclick="return delete_snapshot(this, \'' + mycars[j] + '\')"/></div>' } _div_codes = _div_codes + '</div>'; } _check_snapshot.innerHTML = _div_codes ? _div_codes : "<font color=red>"+"<%:Invalid value.%>"+"</font>"; } else { _check_snapshot.innerHTML = "<font color=red>"+ _no_snapshots +"</font>"; } }); //]]></script>
281677160/openwrt-package
3,571
luci-app-amlogic/luasrc/view/amlogic/other_info.htm
<style> .NewsTdHeight{ line-height:20px; } </style> <fieldset class="cbi-section"> <table width="100%" class="NewsTdHeight"> <tr><td colspan="2" width="100%" align="center"> <img id="logo_amlogic" src="<%=resource%>/amlogic/logo.png" alt="Logo" width="135" /> </td></tr> <tr><td colspan="2" width="100%" align="center"> <img id="Packit" src="<%=resource%>/amlogic/packit.svg" alt="Packit" width="168px" height="20px" onclick="return homepage('packit')" /> &nbsp;&nbsp; <img id="Author" src="<%=resource%>/amlogic/author.svg" alt="Author" width="168px" height="20px" onclick="return author_homepage('author')" /> &nbsp;&nbsp; <img id="Plugin" src="<%=resource%>/amlogic/plugin.svg" alt="luci-app-amlogic" width="160px" height="20px" onclick="return homepage('plugin')" /> </td></tr> <tr><td width="20%" align="right"><%:Supported functions:%></td><td width="80%" align="left" id="_clash"> <%:Provide services such as install to EMMC, Update Firmware and Kernel, Backup and Recovery Config, Snapshot management, etc.%> </td></tr> <tr><td width="20%" align="right"><%:Supported Boxes:%></td><td width="80%" align="left" id="_clash"> <%:Amlogic s922x --- [ Beelink, Beelink-Pro, Ugoos-AM6-Plus, ODROID-N2, Khadas-VIM3, Ali-CT2000 ]%><br> <%:Amlogic s905x3 -- [ X96-Max+, HK1-Box, H96-Max-X3, Ugoos-X3, TX3, X96-Air, A95XF3-Air ]%><br> <%:Amlogic s905x2 -- [ X96Max-4G, X96Max-2G, MECOOL-KM3-4G, Tanix-Tx5-Max, A95X-F2 ]%><br> <%:Amlogic s912 ---- [ H96-Pro-Plus, Octopus-Planet, A1, A2, Z6-Plus, TX92, X92, TX8-MAX, TX9-Pro ]%><br> <%:Amlogic s905x --- [ HG680P, B860H, TBee, T95, TX9, XiaoMI-3S, X96 ]%><br> <%:Amlogic s905w --- [ X96-Mini, TX3-Mini, W95, X96W/FunTV, MXQ-Pro-4K ]%><br> <%:Amlogic s905d --- [ Phicomm-N1, MECOOL-KI-Pro, SML-5442TW ]%><br> <%:Amlogic s905l --- [ UNT402A, M201-S ]%><br> <%:Amlogic s905l2 -- [ MGV2000, MGV3000, Wojia-TV-IPBS9505, M301A, E900v21E ]%><br> <%:Amlogic s905l3 -- [ CM211-1, CM311-1, HG680-LC, M401A, UNT400G1, UNT402A, ZXV10-BV310 ]%><br> <%:Amlogic s905l3a - [ E900V22C/D, CM311-1a-YST, M401A, M411A, UNT403A, UNT413A, IP112H ]%><br> <%:Amlogic s905l3b - [ CM211-1, CM311-1, E900V22D, E900V21E, E900V22E, M302A/M304A ]%><br> <%:Amlogic s905 ---- [ Beelink-Mini-MX-2G, Sunvell-T95M, MXQ-Pro+4K, SumaVision-Q5 ]%><br> <%:Allwinner H6 ---- [ V-Plus Cloud ]%><br> <%:Rockchip -------- [ BeikeYun, L1-Pro, FastRhino R66S/R68S, Radxa 5B/E25 ]%><br> <%:Used in KVM ----- [ Can be used in KVM virtual machine of Armbian system. ]%> </td></tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ function winOpen(url) { var winOpen = window.open(url); if( winOpen == null || typeof(winOpen) == 'undefined' ){ window.location.href=url; } } function homepage(website) { var url = ""; if( website == 'packit' ) { url = 'https://github.com/unifreq/openwrt_packit'; } if( website == 'plugin' ) { url = 'https://github.com/ophub/luci-app-amlogic'; } if ( url != "" ) { winOpen(url); } } function author_homepage(website) { var openwrt_author_repo = ""; XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "start_openwrt_author")%>', null, function(x, status) { if ( x && x.status == 200 ) { let openwrt_author_repo = status.openwrt_author; let trimstr_au = openwrt_author_repo.replace(/(^\s*)|(\s*$)/g, ""); if (trimstr_au.indexOf("https") == -1) { trimstr_au = 'https://github.com/' + trimstr_au; } if ( trimstr_au != "" ) { winOpen(trimstr_au); } } }); } //]]></script>
2929004360/ruoyi-sign
926
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/msg/MessageSendWhenTaskCreatedReq.java
package com.ruoyi.flowable.domain.msg; import lombok.Data; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * BPM 发送任务被分配 Request DTO * * @author fengcheng */ @Data public class MessageSendWhenTaskCreatedReq { /** * 流程实例的编号 */ @NotEmpty(message = "流程实例的编号不能为空") private String processInstanceId; /** * 流程实例的名字 */ @NotEmpty(message = "流程实例的名字不能为空") private String processInstanceName; @NotNull(message = "发起人的用户编号") private Long startUserId; @NotEmpty(message = "发起人的昵称") private String startUserNickname; /** * 流程任务的编号 */ @NotEmpty(message = "流程任务的编号不能为空") private String taskId; /** * 流程任务的名字 */ @NotEmpty(message = "流程任务的名字不能为空") private String taskName; /** * 审批人的用户编号 */ @NotNull(message = "审批人的用户编号不能为空") private Long assigneeUserId; }
2929004360/ruoyi-sign
1,174
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/bo/WfFormBo.java
package com.ruoyi.flowable.domain.bo; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 流程表单业务对象 * * @author fengcheng * @createTime 2022/3/7 22:07 */ @Data @EqualsAndHashCode(callSuper = true) public class WfFormBo extends BaseEntity { private static final long serialVersionUID = 1L; /** * 表单主键 */ @NotNull(message = "表单ID不能为空") private String formId; /** * 用户id */ private Long userId; /** * 部门id */ @NotNull(message = "部门id不能为空") private Long deptId; /** * 创建人 */ private String userName; /** * 部门名称 */ @NotNull(message = "部门名称不能为空") private String deptName; /** * 表单名称 */ @NotBlank(message = "表单名称不能为空") private String formName; /** * 使用类型(1=本级使用,2=本下级使用) */ @NotBlank(message = "使用类型不能为空") private String type; /** * 表单内容 */ @NotBlank(message = "表单内容不能为空") private String content; /** * 备注 */ private String remark; }
2929004360/ruoyi-sign
1,242
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/bo/WfCopyBo.java
package com.ruoyi.flowable.domain.bo; import com.ruoyi.common.core.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 流程抄送业务对象 wf_copy * * @author ruoyi * @date 2022-05-19 */ @Data @EqualsAndHashCode(callSuper = true) public class WfCopyBo extends BaseEntity { /** * 抄送主键 */ @NotNull(message = "抄送主键不能为空") private String copyId; /** * 抄送标题 */ @NotNull(message = "抄送标题不能为空") private String title; /** * 流程主键 */ @NotBlank(message = "流程主键不能为空") private String processId; /** * 流程名称 */ @NotBlank(message = "流程名称不能为空") private String processName; /** * 流程分类主键 */ @NotBlank(message = "流程分类主键不能为空") private String categoryId; /** * 任务主键 */ @NotBlank(message = "任务主键不能为空") private String taskId; /** * 用户主键 */ @NotNull(message = "用户主键不能为空") private Long userId; /** * 发起人Id */ @NotNull(message = "发起人主键不能为空") private Long originatorId; /** * 发起人名称 */ @NotNull(message = "发起人名称不能为空") private String originatorName; }
281677160/openwrt-package
3,736
luci-app-amlogic/luasrc/view/amlogic/other_log.htm
<%+cbi/valueheader%> <textarea id="amlogic.ophub.clog" class="cbi-input-textarea" style="width: 100%;display:inline" data-update="change" rows="8" cols="60" readonly="readonly" > </textarea> <fieldset class="cbi-section"> <table width="100%"> <tr> <td width="25%" align="center"><input type="button" class="cbi-button cbi-button-apply" id="stop_refresh_button" value="<%:Stop Refresh Log%>" onclick=" return stop_refresh() "/></td> <td width="25%" align="center"><input type="button" class="cbi-button cbi-button-apply" id="start_refresh_button" value="<%:Start Refresh Log%>" onclick=" return start_refresh() "/></td> <td width="25%" align="center"><input type="button" class="cbi-button cbi-button-apply" id="del_log_button" value="<%:Clean Log%>" style=" display:inline;" onclick=" return del_log() " /></td> <td width="25%" align="center"><input type="button" class="cbi-button cbi-button-apply" id="down_log_button" value="<%:Download Log%>" style=" display:inline;" onclick=" return download_log() " /></td> </tr> </table> </fieldset> <script type="text/javascript">//<![CDATA[ var r function stop_refresh() { clearTimeout(r); return } function start_refresh() { clearTimeout(r); r=setTimeout("poll_log()",1000*2); return } function createAndDownloadFile(fileName, content) { var aTag = document.createElement('a'); var blob = new Blob([content]); aTag.download = fileName; aTag.href = URL.createObjectURL(blob); aTag.click(); URL.revokeObjectURL(blob); } function download_log(){ var lv = document.getElementById('amlogic.ophub.clog'); var dt = new Date(); var timestamp = dt.getFullYear()+"-"+(dt.getMonth()+1)+"-"+dt.getDate()+"-"+dt.getHours()+"-"+dt.getMinutes()+"-"+dt.getSeconds(); createAndDownloadFile("Amlogic-"+timestamp+".log",lv.innerHTML) return } function del_log() { XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "del_log")%>',null,function(x, data){ var lv = document.getElementById('amlogic.ophub.clog'); lv.innerHTML=""; } ); return } function p(s) { return s < 10 ? '0' + s: s; } function line_tolocal(str){ var strt=new Array(); str.trim().split('\n').forEach(function(v, i) { var dt = new Date(v.substring(6,26)); if (dt != "Invalid Date"){ strt[i]=dt.getFullYear()+"-"+p(dt.getMonth()+1)+"-"+p(dt.getDate())+" "+p(dt.getHours())+":"+p(dt.getMinutes())+":"+p(dt.getSeconds())+v.substring(27); }else{ strt[i]=v;}}) var old_log_line = sessionStorage.log_line; if ( old_log_line != null && strt.length != null ) { if (old_log_line - strt.length < 0) { sessionStorage.log_line = strt.length; return strt.slice('-'+(strt.length-old_log_line)) } else if (old_log_line == strt.length) { sessionStorage.log_line = strt.length; return } else if (old_log_line - strt.length > 0) { sessionStorage.log_line = strt.length; var lv = document.getElementById('amlogic.ophub.clog'); lv.innerHTML = ""; return strt } } else if ( strt.length != null ) { sessionStorage.log_line = strt.length; return strt } else { sessionStorage.log_line = "0"; return strt } } function poll_log(){ XHR.get('<%=luci.dispatcher.build_url("admin", "system", "amlogic", "refresh_log")%>', null, function(x, data) { if ( x && x.status == 200 ) { var lv = document.getElementById('amlogic.ophub.clog'); if (x.responseText && lv) { var lines=line_tolocal(x.responseText); if (lines != null) { lv.innerHTML = lines.reverse().join('\n')+'\n'+lv.innerHTML; //lv.innerHTML = x.responseText.split('\n').reverse().join('\n')+lv.innerHTML; } } } } ); r=setTimeout("poll_log()",1000*2); } sessionStorage.removeItem("log_line"); poll_log(); //]]> </script> <%+cbi/valuefooter%>
2929004360/ruoyi-sign
1,720
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/bo/WfModelBo.java
package com.ruoyi.flowable.domain.bo; import com.ruoyi.flowable.base.BaseEntity; import com.ruoyi.flowable.domain.WfModelPermission; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.List; /** * 流程模型对象 * * @author fengcheng * @createTime 2022/6/21 9:16 */ @Data public class WfModelBo extends BaseEntity { /** * 模型主键 */ @NotNull(message = "模型主键不能为空") private String modelId; /** * 菜单id */ private String menuId; /** * 模型名称 */ @NotNull(message = "模型名称不能为空") private String modelName; /** * 模型Key */ @NotNull(message = "模型Key不能为空") private String modelKey; /** * 菜单名称 */ private String menuName; /** * 流程分类 */ @NotBlank(message = "流程分类不能为空") private String category; /** * 描述 */ private String description; /** * 表单类型 */ private String formType; /** * 流程配置 */ private String processConfig; /** * 模板id */ private String modelTemplateId; /** * 表单主键 */ private String formId; /** * 表单名称 */ private String formName; /** * 表单查看路由 */ private String formCustomViewPath; /** * 表单提交路由 */ private String formCustomCreatePath; /** * 流程图标 */ private String icon; /** * 流程xml */ private String bpmnXml; /** * 是否保存为新版本 */ private Boolean newVersion; /** * 使用人 */ private List<WfModelPermission> selectUserList; /** * 使用部门 */ private List<WfModelPermission> selectDeptList; }
2929004360/ruoyi-sign
1,715
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfCopyVo.java
package com.ruoyi.flowable.domain.vo; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import java.util.Date; /** * 流程抄送视图对象 wf_copy * * @author ruoyi * @date 2022-05-19 */ @Data public class WfCopyVo { private static final long serialVersionUID = 1L; /** * 抄送主键 */ @Excel(name = "抄送主键") @TableId private String copyId; /** * 抄送标题 */ @Excel(name = "抄送标题") private String title; /** * 流程主键 */ @Excel(name = "流程主键") private String processId; /** * 流程名称 */ @Excel(name = "流程名称") private String processName; /** * 流程分类主键 */ @Excel(name = "流程分类主键") private String categoryId; /** * 部署主键 */ @Excel(name = "部署主键") private String deploymentId; /** * 流程实例主键 */ @Excel(name = "流程实例主键") private String instanceId; /** * 任务主键 */ @Excel(name = "任务主键") private String taskId; /** * 用户主键 */ @Excel(name = "用户主键") private Long userId; /** * 发起人Id */ @Excel(name = "发起人主键") private Long originatorId; /** * 发起人名称 */ @Excel(name = "发起人名称") private String originatorName; /** * 抄送时间(创建时间) */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "抄送时间") private Date createTime; /** * 表单类型 */ private String formType; /** * 表单查看路径 */ private String formViewPath; /** * 流程状态 */ private String processStatus; /** 业务id */ private String businessId; }
281677160/openwrt-package
9,879
luci-app-amlogic/luasrc/model/cbi/amlogic/amlogic_upload.lua
--Copyright: https://github.com/coolsnowwolf/luci/tree/master/applications/luci-app-filetransfer --Extended support: https://github.com/ophub/luci-app-amlogic --Function: Upload files local os = require "os" local fs = require "nixio.fs" local nutil = require "nixio.util" local type = type local b, form --Remove the spaces in the string function trim(str) --return (string.gsub(str, "^%s*(.-)%s*$", "%1")) return (string.gsub(str, "%s+", "")) end -- Evaluate given shell glob pattern and return a table containing all matching function glob(...) local iter, code, msg = fs.glob(...) if iter then return nutil.consume(iter) else return nil, code, msg end end -- Checks wheather the given path exists and points to a regular file. function isfile(filename) return fs.stat(filename, "type") == "reg" end -- Get the last modification time of given file path in Unix epoch format. function mtime(path) return fs.stat(path, "mtime") end local stat_tr = { reg = "regular", dir = "directory", lnk = "link", chr = "character device", blk = "block device", fifo = "fifo", sock = "socket" } -- Get information about given file or directory. function stat(path, key) local data, code, msg = fs.stat(path) if data then data.mode = data.modestr data.type = stat_tr[data.type] or "?" end return key and data and data[key] or data, code, msg end --Set default upload path local ROOT_PTNAME = trim(luci.sys.exec("df / | tail -n1 | awk '{print $1}' | awk -F '/' '{print $3}'")) if ROOT_PTNAME then if (string.find(ROOT_PTNAME, "mmcblk[0-4]p[1-4]")) then local EMMC_NAME = trim(luci.sys.exec("echo " .. ROOT_PTNAME .. " | awk '{print substr($1, 1, length($1)-2)}'")) upload_path = trim("/mnt/" .. EMMC_NAME .. "p4/") elseif (string.find(ROOT_PTNAME, "[hsv]d[a-z]")) then local EMMC_NAME = trim(luci.sys.exec("echo " .. ROOT_PTNAME .. " | awk '{print substr($1, 1, length($1)-1)}'")) upload_path = trim("/mnt/" .. EMMC_NAME .. "4/") else upload_path = "/tmp/upload/" end else upload_path = "/tmp/upload/" end --Clear the version check log luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_plugin.log && sync >/dev/null 2>&1") luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_kernel.log && sync >/dev/null 2>&1") --SimpleForm for Update OpenWrt firmware/kernel b = SimpleForm("upload", nil) b.title = translate("Upload") local des_content = translate("Update plugins first, then update the kernel or firmware.") local des_content = des_content .. "<br />" .. translate("After uploading [Firmware], [Kernel], [IPK] or [Backup Config], the operation buttons will be displayed.") b.description = des_content b.reset = false b.submit = false s = b:section(SimpleSection, "", "") o = s:option(FileUpload, "") o.template = "amlogic/other_upload" um = s:option(DummyValue, "", nil) um.template = "amlogic/other_dvalue" local dir, fd dir = upload_path fs.mkdir(dir) luci.http.setfilehandler( function(meta, chunk, eof) if not fd then if not meta then return end if meta and chunk then fd = nixio.open(dir .. meta.file, "w") end if not fd then um.value = translate("Create upload file error.") .. " Error Info: " .. trim(upload_path .. meta.file) return end end if chunk and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil um.value = translate("File saved to") .. trim(upload_path .. meta.file) end end ) if luci.http.formvalue("upload") then local f = luci.http.formvalue("ulfile") if #f <= 0 then um.value = translate("No specify upload file.") end end local function getSizeStr(size) local i = 0 local byteUnits = { ' kB', ' MB', ' GB', ' TB' } repeat size = size / 1024 i = i + 1 until (size <= 1024) return string.format("%.1f", size) .. byteUnits[i] end local inits, attr = {} for i, f in ipairs(glob(trim(upload_path .. "*"))) do attr = stat(f) itisfile = isfile(f) if attr and itisfile then inits[i] = {} inits[i].name = fs.basename(f) inits[i].mtime = os.date("%Y-%m-%d %H:%M:%S", attr.mtime) inits[i].modestr = attr.modestr inits[i].size = getSizeStr(attr.size) inits[i].remove = 0 inits[i].ipk = false --Check whether the openwrt firmware file -- openwrt_s905d_v5.10.16_2021.05.31.1958.img.gz if (string.lower(string.sub(fs.basename(f), -7, -1)) == ".img.gz") then openwrt_firmware_file = true end -- openwrt_s905d_n1_R21.7.15_k5.4.134-flippy-62+o.img.xz if (string.lower(string.sub(fs.basename(f), -7, -1)) == ".img.xz") then openwrt_firmware_file = true end -- openwrt_s905d_n1_R21.7.15_k5.13.2-flippy-62+.7z if (string.lower(string.sub(fs.basename(f), -3, -1)) == ".7z") then openwrt_firmware_file = true end -- openwrt_s905d_n1_R21.7.15_k5.13.2-flippy-62+.img if (string.lower(string.sub(fs.basename(f), -4, -1)) == ".img") then openwrt_firmware_file = true end --Check whether the three kernel files -- boot-5.10.16-flippy-53+.tar.gz if (string.lower(string.sub(fs.basename(f), 1, 5)) == "boot-") then boot_file = true end -- dtb-amlogic-5.10.16-flippy-53+.tar.gz if (string.lower(string.sub(fs.basename(f), 1, 4)) == "dtb-") then dtb_file = true end -- modules-5.10.16-flippy-53+.tar.gz if (string.lower(string.sub(fs.basename(f), 1, 8)) == "modules-") then modules_file = true end --Check whether the backup file -- openwrt_config.tar.gz if (string.lower(string.sub(fs.basename(f), 1, -1)) == "openwrt_config.tar.gz") then backup_config_file = true end end end --SimpleForm for Upload file list form = SimpleForm("filelist", translate("Upload file list"), nil) form.reset = false form.submit = false description_info = "" luci.sys.exec("echo '' > /tmp/amlogic/amlogic_check_upfiles.log && sync >/dev/null 2>&1") if backup_config_file then description_info = description_info .. translate("There are config file in the upload directory, and you can restore the config. ") end if boot_file and dtb_file and modules_file then description_info = description_info .. translate("There are kernel files in the upload directory, and you can replace the kernel.") luci.sys.exec("echo 'kernel' > /tmp/amlogic/amlogic_check_upfiles.log && sync >/dev/null 2>&1") end if openwrt_firmware_file then description_info = description_info .. translate("There are openwrt firmware file in the upload directory, and you can update the openwrt.") luci.sys.exec("echo 'firmware' > /tmp/amlogic/amlogic_check_upfiles.log && sync >/dev/null 2>&1") end if description_info ~= "" then form.description = ' <span style="color: green"><b> Tip: ' .. description_info .. ' </b></span> ' end tb = form:section(Table, inits) nm = tb:option(DummyValue, "name", translate("File name")) mt = tb:option(DummyValue, "mtime", translate("Modify time")) ms = tb:option(DummyValue, "modestr", translate("Attributes")) sz = tb:option(DummyValue, "size", translate("Size")) btnrm = tb:option(Button, "remove", translate("Remove")) btnrm.render = function(self, section, scope) self.inputstyle = "remove" Button.render(self, section, scope) end btnrm.write = function(self, section) local v = fs.unlink(trim(upload_path .. fs.basename(inits[section].name))) if v then table.remove(inits, section) end return v end function IsConfigFile(name) name = name or "" local config_file = string.lower(string.sub(name, 1, -1)) return config_file == "openwrt_config.tar.gz" end -- Check if the file is a known package type (.ipk or .apk) function IsPackageFile(name) name = name or "" local lname = string.lower(name) return string.sub(lname, -4) == ".ipk" or string.sub(lname, -4) == ".apk" end --Add Button for *.ipk btnis = tb:option(Button, "ipk", translate("Install")) btnis.template = "amlogic/other_button" btnis.render = function(self, section, scope) if not inits[section] then return false end if IsPackageFile(inits[section].name) then scope.display = "" self.inputtitle = translate("Install") elseif IsConfigFile(inits[section].name) then scope.display = "" self.inputtitle = translate("Restore") else scope.display = "none" end self.inputstyle = "apply" Button.render(self, section, scope) end btnis.write = function(self, section) local file_to_install = inits[section].name local full_path = upload_path .. file_to_install if IsPackageFile(file_to_install) then local r = "" local install_cmd = "" -- Check for opkg first if luci.sys.call("command -v opkg >/dev/null") == 0 then install_cmd = string.format('opkg --force-reinstall install %s', full_path) r = luci.sys.exec(install_cmd) -- If opkg is not found, check for apk elseif luci.sys.call("command -v apk >/dev/null") == 0 then -- NOTE: --allow-untrusted is required for local packages install_cmd = string.format('apk add --force-overwrite --allow-untrusted %s', full_path) r = luci.sys.exec(install_cmd) -- If neither is found else r = "Error: Neither 'opkg' nor 'apk' package manager found on the system." end -- Clean LuCI cache after installation luci.sys.exec("rm -rf /tmp/luci-indexcache /tmp/luci-modulecache/* >/dev/null 2>&1") -- Display the result message -- We add a message to prompt the user to refresh the page to see changes. local result_msg = r .. "<br/><b>" .. translate("Please refresh the page to see the changes.") .. "</b>" form.description = string.format('<span style="color: red">%s</span>', result_msg) elseif IsConfigFile(inits[section].name) then form.description = ' <span style="color: green"><b> ' .. translate("Tip: The config is being restored, and it will automatically restart after completion.") .. ' </b></span> ' luci.sys.exec("chmod +x /usr/sbin/openwrt-backup 2>/dev/null") luci.sys.exec("/usr/sbin/openwrt-backup -r > /tmp/amlogic/amlogic.log && sync 2>/dev/null") end end --SimpleForm for Check upload files form:section(SimpleSection).template = "amlogic/other_upfiles" return b, form
281677160/openwrt-package
5,066
luci-app-amlogic/luasrc/model/cbi/amlogic/amlogic_config.lua
--Remove the spaces in the string function trim(str) --return (string.gsub(str, "^%s*(.-)%s*$", "%1")) return (string.gsub(str, "%s+", "")) end --Auto-complete node local check_config_amlogic = luci.sys.exec("uci get amlogic.@amlogic[0].amlogic_firmware_repo 2>/dev/null") or "" if (trim(check_config_amlogic) == "") then luci.sys.exec("uci delete amlogic.@amlogic[0] 2>/dev/null") luci.sys.exec("uci set amlogic.config='amlogic' 2>/dev/null") luci.sys.exec("uci commit amlogic 2>/dev/null") end b = Map("amlogic") b.title = translate("Plugin Settings") local des_content = translate("You can customize the github.com download repository of OpenWrt files and kernels in [Online Download Update].") local des_content = des_content .. "<br />" .. translate("Tip: The same files as the current OpenWrt system's BOARD (such as rock5b) and kernel (such as 5.10) will be downloaded.") b.description = des_content o = b:section(NamedSection, "config", "amlogic") o.anonymouse = true --1.Set OpenWrt Firmware Repository mydevice = o:option(DummyValue, "mydevice", translate("Current Device:")) mydevice.description = translate("Display the PLATFORM classification of the device.") mydevice_platfrom = trim(luci.sys.exec("cat /etc/flippy-openwrt-release 2>/dev/null | grep PLATFORM | awk -F'=' '{print $2}' | grep -oE '(amlogic|rockchip|allwinner|qemu)'")) or "Unknown" mydevice.default = "PLATFORM: " .. mydevice_platfrom mydevice.rmempty = false --2.Set OpenWrt Firmware Repository firmware_repo = o:option(Value, "amlogic_firmware_repo", translate("Download repository of OpenWrt:")) firmware_repo.description = translate("Set the download repository of the OpenWrt files on github.com in [Online Download Update].") firmware_repo.default = "https://github.com/breakingbadboy/OpenWrt" firmware_repo.rmempty = false --3.Set OpenWrt Releases's Tag Keywords firmware_tag = o:option(Value, "amlogic_firmware_tag", translate("Keywords of Tags in Releases:")) firmware_tag.description = translate("Set the keywords of Tags in Releases of github.com in [Online Download Update].") firmware_tag.default = "ARMv8" firmware_tag.rmempty = false --4.Set OpenWrt Firmware Suffix firmware_suffix = o:option(Value, "amlogic_firmware_suffix", translate("Suffix of OpenWrt files:")) firmware_suffix.description = translate("Set the suffix of the OpenWrt in Releases of github.com in [Online Download Update].") firmware_suffix:value(".7z", translate(".7z")) firmware_suffix:value(".zip", translate(".zip")) firmware_suffix:value(".img.gz", translate(".img.gz")) firmware_suffix:value(".img.xz", translate(".img.xz")) firmware_suffix.default = ".img.gz" firmware_suffix.rmempty = false --5.Set OpenWrt Kernel DownLoad Path kernel_path = o:option(Value, "amlogic_kernel_path", translate("Download path of OpenWrt kernel:")) kernel_path.description = translate("Set the download path of the kernel in the github.com repository in [Online Download Update].") kernel_path:value("https://github.com/breakingbadboy/OpenWrt") kernel_path:value("https://github.com/ophub/kernel") kernel_path.default = "https://github.com/breakingbadboy/OpenWrt" kernel_path.rmempty = false --6.Set kernel version branch kernel_branch = o:option(Value, "amlogic_kernel_branch", translate("Set version branch:")) kernel_branch.description = translate("Set the version branch of the openwrt firmware and kernel selected in [Online Download Update].") kernel_branch:value("5.4", translate("5.4")) kernel_branch:value("5.10", translate("5.10")) kernel_branch:value("5.15", translate("5.15")) kernel_branch:value("6.1", translate("6.1")) kernel_branch:value("6.6", translate("6.6")) kernel_branch:value("6.12", translate("6.12")) local default_kernel_branch = luci.sys.exec("uname -r | grep -oE '^[1-9].[0-9]{1,3}'") kernel_branch.default = trim(default_kernel_branch) kernel_branch.rmempty = false --7.Restore configuration firmware_config = o:option(Flag, "amlogic_firmware_config", translate("Keep config update:")) firmware_config.description = translate("Set whether to keep the current config during [Online Download Update] and [Manually Upload Update].") firmware_config.default = "1" firmware_config.rmempty = false --8.Write bootloader write_bootloader = o:option(Flag, "amlogic_write_bootloader", translate("Auto write bootloader:")) write_bootloader.description = translate("[Recommended choice] Set whether to auto write bootloader during install and update OpenWrt.") write_bootloader.default = "0" write_bootloader.rmempty = false --9.Set the file system type of the shared partition shared_fstype = o:option(ListValue, "amlogic_shared_fstype", translate("Set the file system type:")) shared_fstype.description = translate("[Default ext4] Set the file system type of the shared partition (/mnt/mmcblk*p4) when install OpenWrt.") shared_fstype:value("ext4", translate("ext4")) shared_fstype:value("f2fs", translate("f2fs")) shared_fstype:value("btrfs", translate("btrfs")) shared_fstype:value("xfs", translate("xfs")) shared_fstype.default = "ext4" shared_fstype.rmempty = false return b
2929004360/ruoyi-sign
1,119
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfProcNodeVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.flowable.engine.task.Comment; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 工作流节点元素视图对象 * * @author fengcheng * @createTime 2022/9/11 22:04 */ @Data public class WfProcNodeVo implements Serializable { /** * 流程ID */ private String procDefId; /** * 活动ID */ private String activityId; /** * 活动名称 */ private String activityName; /** * 活动类型 */ private String activityType; /** * 活动耗时 */ private String duration; /** * 执行人Id */ private Long assigneeId; /** * 执行人名称 */ private String assigneeName; /** * 候选执行人 */ private String candidate; /** * 任务意见 */ private List<Comment> commentList; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 结束时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date endTime; }
2929004360/ruoyi-sign
1,143
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfModelExportVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 流程模型对象导出VO * * @author fengcheng */ @Data @NoArgsConstructor public class WfModelExportVo implements Serializable { private static final long serialVersionUID = 1L; /** * 模型ID */ @Excel(name = "模型ID") private String modelId; /** * 模型Key */ @Excel(name = "模型Key") private String modelKey; /** * 模型名称 */ @Excel(name = "模型名称") private String modelName; /** * 分类编码 */ @Excel(name = "分类编码") private String category; /** * 流程分类 */ @Excel(name = "流程分类") private String categoryName; /** * 模型版本 */ @Excel(name = "模型版本") private Integer version; /** * 模型描述 */ @Excel(name = "模型描述") private String description; /** * 创建时间 */ @Excel(name = "创建时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; }
281677160/openwrt-package
4,802
luci-app-amlogic/luasrc/model/cbi/amlogic/amlogic_backup.lua
--Copyright: https://github.com/coolsnowwolf/luci/tree/master/applications/luci-app-filetransfer --Extended support: https://github.com/ophub/luci-app-amlogic --Function: Download files local io = require "io" local os = require "os" local fs = require "nixio.fs" local b, c, x -- Checks wheather the given path exists and points to a directory. function isdirectory(dirname) return fs.stat(dirname, "type") == "dir" end -- Check if a file or directory exists function file_exists(path) local file = io.open(path, "rb") if file then file:close() end return file ~= nil end --SimpleForm for Backup Config b = SimpleForm("backup", nil) b.title = translate("Backup Firmware Config") b.description = translate("Backup OpenWrt config (openwrt_config.tar.gz). Use this file to restore the config in [Manually Upload Update].") b.reset = false b.submit = false s = b:section(SimpleSection, "", "") -- Button for customize backup list my = s:option(Button, "customize", translate("Edit List:")) my.template = "amlogic/other_button" my.render = function(self, section, scope) self.section = true scope.display = "" self.inputtitle = translate("Open List") self.inputstyle = "save" Button.render(self, section, scope) end my.write = function(self, section, scope) local handle = io.popen("[[ -s /etc/amlogic_backup_list.conf ]] || sed -n \"/BACKUP_LIST='/,/.*'$/p\" /usr/sbin/openwrt-backup | sed -e \"s/BACKUP_LIST=\\(.*\\)/\\1/; s/'//g; s/\\\\\\\\//g; s/ //g\" > /etc/amlogic_backup_list.conf 2>/dev/null") handle:close() luci.http.redirect(luci.dispatcher.build_url("admin", "system", "amlogic", "backuplist")) end -- Button for download backup config o = s:option(Button, "download", translate("Backup Config:")) o.template = "amlogic/other_button" um = s:option(DummyValue, "", nil) um.template = "amlogic/other_dvalue" o.render = function(self, section, scope) self.section = true scope.display = "" self.inputtitle = translate("Download Backup") self.inputstyle = "save" Button.render(self, section, scope) end o.write = function(self, section, scope) local x = luci.sys.exec("chmod +x /usr/sbin/openwrt-backup 2>/dev/null") local r = luci.sys.exec("/usr/sbin/openwrt-backup -b > /tmp/amlogic/amlogic.log && sync 2>/dev/null") local sPath, sFile, fd, block sPath = "/.reserved/openwrt_config.tar.gz" sFile = fs.basename(sPath) if isdirectory(sPath) then fd = io.popen('tar -C "%s" -cz .' % { sPath }, "r") sFile = sFile .. ".tar.gz" else fd = nixio.open(sPath, "r") end if not fd then um.value = translate("Couldn't open file:") .. sPath return else um.value = translate("The file Will download automatically.") .. sPath end luci.http.header('Content-Disposition', 'attachment; filename="%s"' % { sFile }) luci.http.prepare_content("application/octet-stream") while true do block = fd:read(nixio.const.buffersize) if (not block) or (#block == 0) then break else luci.http.write(block) end end fd:close() luci.http.close() end -- Button for restore backup list r = s:option(Button, "restore", translate("Restore Backup:")) r.template = "amlogic/other_button" r.render = function(self, section, scope) self.section = true scope.display = "" self.inputtitle = translate("Upload Backup") self.inputstyle = "save" Button.render(self, section, scope) end r.write = function(self, section, scope) luci.http.redirect(luci.dispatcher.build_url("admin", "system", "amlogic", "upload")) end -- SimpleForm for Create Snapshot c = SimpleForm("snapshot", nil) c.title = translate("Snapshot Management") c.description = translate("Create a snapshot of the current system configuration, or restore to a snapshot.") c.reset = false c.submit = false d = c:section(SimpleSection, "", nil) w = d:option(Button, "create_snapshot", "") w.template = "amlogic/other_button" w.render = function(self, section, scope) self.section = true scope.display = "" self.inputtitle = translate("Create Snapshot") self.inputstyle = "save" Button.render(self, section, scope) end w.write = function(self, section, scope) local x = luci.sys.exec("btrfs subvolume snapshot -r /etc /.snapshots/etc-" .. os.date("%m.%d.%H%M%S") .. " 2>/dev/null && sync") luci.http.redirect(luci.dispatcher.build_url("admin", "system", "amlogic", "backup")) end w = d:option(TextValue, "snapshot_list", nil) w.template = "amlogic/other_snapshot" --KVM virtual machine switching dual partition if file_exists("/boot/efi/EFI/BOOT/grub.cfg.prev") then x = SimpleForm("kvm", nil) x.title = translate("KVM dual system switching") x.description = translate("You can freely switch between KVM dual partitions, using OpenWrt systems in different partitions.") x.reset = false x.submit = false x:section(SimpleSection).template = "amlogic/other_kvm" end return b, c, x
281677160/openwrt-package
3,568
luci-app-amlogic/luasrc/model/cbi/amlogic/amlogic_armcpu.lua
--Copyright: https://github.com/coolsnowwolf/luci/tree/master/applications/luci-app-cpufreq --Planner: https://github.com/unifreq/openwrt_packit --Extended support: https://github.com/ophub/luci-app-amlogic --Function: Support multi-core local mp --Remove the spaces in the string function trim(str) --return (string.gsub(str, "^%s*(.-)%s*$", "%1")) return (string.gsub(str, "%s+", "")) end --split function string.split(e, t) e = tostring(e) t = tostring(t) if (t == '') then return false end local a, o = 0, {} for i, t in function() return string.find(e, t, a, true) end do table.insert(o, string.sub(e, a, i - 1)) a = t + 1 end table.insert(o, string.sub(e, a)) return o end --Auto-complete node local check_config_settings = luci.sys.exec("uci get amlogic.@settings[0].governor0 2>/dev/null") or "" if (trim(check_config_settings) == "") then luci.sys.exec("uci delete amlogic.@settings[0] 2>/dev/null") luci.sys.exec("uci set amlogic.armcpu='settings' 2>/dev/null") luci.sys.exec("uci commit amlogic 2>/dev/null") end mp = Map("amlogic") mp.title = translate("CPU Freq Settings") mp.description = translate("Set CPU Scaling Governor to Max Performance or Balance Mode") s = mp:section(NamedSection, "armcpu", "settings") s.anonymouse = true local cpu_policys = luci.sys.exec("ls /sys/devices/system/cpu/cpufreq | grep -E 'policy[0-9]{1,3}' | xargs") or "policy0" policy_array = string.split(cpu_policys, " ") for tt, policy_name in ipairs(policy_array) do --Dynamic tab, automatically changes according to the number of cores, begin ------ policy_name = tostring(trim(policy_name)) policy_id = tostring(trim(string.gsub(policy_name, "policy", ""))) tab_name = policy_name tab_id = tostring(trim("tab" .. policy_id)) cpu_freqs = nixio.fs.readfile(trim("/sys/devices/system/cpu/cpufreq/" .. policy_name .. "/scaling_available_frequencies")) or "100000" cpu_freqs = string.sub(cpu_freqs, 1, -3) cpu_governors = nixio.fs.readfile(trim("/sys/devices/system/cpu/cpufreq/" .. policy_name .. "/scaling_available_governors")) or "performance" cpu_governors = string.sub(cpu_governors, 1, -3) freq_array = string.split(cpu_freqs, " ") governor_array = string.split(cpu_governors, " ") s:tab(tab_id, tab_name) tab_core_type = s:taboption(tab_id, DummyValue, trim("core_type" .. policy_id), translate("Microarchitectures:")) tab_core_type.default = luci.sys.exec("cat /sys/devices/system/cpu/cpu" .. policy_id .. "/uevent | grep -E '^OF_COMPATIBLE_0.*' | tr -d 'OF_COMPATIBLE_0=' | xargs") or "Unknown" tab_core_type.rmempty = false governor = s:taboption(tab_id, ListValue, trim("governor" .. policy_id), translate("CPU Scaling Governor:")) for t, e in ipairs(governor_array) do if e ~= "" then governor:value(e, translate(e, string.upper(e))) end end governor.default = "schedutil" governor.rmempty = false minfreq = s:taboption(tab_id, ListValue, trim("minfreq" .. policy_id), translate("Min Freq:")) for t, e in ipairs(freq_array) do if e ~= "" then minfreq:value(e) end end minfreq.default = "500000" minfreq.rmempty = false maxfreq = s:taboption(tab_id, ListValue, trim("maxfreq" .. policy_id), translate("Max Freq:")) for t, e in ipairs(freq_array) do if e ~= "" then maxfreq:value(e) end end maxfreq.default = "1512000" maxfreq.rmempty = false --Dynamic tab, automatically changes according to the number of cores, end ------ end -- Apply the settings to the system function mp.on_after_commit(self) luci.sys.exec("(sleep 2 && /etc/init.d/amlogic start) >/dev/null 2>&1 &") end return mp
2929004360/ruoyi-sign
993
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfClaimTaskExportVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 待签流程对象导出VO * * @author fengcheng */ @Data @NoArgsConstructor public class WfClaimTaskExportVo implements Serializable { private static final long serialVersionUID = 1L; /** * 任务编号 */ @Excel(name = "任务编号") private String taskId; /** * 流程名称 */ @Excel(name = "流程名称") private String procDefName; /** * 任务节点 */ @Excel(name = "任务节点") private String taskName; /** * 流程版本 */ @Excel(name = "流程版本") private int procDefVersion; /** * 流程发起人名称 */ @Excel(name = "流程发起人名称") private String startUserName; /** * 接收时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "接收时间") private Date createTime; }
2929004360/ruoyi-sign
1,261
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfOwnTaskExportVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 我拥有流程对象导出VO * * @author fengcheng */ @Data @NoArgsConstructor public class WfOwnTaskExportVo implements Serializable { private static final long serialVersionUID = 1L; /** * 流程实例ID */ @Excel(name = "流程编号") private String procInsId; /** * 流程名称 */ @Excel(name = "流程名称") private String procDefName; /** * 流程类别 */ @Excel(name = "流程类别") private String category; /** * 流程版本 */ @Excel(name = "流程版本") private int procDefVersion; /** * 提交时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "提交时间") private Date createTime; /** * 流程状态 */ @Excel(name = "流程状态") private String status; /** * 任务耗时 */ @Excel(name = "任务耗时") private String duration; /** * 当前节点 */ @Excel(name = "当前节点") private String taskName; /** * 任务完成时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date finishTime; }
281677160/openwrt-package
1,404
luci-app-amlogic/luasrc/model/cbi/amlogic/amlogic_backuplist.lua
local fs = require "nixio.fs" local backup_list_conf = "/etc/amlogic_backup_list.conf" -- Delete all spaces and tabs at the beginning of the line, and the unified line break is \n function remove_spaces(value) local lines = {} for line in value:gmatch("[^\r\n]+") do line = line:gsub("^%s*", "") if line ~= "" then table.insert(lines, line) end end value = table.concat(lines, "\n") value = value:gsub("[\r\n]+", "\n") return value end -- Remove backslash at the end of each line function remove_backslash_at_end(value) local lines = {} for line in value:gmatch("[^\r\n]+") do line = line:gsub("%s*\\%s*$", "") table.insert(lines, line) end return table.concat(lines, "\n") end local f = SimpleForm("customize", translate("Backup Configuration - Custom List"), translate("Write one configuration item per line, and directories should end with a /.")) local o = f:field(Value, "_custom") o.template = "cbi/tvalue" o.rows = 30 function o.cfgvalue(self, section) local readconf = fs.readfile(backup_list_conf) local value = remove_spaces(readconf) local value = remove_backslash_at_end(value) return value end function o.write(self, section, value) local value = remove_spaces(value) local value = remove_backslash_at_end(value) fs.writefile(backup_list_conf, value) luci.http.redirect(luci.dispatcher.build_url("admin", "system", "amlogic", "backup")) end return f
2929004360/ruoyi-sign
1,058
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfFormVo.java
package com.ruoyi.flowable.domain.vo; import com.ruoyi.common.annotation.Excel; import com.ruoyi.flowable.base.BaseEntity; import lombok.Data; /** * 流程分类视图对象 * * @author fengcheng * @createTime 2022/3/7 22:07 */ @Data public class WfFormVo extends BaseEntity { private static final long serialVersionUID = 1L; /** * 表单主键 */ @Excel(name = "表单ID") private String formId; /** * 用户id */ private Long userId; /** * 部门id */ private Long deptId; /** * 创建人 */ @Excel(name = "创建人") private String userName; /** * 部门名称 */ @Excel(name = "部门名称") private String deptName; /** * 使用类型(1=本级使用,2=本下级使用) */ @Excel(name = "使用类型", readConverterExp = "1=本级使用,2=本下级使用") private String type; /** * 表单名称 */ @Excel(name = "表单名称") private String formName; /** * 表单内容 */ @Excel(name = "表单内容") private String content; /** * 备注 */ @Excel(name = "备注") private String remark; }
2929004360/ruoyi-sign
1,653
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfModelVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.flowable.domain.WfModelPermission; import lombok.Data; import java.util.Date; import java.util.List; /** * 流程模型视图对象 * * @author fengcheng * @createTime 2022/6/21 9:16 */ @Data public class WfModelVo { /** * 模型ID */ private String modelId; /** * 菜单id */ private String menuId; /** * 菜单名称 */ private String menuName; /** * 模型名称 */ private String modelName; /** * 模型Key */ private String modelKey; /** * 分类编码 */ private String category; /** * 版本 */ private Integer version; /** * 表单类型 */ private String formType; /** * 表单主键 */ private String formId; /** * 表单名称 */ private String formName; /** * 流程配置 */ private String processConfig; /** * 模板id */ private String modelTemplateId; /** * 表单查看路由 */ private String formCustomViewPath; /** * 表单提交路由 */ private String formCustomCreatePath; /** * 流程图标 */ private String icon; /** * 模型描述 */ private String description; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 流程xml */ private String bpmnXml; /** * 表单内容 */ private String content; /** * 使用人 */ private List<WfModelPermission> selectUserList; /** * 使用部门 */ private List<WfModelPermission> selectDeptList; }
2929004360/ruoyi-sign
1,211
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfFinishedTaskExportVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 已办流程对象导出VO * * @author fengcheng */ @Data @NoArgsConstructor public class WfFinishedTaskExportVo implements Serializable { private static final long serialVersionUID = 1L; /** * 任务编号 */ @Excel(name = "任务编号") private String taskId; /** * 流程名称 */ @Excel(name = "流程名称") private String procDefName; /** * 任务节点 */ @Excel(name = "任务节点") private String taskName; /** * 流程版本 */ @Excel(name = "流程版本") private int procDefVersion; /** * 流程发起人名称 */ @Excel(name = "流程发起人") private String startUserName; /** * 接收时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "接收时间") private Date createTime; /** * 审批时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "审批时间") private Date finishTime; /** * 任务耗时 */ @Excel(name = "任务耗时") private String duration; }
281677160/openwrt-package
14,076
luci-app-amlogic/po/zh_Hans/amlogic.po
msgid "" msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Project-Id-Version: \n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Last-Translator: https://github.com/ophub/luci-app-amlogic \n" "Language-Team: \n" "MIME-Version: 1.0\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_Hans\n" "X-Generator: Poedit 2.3.1\n" msgid "Choose local file:" msgstr "选择本地文件:" msgid "Couldn't open file:" msgstr "无法打开文件:" msgid "The file Will download automatically." msgstr "文件将自动下载" msgid "Create upload file error." msgstr "创建上传文件失败。" msgid "Download" msgstr "下载" msgid "Download file" msgstr "下载文件" msgid "File name" msgstr "文件名" msgid "File saved to" msgstr "文件保存到" msgid "FileTransfer" msgstr "文件传输" msgid "Install" msgstr "安装" msgid "Attributes" msgstr "属性" msgid "Modify time" msgstr "修改时间" msgid "No specify upload file." msgstr "未指定上传文件。" msgid "Path on Route:" msgstr "路由根目录:" msgid "Remove" msgstr "移除" msgid "Size" msgstr "大小" msgid "Upload" msgstr "上传" msgid "Upload file list" msgstr "上传文件列表" msgid "There are config file in the upload directory, and you can restore the config. " msgstr "上传文件列表中有配置文件,你可以恢复配置。" msgid "There are kernel files in the upload directory, and you can replace the kernel." msgstr "上传文件列表中有内核文件,你可以升级内核。" msgid "There are openwrt firmware file in the upload directory, and you can update the openwrt." msgstr "上传文件列表中有 OpenWrt 固件文件,你可以升级 OpenWrt。" msgid "Update plugins first, then update the kernel or firmware." msgstr "首先更新插件,再更新内核或固件。" msgid "After uploading [Firmware], [Kernel], [IPK] or [Backup Config], the operation buttons will be displayed." msgstr "当上传 [固件文件],[内核文件],[IPK文件],[配置文件] 后,将自动显示相关操作按钮。" msgid "After uploading firmware (.img/.img.gz/.img.xz/.7z suffix) or kernel files (3 kernel files), the update button will be displayed." msgstr "当上传文件列表中有 OpenWrt 固件(.img/.img.gz/.img.xz/.7z 后缀)或内核文件(3个内核文件)时,将自动显示相关操作按钮。" msgid "Amlogic Service" msgstr "晶晨宝盒" msgid "Restore Config / Replace OpenWrt Kernel" msgstr "恢复配置 / 升级 OpenWrt 内核" msgid "Manually Upload Update" msgstr "手动上传更新" msgid "Install OpenWrt" msgstr "安装 OpenWrt" msgid "Select the device model:" msgstr "选择设备型号:" msgid "Select List" msgstr "选择列表" msgid "Enter the dtb file name" msgstr "输入自定义 dtb 文件名" msgid "Enter the soc name:" msgstr "输入自定义 soc 名称:" msgid "Enter the uboot_overload name:" msgstr "输入自定义 uboot_overload 名称:" msgid "Invalid value." msgstr "无效值" msgid "Install OpenWrt:" msgstr "安装 OpenWrt:" msgid "Install OpenWrt to EMMC, Please select the device model, Or enter the dtb file name." msgstr "将 OpenWrt 安装到 EMMC,请选择设备型号,或输入 dtb 文件名。" msgid "Tip: Writing is in progress, and it will automatically restart after completion." msgstr "提示:正在写入,完成后将自动重启。" msgid "You have chosen:" msgstr "你选择了:" msgid "Start install?" msgstr "开始安装吗?" msgid "Installing..." msgstr "正在安装..." msgid "Install Failed" msgstr "安装失败" msgid "Successful Install" msgstr "安装成功" msgid "Update" msgstr "升级" msgid "Updating..." msgstr "正在更新..." msgid "Update Failed" msgstr "更新失败" msgid "Successful Update" msgstr "更新成功" msgid "Update OpenWrt firmware" msgstr "升级 OpenWrt 固件" msgid "kernel" msgstr "内核" msgid "Replace OpenWrt Kernel" msgstr "更换 OpenWrt 内核" msgid "Tip: The kernel is being replaced, and it will automatically restart after completion." msgstr "提示:正在替换内核,完成后将自动重启。" msgid "Supports management of Amlogic s9xxx, Allwinner (V-Plus Cloud), and Rockchip (BeikeYun, Chainedbox L1 Pro) boxes." msgstr "支持对晶晨 s9xxx 系列(斐讯N1、HK1等),全志(微加云),以及瑞芯微(贝壳云、我家云)的盒子进行在线管理。" msgid "Supported functions:" msgstr "支持的功能:" msgid "Provide services such as install to EMMC, Update Firmware and Kernel, Backup and Recovery Config, Snapshot management, etc." msgstr "支持将 OpenWrt 系统写入 EMMC、升级固件与内核,备份与恢复自定义配置,快照管理等功能。" msgid "Supported Boxes:" msgstr "支持的盒子:" msgid "Amlogic s922x --- [ Beelink, Beelink-Pro, Ugoos-AM6-Plus, ODROID-N2, Khadas-VIM3, Ali-CT2000 ]" msgstr "晶晨 s922x --- [ Beelink, Beelink-Pro, Ugoos-AM6-Plus, ODROID-N2, Khadas-VIM3, Ali-CT2000 ]" msgid "Amlogic s905x3 -- [ X96-Max+, HK1-Box, H96-Max-X3, Ugoos-X3, TX3, X96-Air, A95XF3-Air ]" msgstr "晶晨 s905x3 -- [ X96-Max+, HK1-Box, H96-Max-X3, Ugoos-X3, TX3, X96-Air, A95XF3-Air ]" msgid "Amlogic s905x2 -- [ X96Max-4G, X96Max-2G, MECOOL-KM3-4G, Tanix-Tx5-Max, A95X-F2 ]" msgstr "晶晨 s905x2 -- [ X96Max-4G, X96Max-2G, MECOOL-KM3-4G, Tanix-Tx5-Max, A95X-F2 ]" msgid "Amlogic s912 ---- [ H96-Pro-Plus, Octopus-Planet, A1, A2, Z6-Plus, TX92, X92, TX8-MAX, TX9-Pro ]" msgstr "晶晨 s912 ---- [ H96-Pro-Plus, 章鱼星球, A1, A2, Z6-Plus, TX92, X92, TX8-MAX, TX9-Pro ]" msgid "Amlogic s905x --- [ HG680P, B860H, TBee, T95, TX9, XiaoMI-3S, X96 ]" msgstr "晶晨 s905x --- [ 烽火HG680, 中兴B860H, TBee, T95, TX9, XiaoMI-3S, X96 ]" msgid "Amlogic s905w --- [ X96-Mini, TX3-Mini, W95, X96W/FunTV, MXQ-Pro-4K ]" msgstr "晶晨 s905w --- [ X96-Mini, TX3-Mini, W95, X96W/FunTV, MXQ-Pro-4K ]" msgid "Amlogic s905d --- [ Phicomm-N1, MECOOL-KI-Pro, SML-5442TW ]" msgstr "晶晨 s905d --- [ 斐讯-N1, MECOOL-KI-Pro, SML-5442TW ]" msgid "Amlogic s905l --- [ UNT402A, M201-S ]" msgstr "晶晨 s905l --- [ UNT402A, M201-S ]" msgid "Amlogic s905l2 -- [ MGV2000, MGV3000, Wojia-TV-IPBS9505, M301A, E900v21E ]" msgstr "晶晨 s905l2 -- [ MGV2000, MGV3000, Wojia-TV-IPBS9505, M301A, E900v21E ]" msgid "Amlogic s905l3 -- [ CM211-1, CM311-1, HG680-LC, M401A, UNT400G1, UNT402A, ZXV10-BV310 ]" msgstr "晶晨 s905l3 -- [ CM211-1, CM311-1, HG680-LC, M401A, UNT400G1, UNT402A, ZXV10-BV310 ]" msgid "Amlogic s905l3a - [ E900V22C/D, CM311-1a-YST, M401A, M411A, UNT403A, UNT413A, IP112H ]" msgstr "晶晨 s905l3a - [ E900V22C/D, CM311-1a-YST, M401A, M411A, UNT403A, UNT413A, IP112H ]" msgid "Amlogic s905l3b - [ CM211-1, CM311-1, E900V22D, E900V21E, E900V22E, M302A/M304A ]" msgstr "晶晨 s905l3b - [ CM211-1, CM311-1, E900V22D, E900V21E, E900V22E, M302A/M304A ]" msgid "Amlogic s905 ---- [ Beelink-Mini-MX-2G, Sunvell-T95M, MXQ-Pro+4K, SumaVision-Q5 ]" msgstr "晶晨 s905 ---- [ Beelink-Mini-MX-2G, Sunvell-T95M, MXQ-Pro+4K, SumaVision-Q5 ]" msgid "Allwinner H6 ---- [ V-Plus Cloud ]" msgstr "全志 H6 ------ [ 微加云 ]" msgid "Rockchip -------- [ BeikeYun, L1-Pro, FastRhino R66S/R68S, Radxa 5B/E25 ]" msgstr "瑞芯微 ------- [ 贝壳云, 我家云, 电犀牛R66S/R68S, 瑞莎5B/E25 ]" msgid "Used in KVM ----- [ Can be used in KVM virtual machine of Armbian system. ]" msgstr "KVM 中使用 --- [ 可以在 Armbian 系统的 KVM 虚拟机中使用。 ]" msgid "KVM dual system switching" msgstr "KVM 双系统切换" msgid "You can freely switch between KVM dual partitions, using OpenWrt systems in different partitions." msgstr "您可以在 KVM 双分区之间自由切换,使用不同分区中的 OpenWrt 系统。" msgid "Switch System" msgstr "切换系统" msgid "System is switching..." msgstr "系统切换中..." msgid "Waiting for system switching..." msgstr "等待系统完成切换..." msgid "System switchover succeeded, restarting..." msgstr "系统切换成功,正在重启..." msgid "Are you sure you want to switch systems?" msgstr "你确定要切换系统吗?" msgid "Install Ipk" msgstr "安装Ipk" msgid "Plugin Settings" msgstr "插件设置" msgid "Backup Firmware Config" msgstr "备份固件配置" msgid "Backup Config:" msgstr "备份配置:" msgid "Download Backup" msgstr "下载备份" msgid "Backup OpenWrt config (openwrt_config.tar.gz). Use this file to restore the config in [Manually Upload Update]." msgstr "备份当前 OpenWrt 的相关配置信息(openwrt_config.tar.gz)。使用此文件可在 [手动上传更新] 中恢复配置。" msgid "Edit List:" msgstr "编辑列表:" msgid "Open List" msgstr "打开列表" msgid "Backup Configuration - Custom List" msgstr "备份配置 - 自定义列表" msgid "Write one configuration item per line, and directories should end with a /." msgstr "每行写一个配置项,目录需要以/结尾。" msgid "Restore Backup:" msgstr "恢复备份:" msgid "Upload Backup" msgstr "上传备份" msgid "Restore" msgstr "恢复" msgid "Restore Config" msgstr "恢复配置" msgid "Restore configuration" msgstr "还原配置" msgid "Config File" msgstr "配置文件" msgid "Tip: The config is being restored, and it will automatically restart after completion." msgstr "提示:正在还原配置,完成后将自动重启。" msgid "Snapshot Management" msgstr "快照管理" msgid "Create Snapshot" msgstr "创建快照" msgid "Creating..." msgstr "正在创建" msgid "Created successfully" msgstr "创建成功" msgid "Creation failed" msgstr "创建失败" msgid "Initialize Snapshot" msgstr "初始化快照" msgid "Update Snapshot" msgstr "更新点快照" msgid "Restore Snap" msgstr "还原快照" msgid "Restoring..." msgstr "正在还原" msgid "Restore Failed" msgstr "还原失败" msgid "Successfully Restored" msgstr "还原成功" msgid "Delete Snap" msgstr "删除快照" msgid "You selected a snapshot:" msgstr "你选择了快照:" msgid "Confirm delete?" msgstr "确定删除吗?" msgid "Confirm recovery and restart OpenWrt?" msgstr "确定恢复并重启 OpenWrt 吗?" msgid "Delete Failed" msgstr "删除失败" msgid "Successfully Deleted" msgstr "删除成功" msgid "Create a snapshot of the current system configuration, or restore to a snapshot." msgstr "创建当前系统配置的快照,或还原到某个快照。" msgid "Currently OpenWrt does not support the snapshot function." msgstr "当前 OpenWrt 不支持快照功能。" msgid "Please use this plugin to reinstall or upgrade OpenWrt to enable the snapshot function." msgstr "请使用本插件重新安装或升级 OpenWrt 开启快照功能。" msgid "Deleting..." msgstr "正在删除..." msgid "Online Download Update" msgstr "在线下载更新" msgid "Config Source" msgstr "配置来源" msgid "You can customize the github.com download repository of OpenWrt files and kernels in [Online Download Update]." msgstr "您可以自定义 [在线下载和更新] 中 OpenWrt 固件和内核的 github.com 下载仓库。" msgid "Tip: The same files as the current OpenWrt system's BOARD (such as rock5b) and kernel (such as 5.10) will be downloaded." msgstr "提示:将下载与当前 OpenWrt 系统的 BOARD(如:rock5b)和内核(如:5.10)相同的文件。" msgid "Download repository of OpenWrt:" msgstr "OpenWrt 固件的下载仓库:" msgid "Set the download repository of the OpenWrt files on github.com in [Online Download Update]." msgstr "设置 [在线下载更新] 中 github.com 的 OpenWrt 固件的下载仓库。" msgid "Keywords of Tags in Releases:" msgstr "Releases 里 Tags 的关键字:" msgid "Set the keywords of Tags in Releases of github.com in [Online Download Update]." msgstr "设置 [在线下载更新] 中 github.com 的 Releases 里 Tags 的关键字。" msgid "Suffix of OpenWrt files:" msgstr "OpenWrt 固件的后缀:" msgid "Set the suffix of the OpenWrt in Releases of github.com in [Online Download Update]." msgstr "设置 [在线下载更新] 中 github.com 的 Releases 里 OpenWrt 固件的后缀。" msgid "Download path of OpenWrt kernel:" msgstr "OpenWrt 内核的下载路径:" msgid "Set the download path of the kernel in the github.com repository in [Online Download Update]." msgstr "设置 [在线下载更新] 中 github.com 仓库里内核的下载路径。" msgid "Set version branch:" msgstr "设置版本分支:" msgid "Set the version branch of the openwrt firmware and kernel selected in [Online Download Update]." msgstr "设置 [在线下载更新] 时 OpenWrt 固件与内核所选用的版本分支。" msgid "Keep config update:" msgstr "保留配置更新:" msgid "Set whether to keep the current config during [Online Download Update] and [Manually Upload Update]." msgstr "设置是否在 [在线下载更新] 和 [手动上传更新] 时保留当前的配置。" msgid "Auto write bootloader:" msgstr "自动写入 bootloader:" msgid "[Recommended choice] Set whether to auto write bootloader during install and update OpenWrt." msgstr "[推荐选择] 设置在安装和更新 OpenWrt 固件时是否自动写入 bootloader 文件。" msgid "Set the file system type:" msgstr "设置文件系统类型:" msgid "[Default ext4] Set the file system type of the shared partition (/mnt/mmcblk*p4) when install OpenWrt." msgstr "[默认 ext4] 设置安装 OpenWrt 时共享分区 (/mnt/mmcblk*p4) 的文件系统类型。" msgid "Save Config:" msgstr "保存配置:" msgid "Save" msgstr "保存" msgid "Check All Components Update" msgstr "插件和内核检查更新" msgid "Provide OpenWrt Firmware, Kernel and Plugin online check, download and update service." msgstr "提供 OpenWrt 固件,内核和插件在线检查,下载和更新服务。" msgid "Only update Amlogic Service" msgstr "仅更新晶晨宝盒" msgid "Update system kernel only" msgstr "仅更新系统内核" msgid "Complete system update" msgstr "完整更新全系统" msgid "Check Update" msgstr "检查更新" msgid "Checking..." msgstr "正在检查更新..." msgid "Current Version" msgstr "当前版本" msgid "Latest Version" msgstr "最新版本" msgid "Rescue Kernel" msgstr "救援内核" msgid "When a kernel update fails and causes the OpenWrt system to be unbootable, the kernel can be restored by mutual recovery from eMMC/NVMe/sdX." msgstr "当内核更新失败造成 OpenWrt 系统无法启动时,可以从 eMMC/NVME/sdX 相互恢复内核。" msgid "Rescue the original system kernel" msgstr "救援原系统内核" msgid "Rescuing..." msgstr "正在救援..." msgid "Current Device:" msgstr "当前设备:" msgid "Display the PLATFORM classification of the device." msgstr "显示设备的 PLATFORM 分类。" msgid "Update plugins first, then update the kernel or firmware. More options can be configured in [Plugin Settings]." msgstr "首先更新插件,再更新内核或固件。更多选项可以在插件设置中配置。" msgid "Collecting data..." msgstr "正在收集数据…" msgid "Check All Components Update" msgstr "插件和内核检查更新" msgid "Server Logs" msgstr "操作日志" msgid "Display the execution log of the current operation." msgstr "显示当前操作的执行日志。" msgid "Stop Refresh Log" msgstr "停止刷新" msgid "Start Refresh Log" msgstr "开始刷新" msgid "Clean Log" msgstr "清理日志" msgid "Download Log" msgstr "下载日志" msgid "CPU Settings" msgstr "CPU 设置" msgid "CPU Freq" msgstr "CPU 性能优化调节" msgid "CPU Freq Settings" msgstr "CPU 性能优化调节设置" msgid "Set CPU Scaling Governor to Max Performance or Balance Mode" msgstr "设置路由器的 CPU 性能模式(高性能/均衡省电)" msgid "CPU Scaling Governor:" msgstr "CPU 调速器:" msgid "ondemand" msgstr "Ondemand 自动平衡模式" msgid "performance" msgstr "Performance 高性能模式" msgid "schedutil" msgstr "Schedutil 敏捷调度器模式" msgid "CPU Freq from 48000 to 716000 (Khz)" msgstr "CPU 频率范围为 48000 到 716000 (Khz)" msgid "Min Freq:" msgstr "最小频率:" msgid "Max Freq:" msgstr "最大频率:" msgid "CPU Switching Threshold:" msgstr "CPU 切换频率触发阈值:" msgid "Kernel make a decision on whether it should increase the frequency (%)" msgstr "当 CPU 占用率超过 (%) 的情况下触发内核切换频率" msgid "CPU Switching Sampling rate:" msgstr "CPU 切换周期:" msgid "The sampling rate determines how frequently the governor checks to tune the CPU (ms)" msgstr "CPU 检查切换的周期 (ms) 。注意:过于频繁的切换频率会引起网络延迟抖动" msgid "Microarchitectures:" msgstr "微架构:" msgid "Loading" msgstr "载入中" msgid "PowerOff" msgstr "关机" msgid "Shut down your router device." msgstr "关闭你的路由器设备。" msgid "Perform PowerOff" msgstr "执行关机" msgid "Are you sure you want to shut down?" msgstr "你确定要关机吗?" msgid "Device is shutting down..." msgstr "设备正在关机..." msgid "Waiting for the device to shut down..." msgstr "等待设备关机..." msgid "The device has been turned off" msgstr "设备已经关机"
2929004360/ruoyi-sign
990
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfTodoTaskExportVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 待办流程对象导出VO * * @author fengcheng */ @Data @NoArgsConstructor public class WfTodoTaskExportVo implements Serializable { private static final long serialVersionUID = 1L; /** * 任务编号 */ @Excel(name = "任务编号") private String taskId; /** * 流程名称 */ @Excel(name = "流程名称") private String procDefName; /** * 任务节点 */ @Excel(name = "任务节点") private String taskName; /** * 流程版本 */ @Excel(name = "流程版本") private int procDefVersion; /** * 流程发起人名称 */ @Excel(name = "流程发起人") private String startUserName; /** * 接收时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "接收时间") private Date createTime; }
2929004360/ruoyi-sign
2,438
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfTaskVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.flowable.domain.dto.WfCommentDto; import lombok.Data; import org.flowable.engine.task.Comment; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 工作流任务视图对象 * * @author fengcheng * @createTime 2022/3/10 00:12 */ @Data public class WfTaskVo implements Serializable { /** * 任务编号 */ private String taskId; /** * 任务父级编号 */ private String parentTaskId; /** * 任务名称 */ private String taskName; /** * 任务Key */ private String taskDefKey; /** * 任务执行人Id */ private Long assigneeId; /** * 部门名称 */ @Deprecated private String deptName; /** * 流程发起人部门名称 */ @Deprecated private String startDeptName; /** * 任务执行人名称 */ private String assigneeName; /** * 流程发起人Id */ private Long startUserId; /** * 流程发起人名称 */ private String startUserName; /** * 流程类型 */ private String category; /** * 流程变量信息 */ private Object procVars; /** * 局部变量信息 */ private Object taskLocalVars; /** * 流程部署编号 */ private String deployId; /** * 流程ID */ private String procDefId; /** * 流程key */ private String procDefKey; /** * 流程定义名称 */ private String procDefName; /** * 流程定义内置使用版本 */ private int procDefVersion; /** * 流程实例ID */ private String procInsId; /** * 历史流程实例ID */ private String hisProcInsId; /** * 任务耗时 */ private String duration; /** * 任务意见 */ private WfCommentDto comment; /** * 任务意见 */ private List<Comment> commentList; /** * 候选执行人 */ private String candidate; /** * 任务创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 任务完成时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date finishTime; /** * 流程状态 */ private String processStatus; /** * 表单类型 */ private String formType; /** * 表单查看路径 */ private String formViewPath; /** * 表单创建路径 */ private String formCreatePath; /** * 业务id */ private String businessId; }
2929004360/ruoyi-sign
1,503
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfDefinitionVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import java.util.Date; /** * 流程定义视图对象 workflow_definition * * @author fengcheng * @date 2022-01-17 */ @Data public class WfDefinitionVo { private static final long serialVersionUID = 1L; /** * 流程定义ID */ @Excel(name = "流程定义ID") private String definitionId; /** * 流程名称 */ @Excel(name = "流程名称") private String processName; /** * 流程Key */ @Excel(name = "流程Key") private String processKey; /** * 分类编码 */ @Excel(name = "分类编码") private String category; /** * 版本 */ @Excel(name = "版本") private Integer version; /** * 表单ID */ @Excel(name = "表单ID") private Long formId; /** * 表单名称 */ @Excel(name = "表单名称") private String formName; /** * 部署ID */ @Excel(name = "部署ID") private String deploymentId; /** * 流程是否暂停(true:挂起 false:激活 ) */ @Excel(name = "流程是否挂起", readConverterExp = "true=挂起,false=激活") private Boolean suspended; /** * 部署时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Excel(name = "部署时间") private Date deploymentTime; /** * 流程icon */ private String icon; /** * 表单类型 */ private String formType; /** * 表单创建路径 */ private String formCreatePath; }
2929004360/ruoyi-sign
1,315
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfDeployVo.java
package com.ruoyi.flowable.domain.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.ruoyi.common.annotation.Excel; import lombok.Data; import java.util.Date; /** * 流程部署视图对象 * * @author fengcheng * @date 2022-06-30 */ @Data public class WfDeployVo { private static final long serialVersionUID = 1L; /** * 流程定义ID */ @Excel(name = "流程定义ID") private String definitionId; /** * 流程名称 */ @Excel(name = "流程名称") private String processName; /** * 流程Key */ @Excel(name = "流程Key") private String processKey; /** * 分类编码 */ @Excel(name = "分类编码") private String category; /** * 版本 */ private Integer version; /** * 表单ID */ @Excel(name = "表单ID") private Long formId; /** * 表单名称 */ @Excel(name = "表单名称") private String formName; /** * 部署ID */ @Excel(name = "部署ID") private String deploymentId; /** * 流程定义状态: 1:激活 , 2:中止 */ @Excel(name = "流程定义状态",readConverterExp = "1=激活,2=中止") private Boolean suspended; /** * 部署时间 */ @Excel(name = "部署时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date deploymentTime; /** * 流程图标 */ private String icon; }
2929004360/ruoyi-sign
1,115
ruoyi-flowable/src/main/java/com/ruoyi/flowable/domain/vo/WfDetailVo.java
package com.ruoyi.flowable.domain.vo; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.flowable.core.FormConf; import com.ruoyi.flowable.domain.WfRoamHistorical; import lombok.Data; import java.util.List; import java.util.Map; /** * 流程详情视图对象 * * @author fengcheng * @createTime 2022/8/7 15:01 */ @Data public class WfDetailVo { /** * 任务表单信息 */ private FormConf taskFormData; /** * 历史流程节点信息 */ private List<WfProcNodeVo> historyProcNodeList; /** * 历史流程审批节点信息 */ private List<WfRoamHistorical> historyApproveProcNodeList; /** * 流程表单列表 */ private List<FormConf> processFormList; /** * 显示按钮组 */ private List<String> buttonList; /** * 流程XML */ private String bpmnXml; /** * 任务追踪视图 */ private WfViewerVo flowViewer; /** * 是否存在任务表单信息 * * @return true:存在;false:不存在 */ public Boolean isExistTaskForm() { return ObjectUtil.isNotEmpty(this.taskFormData); } /** * 业务流程 */ private Map<String, Object> businessProcess; }
2929004360/ruoyi-sign
914
ruoyi-framework/src/main/java/com/ruoyi/framework/datasource/DynamicDataSourceContextHolder.java
package com.ruoyi.framework.datasource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 数据源切换处理 * * @author ruoyi */ public class DynamicDataSourceContextHolder { public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); /** * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 */ private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); /** * 设置数据源的变量 */ public static void setDataSourceType(String dsType) { log.info("切换到{}数据源", dsType); CONTEXT_HOLDER.set(dsType); } /** * 获得数据源的变量 */ public static String getDataSourceType() { return CONTEXT_HOLDER.get(); } /** * 清空数据源变量 */ public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } }
281677160/openwrt-package
19,662
luci-app-amlogic/root/usr/sbin/openwrt-kernel
#!/bin/bash #==================================================================================== # # Function: Update the kernel for OpenWrt (Amlogic s9xxx, Allwinner, Rockchip) # Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit # Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic # # Support the kernel: boot-*.tar.gz, dtb-*.tar.gz, modules-*.tar.gz # It is recommended to install MAINLINE_UBOOT for kernel versions above 5.10.y # openwrt-kernel ${AUTO_MAINLINE_UBOOT} # E.g: openwrt-kernel yes # openwrt-kernel no # #================================== Functions list ================================== # # error_msg : Output error message # get_textoffset : Get kernel TEXT_OFFSET # init_var : Initialize all variables # check_kernel : Check kernel files list # chech_files_same : Check file consistency # restore_kernel : Restore current kernel # update_kernel : Update the kernel # update_uboot : Update the uboot # #============================== Set default parameters ============================== # # Receive one-key command related parameters AUTO_MAINLINE_UBOOT="no" # Set the release check file release_file="/etc/flippy-openwrt-release" # #==================================================================================== # Encountered a serious error, abort the script execution error_msg() { echo -e "[Error] ${1}" exit 1 } # Get the partition name of the root file system get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Get kernel TEXT_OFFSET, For u-boot.ext and u-boot.emmc get_textoffset() { boot_tgz_file="${1}" vmlinuz_name="${2}" K510="1" temp_dir="$(mktemp -d)" ( cd ${temp_dir} tar -xf "${boot_tgz_file}" "${vmlinuz_name}" ) # With TEXT_OFFSET patch is [ 0108 ], without TEXT_OFFSET patch is [ 0000 ] [[ "$(hexdump -n 15 -x "${temp_dir}/${vmlinuz_name}" 2>/dev/null | head -n 1 | awk '{print $7}')" == "0108" ]] && K510="0" } init_var() { # Receive one-key command related parameters [[ "${1}" == "yes" ]] && AUTO_MAINLINE_UBOOT="yes" # Check dependencies [[ -n "$(busybox which tar)" ]] || error_msg "Missing [ tar ] in OpenWrt firmware, unable to update kernel" # Check release file if [[ -s "${release_file}" ]]; then source "${release_file}" PLATFORM="${PLATFORM}" MODEL_ID="${MODEL_ID}" UBOOT_OVERLOAD="${UBOOT_OVERLOAD}" MAINLINE_UBOOT="${MAINLINE_UBOOT}" ANDROID_UBOOT="${ANDROID_UBOOT}" SOC="${SOC}" LOCK_KERNEL="${LOCK_KERNEL}" else error_msg "${release_file} file is missing!" fi [[ -n "${PLATFORM}" ]] || error_msg "Missing ${PLATFORM} value in ${release_file} file." # Define supported platforms support_platform=("allwinner" "rockchip" "amlogic" "qemu-aarch64") [[ -n "$(echo "${support_platform[@]}" | grep -w "${PLATFORM}")" ]] || error_msg "[ ${PLATFORM} ] is not supported." # Set /boot/vmlinuz-* replication names for different SoCs MYBOOT_VMLINUZ="$(ls -l /boot/*Image 2>/dev/null | awk '{print $9}' | head -n 1)" MYBOOT_VMLINUZ="${MYBOOT_VMLINUZ##*/}" [[ -n "${MYBOOT_VMLINUZ}" ]] || error_msg "Failed to get Image name: [ ${MYBOOT_VMLINUZ} ]" # Find the partition where root is located ROOT_PTNAME="$(get_root_partition_name)" # Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats case "${ROOT_PTNAME}" in mmcblk?p[1-9]) EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')" PARTITION_NAME="p" ;; [hsv]d[a-z][1-9]) EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}')" PARTITION_NAME="" ;; nvme?n?p[1-9]) EMMC_NAME="$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}')" PARTITION_NAME="p" ;; *) error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!" ;; esac P4_PATH="/mnt/${EMMC_NAME}${PARTITION_NAME}4" # Move kernel related files to the ${P4_PATH} directory mv -f /tmp/upload/* ${P4_PATH} 2>/dev/null # Current device model MYDEVICE_NAME="$(cat /proc/device-tree/model | tr -d '\000')" [[ "${PLATFORM}" == "qemu-aarch64" ]] && MYDEVICE_NAME="KVM Virtual Machine" echo -e "Current device: ${MYDEVICE_NAME} [ ${PLATFORM} ], Use in [ ${EMMC_NAME} ]" sync && echo "" } # Check kernel files list check_kernel() { cd ${P4_PATH} # Determine custom kernel filename kernel_boot="$(ls boot-*.tar.gz 2>/dev/null | head -n 1)" kernel_name="${kernel_boot:5:-7}" KERNEL_VERSION="$(echo ${kernel_name} | grep -oE '^[1-9].[0-9]{1,3}.[0-9]+')" echo -e "Kernel name: ${kernel_name}" # check if kernel is locked if [ -n "${LOCK_KERNEL}" ]; then if [ "${LOCK_KERNEL}" != "${kernel_name}" ]; then if ! echo "${kernel_name}" | grep -E '^5.10.\d+-.*?rk35.*?$' >/dev/null; then error_msg "The kernel version is locked to [ ${LOCK_KERNEL} ], but your kernel is [ ${kernel_name} ]. " fi fi fi # Check if the file is added with TEXT_OFFSET patch get_textoffset "${P4_PATH}/${kernel_boot}" "vmlinuz-${kernel_name}" echo -e "K510 [ ${K510} ]" if [[ "${PLATFORM}" == "amlogic" && "${K510}" -eq "1" ]]; then [[ -n "${UBOOT_OVERLOAD}" && -f "/boot/${UBOOT_OVERLOAD}" ]] || error_msg "The UBOOT_OVERLOAD file is missing and cannot be update." fi # Check the sha256sums file sha256sums_file="sha256sums" sha256sums_check="1" [[ -s "${sha256sums_file}" && -n "$(cat ${sha256sums_file})" ]] || sha256sums_check="0" [[ -n "$(busybox which sha256sum)" ]] || sha256sums_check="0" [[ "${sha256sums_check}" -eq "1" ]] && echo -e "Enable sha256sum checking..." # Loop check file i="1" if [[ "${PLATFORM}" == "qemu-aarch64" ]]; then kernel_list=("boot" "modules") else kernel_list=("boot" "dtb-${PLATFORM}" "modules") fi for kernel_file in ${kernel_list[*]}; do # Set check filename tmp_file="${kernel_file}-${kernel_name}.tar.gz" # Check if file exists [[ -s "${tmp_file}" ]] || error_msg "The [ ${kernel_file} ] file is missing." # Check if the file sha256sum is correct if [[ "${sha256sums_check}" -eq "1" ]]; then tmp_sha256sum="$(sha256sum "${tmp_file}" | awk '{print $1}')" tmp_checkcode="$(cat ${sha256sums_file} | grep ${tmp_file} | awk '{print $1}')" [[ "${tmp_sha256sum}" == "${tmp_checkcode}" ]] || error_msg "${tmp_file}: sha256sum verification failed." echo -e "(${i}/3) [ ${tmp_file} ] file sha256sum check same." fi let i++ done sync && echo "" } # Check the consistency of amlogic device files chech_files_same() { i="0" max_try="5" while [[ "${i}" -le "${max_try}" ]]; do if [[ "$(sha256sum "${1}" | awk '{print $1}')" == "$(sha256sum "${2}" | awk '{print $1}')" ]]; then echo "" && break else cp -f ${1} ${2} i="$((i + 1))" fi done [[ "${i}" -gt "${max_try}" ]] && echo "God, it's different after ${max_try} copies: [ ${1} ]" } # Restore the kernel when the update fails restore_kernel() { ( cd /boot rm -rf \ config-${kernel_name} \ System.map-${kernel_name} \ initrd.img-${kernel_name} \ uInitrd-${kernel_name} \ vmlinuz-${kernel_name} \ initrd.img \ uInitrd \ zImage \ Image \ vmlinuz \ dtb* 2>/dev/null tar -xzf /tmp/boot-backup.tar.gz 2>/dev/null ) error_msg "Kernel update failed and has been reverted." } # Update the kernel update_kernel() { local cur_kernel_name=$(uname -r) local boot_fstype=$(df -T /boot | tail -n1 | awk '{print $2}') echo -e "Start unpacking the kernel..." # 01. for /boot five files # Backup the current_kernel ( cd /boot tar -czf /tmp/boot-backup.tar.gz \ config-${cur_kernel_name} \ System.map-${cur_kernel_name} \ initrd.img-${cur_kernel_name} \ uInitrd-${cur_kernel_name} \ vmlinuz-${cur_kernel_name} \ initrd.img \ uInitrd \ zImage \ Image \ vmlinuz \ dtb* 2>/dev/null rm -rf \ config-${cur_kernel_name} \ System.map-${cur_kernel_name} \ initrd.img-${cur_kernel_name} \ uInitrd-${cur_kernel_name} \ vmlinuz-${cur_kernel_name} \ initrd.img \ uInitrd \ zImage \ Image \ vmlinuz \ dtb* 2>/dev/null ) # Extract the new kernel tar -xf ${P4_PATH}/boot-${kernel_name}.tar.gz -C /boot # Check if the file exists local valid_files if [[ "${PLATFORM}" == "qemu-aarch64" ]]; then valid_files="vmlinuz-${kernel_name} initrd.img-${kernel_name} config-${kernel_name} System.map-${kernel_name}" rm -f /boot/uInitrd* else valid_files="vmlinuz-${kernel_name} uInitrd-${kernel_name} config-${kernel_name} System.map-${kernel_name}" # wxy-oect: MODEL_ID numbers r304 and r306, require special handling of uInitrd [[ "${MODEL_ID}" =~ ^(r304|r306)$ ]] || rm -f /boot/initrd.img* fi for f in ${valid_files}; do [[ -f "/boot/${f}" ]] || restore_kernel; done # Check if the files are the same ( cd /boot if [[ "${PLATFORM}" == "qemu-aarch64" ]]; then ln -sf initrd.img-${kernel_name} initrd.img ln -sf vmlinuz-${kernel_name} ${MYBOOT_VMLINUZ} elif [[ "$boot_fstype" == "vfat" ]]; then cp -f uInitrd-${kernel_name} uInitrd [[ -z "$(chech_files_same uInitrd-${kernel_name} uInitrd)" ]] || restore_kernel cp -f vmlinuz-${kernel_name} ${MYBOOT_VMLINUZ} [[ -z "$(chech_files_same vmlinuz-${kernel_name} ${MYBOOT_VMLINUZ})" ]] || restore_kernel else ln -sf uInitrd-${kernel_name} uInitrd ln -sf vmlinuz-${kernel_name} ${MYBOOT_VMLINUZ} fi # wxy-oect: MODEL_ID numbers r304 and r306, require special handling of uInitrd [[ "${MODEL_ID}" =~ ^(r304|r306)$ ]] && ln -sf initrd.img-${kernel_name} uInitrd ) echo -e "(1/3) Unpacking [ boot-${kernel_name}.tar.gz ] done." if [[ "${PLATFORM}" == "qemu-aarch64" ]]; then echo -e "(2/3) skip unpack dtb files." else # 02. for /boot/dtb/${PLATFORM}/* if [[ "${boot_fstype}" == "vfat" ]]; then (cd /boot && mkdir -p dtb/${PLATFORM}) else (cd /boot && mkdir -p dtb-${kernel_name}/${PLATFORM} && ln -sf dtb-${kernel_name} dtb) fi tar -xf ${P4_PATH}/dtb-${PLATFORM}-${kernel_name}.tar.gz -C /boot/dtb/${PLATFORM} [[ "$(ls /boot/dtb/${PLATFORM} -l 2>/dev/null | grep "^-" | wc -l)" -ge "1" ]] || error_msg "/boot/dtb/${PLATFORM} file is missing." echo -e "(2/3) Unpacking [ dtb-${PLATFORM}-${kernel_name}.tar.gz ] done." fi # 03. for /lib/modules/* rm -rf /lib/modules/* tar -xf ${P4_PATH}/modules-${kernel_name}.tar.gz -C /lib/modules ( cd /lib/modules/${kernel_name} rm -f *.ko find ./ -type f -name '*.ko' -exec ln -s {} ./ \; sync && sleep 3 x=$(ls *.ko -l 2>/dev/null | grep "^l" | wc -l) [[ "${x}" -eq "0" ]] && error_msg "Error *.ko Files not found." ) echo -e "(3/3) Unpacking [ modules-${kernel_name}.tar.gz ] done." # Delete kernel tmpfiles rm -f ${P4_PATH}/*-${kernel_name}.tar.gz rm -f ${P4_PATH}/sha256sums sync && echo "" } # Update the uboot update_uboot() { # Only amlogic SoCs needs to be updated if [[ "${PLATFORM}" == "amlogic" ]]; then # Copy u-boot.ext and u-boot.emmc if [[ "${K510}" -eq "1" && -n "${UBOOT_OVERLOAD}" && -f "/boot/${UBOOT_OVERLOAD}" ]]; then [[ ! -f "/boot/u-boot.ext" ]] && cp -f "/boot/${UBOOT_OVERLOAD}" /boot/u-boot.ext && chmod +x /boot/u-boot.ext [[ ! -f "/boot/u-boot.emmc" ]] && cp -f "/boot/u-boot.ext" /boot/u-boot.emmc && chmod +x /boot/u-boot.emmc echo -e "The ${UBOOT_OVERLOAD} file copy is complete." elif [[ "${K510}" -eq "0" ]]; then rm -f "/boot/u-boot.ext" "/boot/u-boot.emmc" fi # Write Mainline bootloader if [[ -f "${MAINLINE_UBOOT}" && "${AUTO_MAINLINE_UBOOT}" == "yes" ]]; then echo -e "Write Mainline bootloader: [ ${MAINLINE_UBOOT} ] to [ /dev/${EMMC_NAME} ]" dd if=${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=1 count=442 conv=fsync dd if=${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=512 skip=1 seek=1 conv=fsync echo -e "The MAINLINE_UBOOT file write is complete." fi fi # Update release file sed -i "s|^KERNEL_VERSION=.*|KERNEL_VERSION='${kernel_name}'|g" ${release_file} 2>/dev/null # Update banner file sed -i "s| Kernel.*| Kernel: ${kernel_name}|g" /etc/banner 2>/dev/null sync && echo "" } # Rescue the kernel sos_kernel() { echo -e "Start rescuing kernel..." # Supports specifying disks, such as: [ openwrt-kernel -s mmcblk1 ] box_disk="${2}" if [[ -n "${box_disk}" ]]; then # Format the disk names box_disk="${box_disk//\/dev\//}" # Check if the disk exists [[ -b "/dev/${box_disk}" ]] || error_msg "The specified disk [ ${box_disk} ] does not exist." # Check if the disk is the same as the current system disk [[ "${box_disk}" == "${EMMC_NAME}" ]] && error_msg "The specified disk [ ${box_disk} ] is the same as the current system disk [ ${EMMC_NAME} ]." echo -e "The device name of the specified disk: [ ${box_disk} ]" else # Find emmc disk, first find emmc containing boot0 partition box_disk="$(lsblk -l -o NAME | grep -oE '(mmcblk[0-9]?|nvme[0-9]?n[0-9]?|[hsv]d[a-z])' | grep -vE ^${EMMC_NAME} | sort -u | head -n 1)" # Check if disk exists [[ -z "${box_disk}" ]] && error_msg "Unable to locate the storage requiring rescue." echo -e "The device name of the target disk: [ ${box_disk} ]" fi rescue_disk="/dev/${box_disk}" echo -e "The current OpenWrt is running on [ /dev/${EMMC_NAME} ], and the target disk for restoration is [ ${rescue_disk} ]." # Create a temporary mount directory umount ${P4_PATH}/bootfs 2>/dev/null umount ${P4_PATH}/rootfs 2>/dev/null rm -rf ${P4_PATH}/bootfs ${P4_PATH}/rootfs 2>/dev/null mkdir -p ${P4_PATH}/{bootfs/,rootfs/} && sync [[ "${?}" -ne "0" ]] && error_msg "Failed to create temporary mount directory [ ${P4_PATH} ]" # Mount target bootfs partition [[ "${box_disk}" =~ ^([hsv]d[a-z]) ]] && rescue_disk_partition_name="" || rescue_disk_partition_name="p" mount ${rescue_disk}${rescue_disk_partition_name}1 ${P4_PATH}/bootfs [[ "${?}" -ne "0" ]] && error_msg "mount ${rescue_disk}${PARTITION_NAME}1 failed!" echo -e "The [ ${rescue_disk}${rescue_disk_partition_name}1 ] partition is mounted on [ ${P4_PATH}/bootfs ]." # Search uuid file if [[ -f "${P4_PATH}/bootfs/uEnv.txt" ]]; then search_file="uEnv.txt" elif [[ -f "${P4_PATH}/bootfs/armbianEnv.txt" ]]; then search_file="armbianEnv.txt" elif [[ -f "${P4_PATH}/bootfs/extlinux/extlinux.conf" ]]; then search_file="extlinux/extlinux.conf" else error_msg "The [ uEnv.txt, armbianEnv.txt, extlinux/extlinux.conf ] file does not exist, stop rescuing." fi # Get the target partition uuid and rootfs target_parttion_uuid="$(grep '=UUID=' ${P4_PATH}/bootfs/${search_file} | sed -n 's/.*=UUID=\([a-f0-9-]*\).*/\1/p')" [[ -z "${target_parttion_uuid}" ]] && error_msg "The [ ${search_file} ] file does not contain the UUID value." target_rootfs="$(blkid | grep ${target_parttion_uuid} | awk -F':' '{print $1;}')" [[ -z "${target_rootfs}" ]] && error_msg "The [ ${target_parttion_uuid} ] UUID does not exist in the system." # Mount target rootfs partition mount ${target_rootfs} ${P4_PATH}/rootfs [[ "${?}" -ne "0" ]] && error_msg "mount ${rescue_disk}${PARTITION_NAME}2 failed!" echo -e "The [ ${target_rootfs} ] partition is mounted on [ ${P4_PATH}/rootfs ]." # Identify the current kernel files kernel_signature="$(uname -r)" # 01. For /boot files [[ -d "${P4_PATH}/bootfs" ]] && { cd ${P4_PATH}/bootfs rm -rf config-* initrd.img-* System.map-* vmlinuz-* uInitrd* *Image dtb* u-boot.ext u-boot.emmc [[ -f "/boot/u-boot.ext" ]] && { cp -f /boot/u-boot.ext . cp -f /boot/u-boot.ext u-boot.emmc chmod +x u-boot.ext u-boot.emmc } cp -rf /boot/{*-${kernel_signature},uInitrd,*Image,dtb} . [[ "${?}" -ne "0" ]] && error_msg "(1/2) [ boot ] kernel files rescue failed." echo -e "(1/2) [ boot ] kernel files rescue succeeded." [[ -f "/boot/emmc_autoscript.cmd" ]] && cp -f /boot/emmc_autoscript.cmd . [[ -f "/boot/emmc_autoscript" ]] && cp -f /boot/emmc_autoscript . [[ -f "/boot/s905_autoscript.cmd" ]] && cp -f /boot/s905_autoscript.cmd . [[ -f "/boot/s905_autoscript" ]] && cp -f /boot/s905_autoscript . } || error_msg "(1/2) The [ ${P4_PATH}/bootfs ] folder does not exist, stop rescuing." # 02. For /lib/modules/${kernel_signature} [[ -d "${P4_PATH}/rootfs/lib/modules" ]] && { cd ${P4_PATH}/rootfs/lib/modules rm -rf * cp -rf /lib/modules/${kernel_signature} . [[ "${?}" -ne "0" ]] && error_msg "(2/2) [ modules ] kernel files rescue failed." echo -e "(2/2) [ modules ] kernel files rescue succeeded." } || error_msg "(2/2) The [ ${P4_PATH}/rootfs/lib/modules ] folder does not exist, stop rescuing." # Unmount the emmc partition cd ${P4_PATH} umount -f ${P4_PATH}/bootfs [[ "${?}" -ne "0" ]] && error_msg "Failed to umount [ ${P4_PATH}/bootfs ]" umount -f ${P4_PATH}/rootfs [[ "${?}" -ne "0" ]] && error_msg "Failed to umount [ ${P4_PATH}/rootfs ]" # Remove the temporary mount directory rm -rf ${P4_PATH}/bootfs ${P4_PATH}/rootfs sync && echo "" } echo -e "Welcome to the OpenWrt Kernel Management Tool." # Operation environment check [[ -x "/usr/sbin/openwrt-kernel" ]] || error_msg "Please grant execution permission: chmod +x /usr/sbin/openwrt-kernel" # Execute relevant functions based on the options if [[ "${@}" =~ ^-s(\s)* ]]; then # Initialize all variables init_var "${@}" # Start rescuing the kernel sos_kernel "${@}" # Kernel restore successful sync && sleep 3 echo -e "Kernel rescue successful, please remove the disk and restart the OpenWrt system." exit 0 else # Initialize all variables init_var "${@}" # Check kernel files list check_kernel # Update the kernel update_kernel # Update the uboot update_uboot # Kernel update successful sync && sleep 3 echo "Successfully updated, automatic restarting..." reboot exit 0 fi
2929004360/ruoyi-sign
2,957
ruoyi-framework/src/main/java/com/ruoyi/framework/websocket/WebSocketUsers.java
package com.ruoyi.framework.websocket; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * websocket 客户端用户集 * * @author ruoyi */ public class WebSocketUsers { /** * WebSocketUsers 日志控制器 */ private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class); /** * 用户集 */ private static Map<String, Session> USERS = new ConcurrentHashMap<String, Session>(); /** * 存储用户 * * @param key 唯一键 * @param session 用户信息 */ public static void put(String key, Session session) { USERS.put(key, session); } /** * 移除用户 * * @param session 用户信息 * * @return 移除结果 */ public static boolean remove(Session session) { String key = null; boolean flag = USERS.containsValue(session); if (flag) { Set<Map.Entry<String, Session>> entries = USERS.entrySet(); for (Map.Entry<String, Session> entry : entries) { Session value = entry.getValue(); if (value.equals(session)) { key = entry.getKey(); break; } } } else { return true; } return remove(key); } /** * 移出用户 * * @param key 键 */ public static boolean remove(String key) { LOGGER.info("\n 正在移出用户 - {}", key); Session remove = USERS.remove(key); if (remove != null) { boolean containsValue = USERS.containsValue(remove); LOGGER.info("\n 移出结果 - {}", containsValue ? "失败" : "成功"); return containsValue; } else { return true; } } /** * 获取在线用户列表 * * @return 返回用户集合 */ public static Map<String, Session> getUsers() { return USERS; } /** * 群发消息文本消息 * * @param message 消息内容 */ public static void sendMessageToUsersByText(String message) { Collection<Session> values = USERS.values(); for (Session value : values) { sendMessageToUserByText(value, message); } } /** * 发送文本消息 * * @param userName 自己的用户名 * @param message 消息内容 */ public static void sendMessageToUserByText(Session session, String message) { if (session != null) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { LOGGER.error("\n[发送消息异常]", e); } } else { LOGGER.info("\n[你已离线]"); } } }
2929004360/ruoyi-sign
984
ruoyi-framework/src/main/java/com/ruoyi/framework/websocket/SemaphoreUtils.java
package com.ruoyi.framework.websocket; import java.util.concurrent.Semaphore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 信号量相关处理 * * @author ruoyi */ public class SemaphoreUtils { /** * SemaphoreUtils 日志控制器 */ private static final Logger LOGGER = LoggerFactory.getLogger(SemaphoreUtils.class); /** * 获取信号量 * * @param semaphore * @return */ public static boolean tryAcquire(Semaphore semaphore) { boolean flag = false; try { flag = semaphore.tryAcquire(); } catch (Exception e) { LOGGER.error("获取信号量异常", e); } return flag; } /** * 释放信号量 * * @param semaphore */ public static void release(Semaphore semaphore) { try { semaphore.release(); } catch (Exception e) { LOGGER.error("释放信号量异常", e); } } }
281677160/openwrt-package
22,440
luci-app-amlogic/root/usr/sbin/openwrt-backup
#!/bin/bash #====================================================================== # Function: Backup and restore config files in the /etc directory # Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit # Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic #====================================================================== VERSION="v1.3" ZSTD_LEVEL=6 SNAPSHOT_PRESTR=".snapshots/" BACKUP_DIR="/.reserved" BACKUP_NAME="openwrt_config.tar.gz" BACKUP_FILE="${BACKUP_DIR}/${BACKUP_NAME}" # Customize backup list backup_list_conf="/etc/amlogic_backup_list.conf" if [[ -s "${backup_list_conf}" ]]; then while IFS= read -r line; do BACKUP_LIST+="${line} " done <"${backup_list_conf}" else BACKUP_LIST='./etc/AdGuardHome.yaml \ ./etc/amlogic_backup_list.conf \ ./etc/adblocklist/ \ ./etc/amule/ \ ./etc/balance_irq \ ./etc/bluetooth/ \ ./etc/china_ssr.txt \ ./etc/cifs/cifsdpwd.db \ ./etc/smbd/smbdpwd.db \ ./etc/ksmbd/ksmbdpwd.db \ ./etc/config/ \ ./etc/crontabs/ \ ./etc/dae/ \ ./etc/daed/ \ ./usr/share/openclash/core/ \ ./etc/openclash/backup/ \ ./etc/openclash/config/ \ ./etc/openclash/custom/ \ ./etc/openclash/game_rules/ \ ./etc/openclash/rule_provider/ \ ./etc/openclash/proxy_provider/ \ ./etc/dnsforwarder/ \ ./etc/dnsmasq.conf \ ./etc/dnsmasq.d/ \ ./etc/dnsmasq.oversea/ \ ./etc/dnsmasq.ssr/ \ ./etc/docker/daemon.json \ ./etc/docker/key.json \ ./etc/dropbear/ \ ./etc/easy-rsa/ \ ./etc/environment \ ./etc/exports \ ./etc/firewall.user \ ./etc/gfwlist/ \ ./etc/haproxy.cfg \ ./etc/hosts \ ./etc/ipsec.conf \ ./etc/ipsec.d/ \ ./etc/ipsec.secrets \ ./etc/ipsec.user \ ./etc/ipset/ \ ./etc/mosdns/config.yaml \ ./etc/mwan3.user \ ./etc/nginx/nginx.conf \ ./etc/ocserv/ \ ./etc/openvpn/ \ ./etc/pptpd.conf \ ./etc/qBittorrent/ \ ./etc/rc.local \ ./etc/samba/smbpasswd \ ./etc/shadow \ ./etc/smartdns/ \ ./etc/sqm/ \ ./etc/ssh/*key* \ ./etc/ssl/private/ \ ./etc/ssrplus/ \ ./etc/sysupgrade.conf \ ./etc/tailscale/ \ ./etc/transmission/ \ ./etc/uhttpd.crt \ ./etc/uhttpd.key \ ./etc/urandom.seed \ ./etc/v2raya/ \ ./etc/verysync/ \ ./root/.ssh/' fi error_msg() { echo -e " [ERROR] ${1}" exit 1 } if dmesg | grep 'meson' >/dev/null 2>&1; then PLATFORM="amlogic" elif dmesg | grep 'rockchip' >/dev/null 2>&1; then PLATFORM="rockchip" elif dmesg | grep 'sun50i-h6' >/dev/null 2>&1; then PLATFORM="allwinner" else source /etc/flippy-openwrt-release case ${PLATFORM} in amlogic | rockchip | allwinner | qemu-aarch64) : ;; *) error_msg "Unknown platform, only support amlogic or rockchip or allwinner h6 or qemu-aarch64!" ;; esac fi get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Get the partition message of the root file system get_root_partition_msg() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_msg=$(lsblk -l -o NAME,PATH,MOUNTPOINT,UUID,FSTYPE,LABEL | awk '$3 ~ "^" "'"${path}"'" "$" {print $0}') [[ -n "${partition_msg}" ]] && break done [[ -z "${partition_msg}" ]] && error_msg "Cannot find the root partition message!" echo "${partition_msg}" } backup() { cd / echo -n "Backup config files ... " [ -d "${BACKUP_DIR}" ] || mkdir -p "${BACKUP_DIR}" eval tar czf "${BACKUP_FILE}" "${BACKUP_LIST}" 2>/dev/null sync if [ -f "${BACKUP_FILE}" ]; then echo "Has been backed up to [ ${BACKUP_FILE} ], please download and save." exit 0 else error_msg "Backup failed!" fi } restore() { # Find the partition where root is located ROOT_PTNAME="$(get_root_partition_name)" # Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats case ${ROOT_PTNAME} in mmcblk?p[1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}') PARTITION_NAME="p" LB_PRE="EMMC_" ;; [hsv]d[a-z][1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}') PARTITION_NAME="" LB_PRE="" ;; *) error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!" ;; esac [ -d "${BACKUP_DIR}" ] || mkdir -p "${BACKUP_DIR}" [ -f "/tmp/upload/${BACKUP_NAME}" ] && mv -f "/tmp/upload/${BACKUP_NAME}" ${BACKUP_FILE} [ -f "/mnt/${EMMC_NAME}${PARTITION_NAME}4/${BACKUP_NAME}" ] && mv -f "/mnt/${EMMC_NAME}${PARTITION_NAME}4/${BACKUP_NAME}" ${BACKUP_FILE} sync if [ -f "${BACKUP_FILE}" ]; then echo -n "restore config files ... " cd / tar xzf "${BACKUP_FILE}" 2>/dev/null && sync echo "Successful recovery. Will start automatically, please refresh later!" sleep 3 reboot exit 0 else error_msg "The backup file [ ${BACKUP_FILE} ] not found!" fi } gen_fstab() { # Find the partition where root is located ROOT_PTNAME="$(get_root_partition_name)" # Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats case ${ROOT_PTNAME} in mmcblk?p[1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}') PARTITION_NAME="p" ;; [hsv]d[a-z][1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}') PARTITION_NAME="" ;; *) error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!" ;; esac ROOT_MSG="$(get_root_partition_msg)" ROOT_NAME=$(echo $ROOT_MSG | awk '{print $1}') ROOT_DEV=$(echo $ROOT_MSG | awk '{print $2}') ROOT_UUID=$(echo $ROOT_MSG | awk '{print $4}') ROOT_FSTYPE=$(echo $ROOT_MSG | awk '{print $5}') ROOT_LABEL=$(echo $ROOT_MSG | awk '{print $6}') BOOT_NAME="${EMMC_NAME}${PARTITION_NAME}1" BOOT_MSG=$(lsblk -l -o NAME,UUID,FSTYPE,LABEL | grep "${BOOT_NAME}") BOOT_DEV="/dev/${BOOT_NAME}" BOOT_UUID=$(echo $BOOT_MSG | awk '{print $2}') BOOT_FSTYPE=$(echo $BOOT_MSG | awk '{print $3}') BOOT_LABEL=$(echo $BOOT_MSG | awk '{print $4}') cat >/etc/config/fstab <<EOF config global option anon_swap '0' option anon_mount '1' option auto_swap '0' option auto_mount '1' option delay_root '5' option check_fs '0' config mount option target '/rom' option uuid '${ROOT_UUID}' option enabled '1' option enabled_fsck '1' option fstype '${ROOT_FSTYPE}' EOF if [ "${ROOT_FSTYPE}" == "btrfs" ]; then echo " option options 'compress=zstd:${ZSTD_LEVEL}'" >>/etc/config/fstab fi cat >>/etc/config/fstab <<EOF config mount option target '/boot' EOF if [ "${BOOT_FSTYPE}" == "vfat" ]; then echo " option label '${BOOT_LABEL}'" >>/etc/config/fstab else echo " option uuid '${BOOT_UUID}'" >>/etc/config/fstab fi cat >>/etc/config/fstab <<EOF option enabled '1' option enabled_fsck '1' option fstype '${BOOT_FSTYPE}' EOF echo "/etc/config/fstab generated." echo "please reboot" exit 0 } print_list() { echo "${BACKUP_LIST}" exit 0 } list_snapshot() { echo "----------------------------------------------------------------" btrfs subvolume list -rt / echo "----------------------------------------------------------------" read -p "Press [ enter ] to return." q } create_snapshot() { default_snap_name="etc-$(date +"%m.%d.%H%M%S")" echo "The default snapshot name is: ${default_snap_name}" echo "If you want to modify the snapshot name, please enter it below. Cannot contain spaces." echo "If you do not want to modify it, just press [ Enter ]. Or press the [ q ] key to go back directly." while :; do read -p "[${default_snap_name}] : " nname if [ "${nname}" == "" ]; then snap_name="${default_snap_name}" break elif echo "${nname}" | grep -E "\s+" >/dev/null; then echo "The name [${nname}] contains spaces, please re-enter!" continue elif [ "${nname}" == "q" ] || [ "${nname}" == "Q" ]; then return else if btrfs subvolume list -rt / | awk '{print $4}' | grep "^\\${SNAPSHOT_PRESTR}${nname}$" >/dev/null; then echo "Name: [ ${nname} ] has been used, please re-enter!" continue else snap_name="${nname}" break fi fi done ( cd / chattr -ia etc/config/fstab btrfs subvolume snapshot -r /etc "${SNAPSHOT_PRESTR}${snap_name}" if [[ "$?" -eq "0" ]]; then echo "The snapshot is created successfully: ${snap_name}" else echo "Snapshot creation failed!" fi ) read -p "Press [ enter ] to return." q } restore_snapshot() { echo "Below are the existing etc snapshots, please enter the name of one of them." echo "Tip: [ etc-000 ] This is the factory initial configuration." echo " [ etc-001 ] if it exists, it is the initial configuration after upgrading from the previous version." echo "----------------------------------------------------------------" btrfs subvolume list -rt / echo "----------------------------------------------------------------" read -p "Please enter the name of the snapshot to be restored (only the part after ${SNAPSHOT_PRESTR} needs to be entered): " snap_name if btrfs subvolume list -rt / | grep "${SNAPSHOT_PRESTR}${snap_name}" >/dev/null; then while :; do echo "Once the snapshot is restored, the current [ /etc ] will be overwritten!" read -p "Are you sure you want to restore the snapshot: [$snap_name]? y/n [n] " yn case $yn in y | Y) ( cd / chattr -ia etc/config/fstab mv etc etc.backup btrfs subvolume snapshot "${SNAPSHOT_PRESTR}${snap_name}" etc if [[ "$?" -eq "0" ]]; then btrfs subvolume delete -c etc.backup echo "Successfully restored, please enter [ reboot ] to restart the openwrt." else rm -rf etc mv etc.backup etc echo "Recovery failed, [ etc ] has not changed!" fi ) read -p "Press [ enter ] to return." q break ;; *) break ;; esac done else read -p "The snapshot name is incorrect, please run the program again! Press [ Enter ] to go back." q fi } delete_snapshot() { echo "Below are the existing [ etc ] snapshots, please enter the name of one of them." echo "Tip: [ etc-000 ] This is the factory initial configuration (cannot be deleted)" echo " [ etc-001 ] if it exists, it is the initial configuration after upgrading from the previous version (cannot be deleted)" echo "----------------------------------------------------------------" btrfs subvolume list -rt / echo "----------------------------------------------------------------" read -p "Please enter the name of the snapshot to be deleted (only the part after ${SNAPSHOT_PRESTR} needs to be entered): " snap_name if [ "${snap_name}" == "etc-000" ] || [ "${snap_name}" == "etc-001" ]; then read -p "The key snapshot cannot be deleted! Press [ enter ] to return." q elif [ "${snap_name}" == "" ]; then read -p "Name is empty! Press [ enter ] to return." q else if btrfs subvolume list -rt / | grep "${SNAPSHOT_PRESTR}${snap_name}" >/dev/null; then read -p "Are you sure you want to delete ${snap_name}? y/n [n] " yn case $yn in y | Y) ( cd / btrfs subvolume delete -c "${SNAPSHOT_PRESTR}${snap_name}" if [[ "$?" -eq "0" ]]; then echo "Snapshot [ ${snap_name} ] has been deleted." else echo "Snapshot [ ${snap_name} ] failed to delete!" fi ) read -p "Press [ Enter ] to return." q ;; *) break ;; esac else read -p "The name of the snapshot is incorrect, press [ Enter ] to return." q fi fi } migrate_snapshot() { cur_rootdev="$(get_root_partition_name)" dev_pre=$(echo "${cur_rootdev}" | awk '{print substr($1, 1, length($1)-1);}') rootdev_idx=$(echo "${cur_rootdev}" | awk '{print substr($1, length($1),1);}') case $rootdev_idx in 2) old_rootpath="/mnt/${dev_pre}3" ;; 3) old_rootpath="/mnt/${dev_pre}2" ;; *) echo "Judge the old version of rootfs path failed!" read -p "Press [ enter ] to return." q return ;; esac echo "The following are snapshots of etc found from the old version of rootfs, please enter the name of one of them." echo "Tip: Automatically exclude etc-000 and etc-001" echo "-----------------------------------------------------------------------------------" btrfs subvolume list -rt "${old_rootpath}" | grep -v "${SNAPSHOT_PRESTR}etc-000" | grep -v "${SNAPSHOT_PRESTR}etc-001" echo "-----------------------------------------------------------------------------------" read -p "Please enter the name of the snapshot to be migrated (only the part after $(SNAPSHOT_PRESTR) needs to be entered): " old_snap_name if [ "${old_snap_name}" == "" ]; then read -p "The name is empty, Press [ enter ] to return." q return elif ! btrfs subvolume list -rt "${old_rootpath}" | awk '{print $4}' | grep "^${SNAPSHOT_PRESTR}${old_snap_name}$" >/dev/null; then echo "The name was entered incorrectly, and the corresponding snapshot was not found!" read -p "Press [ enter ] to return." q return elif [ "${old_snap_name}" == "etc-000" ] || [ "${old_snap_name}" == "etc-001" ]; then echo "Critical snapshots are not allowed to migrate!" read -p "Press [ enter ] to return." q return fi # Find out if there is a snapshot with the same name under the current rootfs if btrfs subvolume list -rt / | awk '{print $4}' | grep "^\\${SNAPSHOT_PRESTR}${old_snap_name}$" >/dev/null; then echo "A snapshot with the name [ ${old_snap_name} ] already exists and cannot be migrated! (But you can delete the existing snapshot with the same name and then migrate)" read -p "Press [ enter ] to return." q return fi need_size=$(du -h -d0 ${old_rootpath}/${SNAPSHOT_PRESTR}${old_snap_name} | tail -n1 | awk '{print $1}') echo "----------------------------------------------------------------------------------------------" df -h echo "----------------------------------------------------------------------------------------------" echo -e "Note: To migrate the snapshot [ ${old_snap_name} ] of [ ${old_rootpath} ] to the current rootfs, it takes about [ ${need_size} ] space," echo -e " Please confirm whether the partition [/dev/${cur_rootdev}] where [/] is located has enough free space (Available)?" read -p "Are you sure to migrate? y/n [n] " yn if [ "$yn" == "y" ] || [ "$yn" == "Y" ]; then ( cd / btrfs send ${old_rootpath}/${SNAPSHOT_PRESTR}${old_snap_name} | btrfs receive ${SNAPSHOT_PRESTR} if [ $? -eq 0 ]; then btrfs property set -ts ${SNAPSHOT_PRESTR}${old_snap_name} ro false cp ${SNAPSHOT_PRESTR}etc-000/config/fstab ${SNAPSHOT_PRESTR}${old_snap_name}/config/ cp ${SNAPSHOT_PRESTR}etc-000/fstab ${SNAPSHOT_PRESTR}${old_snap_name}/ cp ${SNAPSHOT_PRESTR}etc-000/openwrt_release ${SNAPSHOT_PRESTR}${old_snap_name}/ cp ${SNAPSHOT_PRESTR}etc-000/openwrt_version ${SNAPSHOT_PRESTR}${old_snap_name}/ cp ${SNAPSHOT_PRESTR}etc-000/flippy-openwrt-release ${SNAPSHOT_PRESTR}${old_snap_name}/ cp ${SNAPSHOT_PRESTR}etc-000/banner ${SNAPSHOT_PRESTR}${old_snap_name}/banner btrfs property set -ts ${SNAPSHOT_PRESTR}${old_snap_name} ro true echo "The migration is complete, if you want to apply the snapshot [ ${old_snap_name} ], please use the restore snapshot function." else echo "The migration failed!" fi read -p "Press [ enter ] to return." q return ) fi } snapshot_help() { clear cat <<EOF ============================================================================================================================ 1. What is a snapshot? A snapshot is the state record of a certain subvolume at a certain point in time, and a snapshot is a special subvolume; When the local snapshot is first generated, it shares the disk space with the original subvolume, so it does not occupy additional space, and only the files that have changed subsequently occupy space; Snapshots migrated from other places are not snapshots in essence, but just ordinary subvolumes, so they take up space. 2. How to display existing snapshots? input the command: btrfs subvolume list -rt / --------------------------------------------------------------------------------------------- EOF btrfs subvolume list -rt / cat <<EOF --------------------------------------------------------------------------------------------- 2. How to create a snapshot? btrfs subvolume snapshot -r /etc /.snapshots/snapshot_1 # -r It means to generate a read-only snapshot 3. How to delete a snapshot? btrfs subvolume delete -c /.snapshots/snapshot_1 # -c 是 commit 的意思 4. How to rename a snapshot? Just use the [ mv ] command of the operating system, for example: mv /.snapshots/snapshot_1 /.snapshots/snapshot_2 5. How to restore the snapshot? mv /etc /etc.backup # Back up /etc to /etc.backup, that is, rename the subvolume btrfs subvolume snapshot /.snapshots/etc-001 /etc # Use snapshot etc-001 to generate snapshot etc, no -r parameter # (Yes, snapshots can also be re-generated snapshots) btrfs delete -c /etc.backup # After the previous step is successful, you can delete the etc backup just now 6. How to restore a certain file from the snapshot? Example A: Restore the mount point configuration file from snapshot etc-000: /etc/config/fstab cp /.snapshots/etc-000/config/fstab /etc/config/ Example B: Restore network configuration from snapshot etc-001: cp /.snapshots/etc-001/config/network /etc/config/ Example C: Restore the ssr configuration file from snapshot etc-001: cp /.snapshots/etc-001/config/shadowsocksr /etc/config/ # (Yes, it is the [ cp ] command of the operating system) 7. How to migrate snapshots from remote? btrfs supports ssh remote migration snapshots, for example: ssh 192.168.1.1 btrfs send /.snapshots/snapshot_x | btrfs receive /.snapshots After the command is completed, the remote snapshot_x is copied to the local /.snapshots/snapshot_x (as mentioned above, the migration is a subvolume, which takes up space) ============================================================================================================================ EOF exit 0 } print_help() { echo "Usage: $0 -b [ backup ]" echo " $0 -r [ restore ]" echo " $0 -g [ generate fstab ]" echo " $0 -p [ print backup list ]" echo " $0 -l [ list snapshots ]" echo " $0 -c [ create snapshot ]" echo " $0 -s [ restore snapshot ]" echo " $0 -d [ delete snapshot ]" echo " $0 -h [ help ]" echo " $0 -q [ quit ]" exit 0 } menu() { while :; do clear cat <<EOF ┌────────[ backup config ]────────┐ │ │ │ b. backup config │ │ r. restore config │ │ g. generate fstab │ │ p. print backup list │ │ │ ├─────[ Snapshot management ]─────┤ │ │ │ l. list snapshots │ │ c. create snapshot │ │ d. delete snapshot │ │ R. restore snapshot │ │ m. migrate snapshot │ │ s. snapshot help │ │ │ ╞═════════════════════════════════╡ │ │ │ h. help │ │ q. quit │ │ │ └─────────────────────────────────┘ EOF echo -ne "please select: [ ]\b\b" read select case $select in b | backup) backup ;; r | restore) restore gen_fstab ;; g | gen_fstab) gen_fstab ;; p | print_list) print_list ;; l | list_snapshot) list_snapshot ;; c | create_snapshot) create_snapshot ;; d | delete_snapshot) delete_snapshot ;; R | restore_snapshot) restore_snapshot ;; m | migrate_snapshot) migrate_snapshot ;; s | snapshot_help) snapshot_help ;; h | help) print_help ;; q | quit) exit 0 ;; esac done } getopts 'brgplcRmsdhq' opts case $opts in b | backup) backup ;; r | restore) restore gen_fstab ;; g | gen_fstab) gen_fstab ;; p | print_list) print_list ;; l | list_snapshot) list_snapshot ;; c | create_snapshot) create_snapshot ;; d | delete_snapshot) delete_snapshot ;; R | restore_snapshot) restore_snapshot ;; m | migrate_snapshot) migrate_snapshot ;; s | snapshot_help) snapshot_help ;; h | help) print_help ;; q | quit) exit 0 ;; *) menu ;; esac
2929004360/ruoyi-sign
2,761
ruoyi-framework/src/main/java/com/ruoyi/framework/websocket/WebSocketServer.java
package com.ruoyi.framework.websocket; import java.util.concurrent.Semaphore; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * websocket 消息处理 * * @author ruoyi */ @Component @ServerEndpoint("/websocket/message") public class WebSocketServer { /** * WebSocketServer 日志控制器 */ private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class); /** * 默认最多允许同时在线人数100 */ public static int socketMaxOnlineCount = 100; private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount); /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) throws Exception { boolean semaphoreFlag = false; // 尝试获取信号量 semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore); if (!semaphoreFlag) { // 未获取到信号量 LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount); WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数:" + socketMaxOnlineCount); session.close(); } else { // 添加用户 WebSocketUsers.put(session.getId(), session); LOGGER.info("\n 建立连接 - {}", session); LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size()); WebSocketUsers.sendMessageToUserByText(session, "连接成功"); } } /** * 连接关闭时处理 */ @OnClose public void onClose(Session session) { LOGGER.info("\n 关闭连接 - {}", session); // 移除用户 boolean removeFlag = WebSocketUsers.remove(session.getId()); if (!removeFlag) { // 获取到信号量则需释放 SemaphoreUtils.release(socketSemaphore); } } /** * 抛出异常时处理 */ @OnError public void onError(Session session, Throwable exception) throws Exception { if (session.isOpen()) { // 关闭连接 session.close(); } String sessionId = session.getId(); LOGGER.info("\n 连接异常 - {}", sessionId); LOGGER.info("\n 异常信息 - {}", exception); // 移出用户 WebSocketUsers.remove(sessionId); // 获取到信号量则需释放 SemaphoreUtils.release(socketSemaphore); } /** * 服务器接收到客户端消息时调用的方法 */ @OnMessage public void onMessage(String message, Session session) { String msg = message.replace("你", "我").replace("吗", ""); WebSocketUsers.sendMessageToUserByText(session, msg); } }
2929004360/ruoyi-sign
1,932
ruoyi-framework/src/main/java/com/ruoyi/framework/config/ThreadPoolConfig.java
package com.ruoyi.framework.config; import com.ruoyi.common.utils.Threads; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * 线程池配置 * * @author ruoyi **/ @Configuration public class ThreadPoolConfig { // 核心线程池大小 private int corePoolSize = 50; // 最大可创建的线程数 private int maxPoolSize = 200; // 队列最大长度 private int queueCapacity = 1000; // 线程池维护线程所允许的空闲时间 private int keepAliveSeconds = 300; @Bean(name = "threadPoolTaskExecutor") public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); // 线程池对拒绝任务(无线程可用)的处理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } /** * 执行周期性或定时任务 */ @Bean(name = "scheduledExecutorService") protected ScheduledExecutorService scheduledExecutorService() { return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(), new ThreadPoolExecutor.CallerRunsPolicy()) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); Threads.printException(r, t); } }; } }
2929004360/ruoyi-sign
1,438
ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java
package com.ruoyi.framework.config; import java.nio.charset.Charset; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.filter.Filter; import com.ruoyi.common.constant.Constants; /** * Redis使用FastJson序列化 * * @author ruoyi */ public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(Constants.JSON_WHITELIST_STR); private Class<T> clazz; public FastJson2JsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER); } }
2929004360/ruoyi-sign
1,244
ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java
package com.ruoyi.framework.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import com.ruoyi.common.constant.Constants; /** * 资源文件配置加载 * * @author ruoyi */ @Configuration public class I18nConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); // 默认语言 slr.setDefaultLocale(Constants.DEFAULT_LOCALE); return slr; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); // 参数名 lci.setParamName("lang"); return lci; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
281677160/openwrt-package
20,084
luci-app-amlogic/root/usr/sbin/openwrt-update-allwinner
#!/bin/bash #====================================================================================== # Function: Update openwrt to emmc for Allwinner STB # Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit # Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic #====================================================================================== # # The script supports directly setting parameters for update, skipping interactive selection # openwrt-update-allwinner ${OPENWRT_FILE} ${AUTO_MAINLINE_UBOOT} ${RESTORE_CONFIG} # E.g: openwrt-update-allwinner openwrt_s905d.img.gz yes restore # E.g: openwrt-update-allwinner openwrt_s905d.img.gz no no-restore # You can also execute the script directly, and interactively select related functions # E.g: openwrt-update-allwinner # #====================================================================================== # Encountered a serious error, abort the script execution error_msg() { echo -e "[ERROR] ${1}" exit 1 } # Get the partition name of the root file system get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Get the partition message of the root file system get_root_partition_msg() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_msg=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ "^" "'"${path}"'" "$" {print $0}') [[ -n "${partition_msg}" ]] && break done [[ -z "${partition_msg}" ]] && error_msg "Cannot find the root partition message!" echo "${partition_msg}" } # Receive one-key command related parameters IMG_NAME=${1} AUTO_MAINLINE_UBOOT=${2} BACKUP_RESTORE_CONFIG=${3} # Current FDT file if [[ -f "/boot/uEnv.txt" ]]; then source /boot/uEnv.txt 2>/dev/null MYDTB_FDTFILE=$(basename $FDT) elif [[ -f "/boot/armbianEnv.txt" ]]; then source /boot/armbianEnv.txt 2>/dev/null MYDTB_FDTFILE="$(basename $fdtfile)" elif [[ -f "/etc/flippy-openwrt-release" ]]; then source /etc/flippy-openwrt-release 2>/dev/null MYDTB_FDTFILE="${FDTFILE}" fi [[ -z "${MYDTB_FDTFILE}" ]] && error_msg "Invalid FDTFILE: [ ${MYDTB_FDTFILE} ]" # Current device model MYDEVICE_NAME=$(cat /proc/device-tree/model | tr -d '\000') if [[ -z "${MYDEVICE_NAME}" ]]; then error_msg "The device name is empty and cannot be recognized." elif [[ "$(echo ${MYDEVICE_NAME} | grep "V-Plus Cloud")" == "" ]]; then error_msg "[ ${MYDEVICE_NAME} ] is not [ V-Plus Cloud ] device, please select the correct script." else echo -e "Current device: ${MYDEVICE_NAME} [ vplus ]" sleep 3 fi # Find the partition where root is located ROOT_PTNAME="$(get_root_partition_name)" # Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats case ${ROOT_PTNAME} in mmcblk?p[1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-2)}') PARTITION_NAME="p" LB_PRE="EMMC_" ;; [hsv]d[a-z][1-4]) EMMC_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}') PARTITION_NAME="" LB_PRE="" ;; *) error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!" ;; esac cd /mnt/${EMMC_NAME}${PARTITION_NAME}4/ mv -f /tmp/upload/* . 2>/dev/null && sync if [[ "${IMG_NAME}" == *.img ]]; then echo -e "Update using [ ${IMG_NAME} ] file. Please wait a moment ..." elif [ $(ls *.img -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then IMG_NAME=$(ls *.img | head -n 1) echo -e "Update using [ ${IMG_NAME} ] ] file. Please wait a moment ..." elif [ $(ls *.img.xz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then xz_file=$(ls *.img.xz | head -n 1) echo -e "Update using [ ${xz_file} ] file. Please wait a moment ..." xz -d ${xz_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.img.gz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then gz_file=$(ls *.img.gz | head -n 1) echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..." gzip -df ${gz_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.7z -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then gz_file=$(ls *.7z | head -n 1) echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..." bsdtar -xmf ${gz_file} 2>/dev/null [ $? -eq 0 ] || 7z x ${gz_file} -aoa -y 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.zip -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then zip_file=$(ls *.zip | head -n 1) echo -e "Update using [ ${zip_file} ] file. Please wait a moment ..." unzip -o ${zip_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) else echo -e "Please upload or specify the update openwrt firmware file." echo -e "Upload method: system menu → Amlogic Service → Manually Upload Update" echo -e "Specify method: Place the openwrt firmware file in [ /mnt/${EMMC_NAME}${PARTITION_NAME}4/ ]" echo -e "The supported file suffixes are: *.img, *.img.xz, *.img.gz, *.7z, *.zip" echo -e "After upload the openwrt firmware file, run again." exit 1 fi sync # check file if [ ! -f "${IMG_NAME}" ]; then error_msg "No update file found." else echo "Start update from [ ${IMG_NAME} ]" fi # find boot partition BOOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ /^\/boot$/ {print $0}') if [ "${BOOT_PART_MSG}" == "" ]; then error_msg "The boot partition is not exists or not mounted, so it cannot be upgraded with this script!" fi BR_FLAG=1 echo -ne "Whether to backup and restore the current config files? y/n [y]\b\b" if [[ ${BACKUP_RESTORE_CONFIG} == "restore" ]]; then yn="y" elif [[ ${BACKUP_RESTORE_CONFIG} == "no-restore" ]]; then yn="n" else read yn fi case $yn in n* | N*) BR_FLAG=0 ;; esac BOOT_NAME=$(echo ${BOOT_PART_MSG} | awk '{print $1}') BOOT_PATH=$(echo ${BOOT_PART_MSG} | awk '{print $2}') BOOT_UUID=$(echo ${BOOT_PART_MSG} | awk '{print $4}') # find root partition ROOT_PART_MSG="$(get_root_partition_msg)" ROOT_NAME=$(echo ${ROOT_PART_MSG} | awk '{print $1}') ROOT_PATH=$(echo ${ROOT_PART_MSG} | awk '{print $2}') ROOT_UUID=$(echo ${ROOT_PART_MSG} | awk '{print $4}') case ${ROOT_NAME} in ${EMMC_NAME}${PARTITION_NAME}2) NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}3" NEW_ROOT_LABEL="${LB_PRE}ROOTFS2" ;; ${EMMC_NAME}${PARTITION_NAME}3) NEW_ROOT_NAME="${EMMC_NAME}${PARTITION_NAME}2" NEW_ROOT_LABEL="${LB_PRE}ROOTFS1" ;; *) error_msg "The root partition location is invalid, so it cannot be upgraded with this script!" ;; esac # find new root partition NEW_ROOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | grep "${NEW_ROOT_NAME}" | awk '$3 ~ /^part$/ && $5 !~ /^\/$/ && $5 !~ /^\/boot$/ {print $0}') if [ "${NEW_ROOT_PART_MSG}" == "" ]; then error_msg "The new root partition is not exists, so it cannot be upgraded with this script!" fi NEW_ROOT_NAME=$(echo $NEW_ROOT_PART_MSG | awk '{print $1}') NEW_ROOT_PATH=$(echo $NEW_ROOT_PART_MSG | awk '{print $2}') NEW_ROOT_UUID=$(echo $NEW_ROOT_PART_MSG | awk '{print $4}') NEW_ROOT_MP=$(echo $NEW_ROOT_PART_MSG | awk '{print $5}') # losetup losetup -f -P $IMG_NAME if [ $? -eq 0 ]; then LOOP_DEV=$(losetup | grep "$IMG_NAME" | awk '{print $1}') if [ "$LOOP_DEV" == "" ]; then error_msg "loop device not found!" fi else error_msg "losetup $IMG_FILE failed!" fi # fix loopdev issue in kernel 5.19 function fix_loopdev() { local parentdev=${1##*/} if [ ! -d /sys/block/${parentdev} ]; then return fi subdevs=$(lsblk -l -o NAME | grep -E "^${parentdev}.+\$") for subdev in $subdevs; do if [ ! -d /sys/block/${parentdev}/${subdev} ]; then return elif [ -b /dev/${sub_dev} ]; then continue fi source /sys/block/${parentdev}/${subdev}/uevent mknod /dev/${subdev} b ${MAJOR} ${MINOR} unset MAJOR MINOR DEVNAME DEVTYPE DISKSEQ PARTN PARTNAME done } fix_loopdev ${LOOP_DEV} WAIT=3 echo -n "The loopdev is $LOOP_DEV, wait ${WAIT} seconds " while [ $WAIT -ge 1 ]; do echo -n "." sleep 1 WAIT=$((WAIT - 1)) done echo # umount loop devices (openwrt will auto mount some partition) MOUNTED_DEVS=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "$LOOP_DEV" | awk '$3 !~ /^$/ {print $2}') for dev in $MOUNTED_DEVS; do while :; do echo -n "umount $dev ... " umount -f $dev sleep 1 mnt=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "$dev" | awk '$3 !~ /^$/ {print $2}') if [ "$mnt" == "" ]; then echo "ok" break else echo "try again ..." fi done done # mount src part WORK_DIR=$PWD P1=${WORK_DIR}/boot P2=${WORK_DIR}/root mkdir -p $P1 $P2 echo -n "mount ${LOOP_DEV}p1 -> ${P1} ... " mount -t vfat -o ro ${LOOP_DEV}p1 ${P1} if [ $? -ne 0 ]; then echo "mount failed" losetup -D exit 1 else echo "ok" fi echo -n "mount ${LOOP_DEV}p2 -> ${P2} ... " ZSTD_LEVEL=6 mount -t btrfs -o ro,compress=zstd:${ZSTD_LEVEL} ${LOOP_DEV}p2 ${P2} if [ $? -ne 0 ]; then echo "mount failed" umount -f ${P1} losetup -D exit 1 else echo "ok" fi # Prepare the dockerman config file if [ -f ${P2}/etc/init.d/dockerman ] && [ -f ${P2}/etc/config/dockerd ]; then flg=0 # get current docker data root data_root=$(uci get dockerd.globals.data_root 2>/dev/null) if [ "$data_root" == "" ]; then flg=1 # get current config from /etc/docker/daemon.json if [ -f "/etc/docker/daemon.json" ] && [ -x "/usr/bin/jq" ]; then data_root=$(jq -r '."data-root"' /etc/docker/daemon.json) bip=$(jq -r '."bip"' /etc/docker/daemon.json) [ "$bip" == "null" ] && bip="172.31.0.1/24" log_level=$(jq -r '."log-level"' /etc/docker/daemon.json) [ "$log_level" == "null" ] && log_level="warn" _iptables=$(jq -r '."iptables"' /etc/docker/daemon.json) [ "$_iptables" == "null" ] && _iptables="true" registry_mirrors=$(jq -r '."registry-mirrors"[]' /etc/docker/daemon.json 2>/dev/null) fi fi if [ "$data_root" == "" ]; then data_root="/opt/docker/" # the default data root fi if ! uci get dockerd.globals >/dev/null 2>&1; then uci set dockerd.globals='globals' uci commit fi # delete alter config , use inner config if uci get dockerd.globals.alt_config_file >/dev/null 2>&1; then uci delete dockerd.globals.alt_config_file uci commit fi if [ $flg -eq 1 ]; then uci set dockerd.globals.data_root=$data_root [ "$bip" != "" ] && uci set dockerd.globals.bip=$bip [ "$log_level" != "" ] && uci set dockerd.globals.log_level=$log_level [ "$_iptables" != "" ] && uci set dockerd.globals.iptables=$_iptables if [ "$registry_mirrors" != "" ]; then for reg in $registry_mirrors; do uci add_list dockerd.globals.registry_mirrors=$reg done fi uci set dockerd.globals.auto_start='1' uci commit fi fi #format NEW_ROOT echo "umount ${NEW_ROOT_MP}" umount -f "${NEW_ROOT_MP}" if [ $? -ne 0 ]; then echo "umount failed, please reboot and try again!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi echo "format ${NEW_ROOT_PATH}" NEW_ROOT_UUID=$(uuidgen) mkfs.btrfs -f -U ${NEW_ROOT_UUID} -L ${NEW_ROOT_LABEL} ${NEW_ROOT_PATH} if [ $? -ne 0 ]; then echo "format ${NEW_ROOT_PATH} failed!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi echo "mount ${NEW_ROOT_PATH} to ${NEW_ROOT_MP}" mount -t btrfs -o compress=zstd:${ZSTD_LEVEL} ${NEW_ROOT_PATH} ${NEW_ROOT_MP} if [ $? -ne 0 ]; then echo "mount ${NEW_ROOT_PATH} to ${NEW_ROOT_MP} failed!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi # begin copy rootfs cd ${NEW_ROOT_MP} echo "Start copy data from ${P2} to ${NEW_ROOT_MP} ..." ENTRYS=$(ls) for entry in $ENTRYS; do if [ "$entry" == "lost+found" ]; then continue fi echo -n "remove old $entry ... " rm -rf $entry if [ $? -eq 0 ]; then echo "ok" else error_msg "failed" fi done echo echo "create etc subvolume ..." btrfs subvolume create etc echo -n "make dirs ... " mkdir -p .snapshots .reserved bin boot dev lib opt mnt overlay proc rom root run sbin sys tmp usr www ln -sf lib/ lib64 ln -sf tmp/ var echo "done" echo COPY_SRC="root etc bin sbin lib opt usr www" echo "copy data ... " for src in $COPY_SRC; do echo -n "copy $src ... " (cd ${P2} && tar cf - $src) | tar xf - sync echo "done" done SHFS="/mnt/${EMMC_NAME}${PARTITION_NAME}4" echo "Modify config files ... " rm -f "./etc/rc.local.orig" "./etc/first_run.sh" "./etc/part_size" rm -f ./etc/bench.log if [ -x ./usr/sbin/balethirq.pl ]; then if grep "balethirq.pl" "./etc/rc.local"; then echo "balance irq is enabled" else echo "enable balance irq" sed -e "/exit/i\/usr/sbin/balethirq.pl" -i ./etc/rc.local fi fi cat >./etc/fstab <<EOF UUID=${NEW_ROOT_UUID} / btrfs compress=zstd:${ZSTD_LEVEL} 0 1 LABEL=${LB_PRE}BOOT /boot vfat defaults 0 2 #tmpfs /tmp tmpfs defaults,nosuid 0 0 EOF cat >./etc/config/fstab <<EOF config global option anon_swap '0' option anon_mount '1' option auto_swap '0' option auto_mount '1' option delay_root '5' option check_fs '0' config mount option target '/rom' option uuid '${NEW_ROOT_UUID}' option enabled '1' option enabled_fsck '1' option fstype 'btrfs' option options 'compress=zstd:${ZSTD_LEVEL}' config mount option target '/boot' option label '${LB_PRE}BOOT' option enabled '1' option enabled_fsck '0' option fstype 'vfat' EOF ( cd etc/rc.d rm -f S??shortcut-fe if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then ln -sf ../init.d/shortcut-fe S99shortcut-fe fi fi ) # move /etc/config/balance_irq to /etc/balance_irq [ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/ sync echo "create the first etc snapshot -> .snapshots/etc-000" btrfs subvolume snapshot -r etc .snapshots/etc-000 [ -d ${SHFS}/docker ] || mkdir -p ${SHFS}/docker rm -rf opt/docker && ln -sf ${SHFS}/docker/ opt/docker if [ -f /mnt/${NEW_ROOT_NAME}/etc/config/AdGuardHome ]; then [ -d ${SHFS}/AdGuardHome/data ] || mkdir -p ${SHFS}/AdGuardHome/data if [ ! -L /usr/bin/AdGuardHome ]; then [ -d /usr/bin/AdGuardHome ] && cp -a /usr/bin/AdGuardHome/* ${SHFS}/AdGuardHome/ fi ln -sf ${SHFS}/AdGuardHome /mnt/${NEW_ROOT_NAME}/usr/bin/AdGuardHome fi BOOTLOADER="./lib/u-boot/u-boot-sunxi-with-spl.bin" if [ -f ${BOOTLOADER} ]; then echo "update u-boot ... " # erase from 8kb to 4mb dd if=/dev/zero of=/dev/${EMMC_NAME} bs=1024 seek=8 count=4088 conv=fsync # write u-boot dd if=${BOOTLOADER} of=/dev/${EMMC_NAME} bs=1024 seek=8 conv=fsync echo "done" fi sync echo "copy done" echo BACKUP_LIST=$(${P2}/usr/sbin/openwrt-backup -p) if [ $BR_FLAG -eq 1 ]; then echo -n "Restore your old config files ... " ( cd / eval tar czf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null ) tar xzf ${NEW_ROOT_MP}/.reserved/openwrt_config.tar.gz [ -f ./etc/config/dockerman ] && sed -e "s/option wan_mode 'false'/option wan_mode 'true'/" -i ./etc/config/dockerman 2>/dev/null [ -f ./etc/config/dockerd ] && sed -e "s/option wan_mode '0'/option wan_mode '1'/" -i ./etc/config/dockerd 2>/dev/null [ -f ./etc/config/verysync ] && sed -e 's/config setting/config verysync/' -i ./etc/config/verysync # 还原 fstab cp -f .snapshots/etc-000/fstab ./etc/fstab cp -f .snapshots/etc-000/config/fstab ./etc/config/fstab # 还原 luci cp -f .snapshots/etc-000/config/luci ./etc/config/luci # 还原/etc/config/rpcd cp -f .snapshots/etc-000/config/rpcd ./etc/config/rpcd sync echo "done" echo fi rm -f ./etc/bench.log cat >>./etc/crontabs/root <<EOF 17 3 * * * /etc/coremark.sh EOF sed -e 's/ttyAMA0/ttyS0/' -i ./etc/inittab sss=$(date +%s) ddd=$((sss / 86400)) sed -e "s/:0:0:99999:7:::/:${ddd}:0:99999:7:::/" -i ./etc/shadow # 修复amule每次升级后重复添加条目的问题 sed -e "/amule:x:/d" -i ./etc/shadow # 修复dropbear每次升级后重复添加sshd条目的问题 sed -e "/sshd:x:/d" -i ./etc/shadow if ! grep "sshd:x:22:sshd" ./etc/group >/dev/null; then echo "sshd:x:22:sshd" >>./etc/group fi if ! grep "sshd:x:22:22:sshd:" ./etc/passwd >/dev/null; then echo "sshd:x:22:22:sshd:/var/run/sshd:/bin/false" >>./etc/passwd fi if ! grep "sshd:x:" ./etc/shadow >/dev/null; then echo "sshd:x:${ddd}:0:99999:7:::" >>./etc/shadow fi if [ $BR_FLAG -eq 1 ]; then if [ -x ./bin/bash ] && [ -f ./etc/profile.d/30-sysinfo.sh ]; then sed -e 's/\/bin\/ash/\/bin\/bash/' -i ./etc/passwd fi sync echo "done" echo fi sed -e "s/option hw_flow '1'/option hw_flow '0'/" -i ./etc/config/turboacc ( cd etc/rc.d rm -f S??shortcut-fe if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then ln -sf ../init.d/shortcut-fe S99shortcut-fe fi fi ) sync eval tar czf .reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null rm -f ./etc/part_size ./etc/first_run.sh mv ./etc/rc.local ./etc/rc.local.orig cat >"./etc/rc.local" <<EOF if ! ls /etc/rc.d/S??dockerd >/dev/null 2>&1;then /etc/init.d/dockerd enable /etc/init.d/dockerd start fi if ! ls /etc/rc.d/S??dockerman >/dev/null 2>&1 && [ -f /etc/init.d/dockerman ];then /etc/init.d/dockerman enable /etc/init.d/dockerman start fi opkg remove --force-removal-of-dependent-packages shairport-sync-openssl mv /etc/rc.local.orig /etc/rc.local chmod 755 /etc/rc.local exec /etc/rc.local exit EOF chmod 755 ./etc/rc.local* # move /etc/config/balance_irq to /etc/balance_irq [ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/ echo "create the second etc snapshot -> .snapshots/etc-001" btrfs subvolume snapshot -r etc .snapshots/etc-001 # 2021.04.01添加 # 强制锁定fstab,防止用户擅自修改挂载点 # 开启了快照功能之后,不再需要锁定fstab #chattr +ia ./etc/config/fstab cd ${WORK_DIR} echo "Start copy data from ${P1} to /boot ..." cd /boot echo -n "remove old boot files ..." rm -rf * echo "done" echo -n "copy new boot files ... " (cd ${P1} && tar cf - .) | tar xf - sync echo "done" echo echo -n "Update boot args ... " cat >uEnv.txt <<EOF LINUX=/zImage INITRD=/uInitrd # Example: # FDT=/dtb/allwinner/sun50i-h6-vplus-cloud.dtb # FDT=/dtb/allwinner/sun50i-h6-vplus-cloud-2ghz.dtb FDT=/dtb/allwinner/${MYDTB_FDTFILE} APPEND=root=UUID=${NEW_ROOT_UUID} rootfstype=btrfs rootflags=compress=zstd:${ZSTD_LEVEL} console=ttyS0,115200n8 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1 EOF # Compatible with armbianEnv.txt file [[ -f "armbianEnv.txt" ]] && { echo "Update armbianEnv.txt settings." sed -i "s|^rootdev=.*|rootdev=UUID=${NEW_ROOT_UUID}|g" armbianEnv.txt rm -f uEnv.txt } # Replace the UUID for extlinux/extlinux.conf if it exists [[ -f "extlinux/extlinux.conf" ]] && { sed -i -E "s|UUID=[^ ]*|UUID=${NEW_ROOT_UUID}|" extlinux/extlinux.conf 2>/dev/null } sync echo "done" echo cd $WORK_DIR umount -f ${P1} ${P2} 2>/dev/null losetup -D 2>/dev/null rmdir ${P1} ${P2} 2>/dev/null rm -f ${IMG_NAME} 2>/dev/null rm -f sha256sums 2>/dev/null sync echo "Successfully updated, automatic restarting..." sleep 3 reboot exit 0
281677160/openwrt-package
21,694
luci-app-amlogic/root/usr/sbin/openwrt-install-amlogic
#!/bin/bash #====================================================================================== # Function: Install openwrt to emmc for Amlogic S9xxx STB # Copyright (C) 2020-- https://github.com/unifreq/openwrt_packit # Copyright (C) 2021-- https://github.com/ophub/luci-app-amlogic #====================================================================================== # # The script supports directly setting parameters for installation, skipping interactive selection # openwrt-install-amlogic ${AUTO_MAINLINE_UBOOT} ${ID} ${FDTFILE}:${SOC}:${UBOOT_OVERLOAD} ${SHARED_FSTYPE} # E.g: openwrt-install-amlogic yes 11 auto ext4 # E.g: openwrt-install-amlogic no 99 meson-gxl-s905d-phicomm-n1.dtb:s905d:u-boot-n1.bin ext4 # Tip: When custom dtb file, set ${SOC_ID} to 99, and parameter ${FDTFILE}:${SOC}:${UBOOT_OVERLOAD} must be set # Tip: ${SHARED_FSTYPE}: Shared partition can be ext4, xfs, btrfs, f2fs # You can also execute the script directly, and interactively select related functions # E.g: openwrt-install-amlogic # #====================================================================================== # Encountered a serious error, abort the script execution error_msg() { echo -e "[ERROR] ${1}" exit 1 } # Get the partition name of the root file system get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Receive one-key command related parameters AUTO_MAINLINE_UBOOT="${1}" ZSTD_LEVEL="6" op_release="/etc/flippy-openwrt-release" # For [luci-app-amlogic] input parameter: DTB, SOC & UBOOT_OVERLOAD # When there is no input parameter, select manually SPECIFY_ID="" SPECIFY_SOC="" SPECIFY_DTB="" SPECIFY_UBOOT="" [[ -n "${2}" ]] && { SPECIFY_ID="${2}" if [[ "${2}" -eq "99" ]]; then if [[ -n "${3}" ]]; then # E.g: meson-gxl-s905d-phicomm-n1.dtb:s905d:u-boot-n1.bin SPECIFY_DTB="$(echo "${3}" | awk -F ':' '{print $1}')" SPECIFY_SOC="$(echo "${3}" | awk -F ':' '{print $2}')" SPECIFY_UBOOT="$(echo "${3}" | awk -F ':' '{print $3}')" else error_msg "Please enter the DTB file name!" fi fi } # shared partition can be ext4, xfs, btrfs, f2fs SHARED_FSTYPE="${4}" echo "AUTO_MAINLINE_UBOOT: ${AUTO_MAINLINE_UBOOT}" echo "SPECIFY_DTB: ${SPECIFY_DTB}" echo "SPECIFY_SOC: ${SPECIFY_SOC}" echo "SPECIFY_UBOOT: ${SPECIFY_UBOOT}" echo "SHARED_FSTYPE: ${SHARED_FSTYPE}" # Current device model MYDEVICE_NAME=$(cat /proc/device-tree/model | tr -d '\000') if [[ -z "${MYDEVICE_NAME}" ]]; then error_msg "The device name is empty and cannot be recognized." elif [[ ! -f "${op_release}" ]]; then error_msg "The [ ${op_release} ] file is missing." else echo -e "Current device: ${MYDEVICE_NAME} [ amlogic ]" sleep 3 fi # Find the device name of / root_devname="$(get_root_partition_name)" if lsblk -l | grep -E "^${root_devname}boot0" >/dev/null; then error_msg "you are running in emmc mode, please boot system with usb or tf card!" fi install_emmc="$(lsblk -l -o NAME | grep -oE '(mmcblk[0-9]?boot0)' | sed "s/boot0//g")" if [[ "${install_emmc}" == "" ]]; then error_msg "No emmc can be found to install the openwrt system!" fi # EMMC DEVICE NAME EMMC_NAME="${install_emmc}" EMMC_DEVPATH="/dev/${EMMC_NAME}" echo ${EMMC_DEVPATH} EMMC_SIZE=$(lsblk -l -b -o NAME,SIZE | grep ${EMMC_NAME} | sort | uniq | head -n1 | awk '{print $2}') echo "${EMMC_NAME} : ${EMMC_SIZE} bytes" ROOT_NAME=$(lsblk -l -o NAME,MAJ:MIN,MOUNTPOINT | grep -e '/$' | awk '{print $1}') echo "ROOTFS: ${ROOT_NAME}" BOOT_NAME=$(lsblk -l -o NAME,MAJ:MIN,MOUNTPOINT | grep -e '/boot$' | awk '{print $1}') echo "BOOT: ${BOOT_NAME}" # box model database # The field separator is : # " " or "" or NA or NULL means this field is null # The fields list: # 1. id # 2. model name # 3. SOC # 4. FDTFILE # 5. UBOOT_OVERLOAD # 6. MAINLINE_UBOOT # 7. ANDROID_UBOOT # 8. brief description # # allow use external modal database if [[ -f "/etc/model_database.txt" ]]; then model_database="$(cat /etc/model_database.txt)" else error_msg "[ /etc/model_database.txt ] file is missing." fi function display_database() { while read -r line; do if [[ "$line" =~ ^# ]]; then # Process comment lines, starting with # line="${line/#+\s+/}" echo "$line >>>" else # Process data lines, starting with id IFS=':' read -r -a fields <<<"$line" printf "%5s %-48s%-10s%-s\n" "${fields[0]}" "${fields[1]}" "${fields[2]}" "${fields[7]}" fi done < <(echo "${model_database}") } function search_model() { local id="${1}" local ret_count="$(echo "${model_database}" | awk -F ':' "\$1~/^$id\$/ {print \$0}" | wc -l)" if [[ "${ret_count}" -eq "1" ]]; then echo "${model_database}" | awk -F ':' "\$1~/^$id\$/ {print \$0}" | sed -e 's/NA//g' -e 's/NULL//g' -e 's/[ ][ ]*//g' fi } echo "Please select s9xxx box model:" echo "----------------------------------------------------------------------------------------------------" display_database echo "----------------------------------------------------------------------------------------------------" # For [luci-app-amlogic] input parameter: SOC & DTB # When there is no input parameter, select manually if [[ -n "${SPECIFY_ID}" ]]; then boxtype="${SPECIFY_ID}" else echo -n "Please choose: " read boxtype fi if [[ "${boxtype}" -eq "99" ]]; then FDTFILE="${SPECIFY_DTB}" AMLOGIC_SOC="${SPECIFY_SOC}" UBOOT_OVERLOAD="${SPECIFY_UBOOT}" MAINLINE_UBOOT="" ANDROID_UBOOT="" elif [[ "${boxtype}" -eq "0" ]]; then read -p "Please Input SoC Name(such as s9xxx): " AMLOGIC_SOC AMLOGIC_SOC="${AMLOGIC_SOC}" read -p "Please Input DTB Name(such as meson-xxx.dtb): " FDTFILE FDTFILE="${FDTFILE}" read -p "Please Input UBOOT_OVERLOAD Name(such as u-boot-xxx.bin): " UBOOT_OVERLOAD UBOOT_OVERLOAD="${UBOOT_OVERLOAD}" read -p "Please Input MAINLINE_UBOOT Name(such as /lib/u-boot/xxx-u-boot.bin.sd.bin): " MAINLINE_UBOOT MAINLINE_UBOOT="${MAINLINE_UBOOT}" read -p "Please Input ANDROID_UBOOT Name(such as /lib/u-boot/xxx-bootloader.img): " ANDROID_UBOOT ANDROID_UBOOT="${ANDROID_UBOOT}" else ret="$(search_model ${boxtype})" if [[ -z "${ret}" ]]; then error_msg "Input error, exit!" fi # 3. soc # 4. FDTFILE # 5. UBOOT_OVERLOAD # 6. MAINLINE_UBOOT # 7. ANDROID_UBOOT AMLOGIC_SOC="$(echo "${ret}" | awk -F ':' '{print $3}')" FDTFILE="$(echo "${ret}" | awk -F ':' '{print $4}')" UBOOT_OVERLOAD="$(echo "${ret}" | awk -F ':' '{print $5}')" MAINLINE_UBOOT="$(echo "${ret}" | awk -F ':' '{print $6}')" ANDROID_UBOOT="$(echo "${ret}" | awk -F ':' '{print $7}')" fi if [[ -z "${FDTFILE}" || ! -f "/boot/dtb/amlogic/${FDTFILE}" ]]; then error_msg "/boot/dtb/amlogic/${FDTFILE} does not exist!" fi echo "AMLOGIC_SOC Value [ ${AMLOGIC_SOC} ]" echo "FDTFILE Value [ ${FDTFILE} ]" echo "UBOOT_OVERLOAD Value [ ${UBOOT_OVERLOAD} ]" echo "MAINLINE_UBOOT Value [ ${MAINLINE_UBOOT} ]" echo "ANDROID_UBOOT Value [ ${ANDROID_UBOOT} ]" sed -i "s|^SOC=.*|SOC='${AMLOGIC_SOC}'|g" ${op_release} 2>/dev/null sed -i "s|^FDTFILE=.*|FDTFILE='${FDTFILE}'|g" ${op_release} 2>/dev/null sed -i "s|^UBOOT_OVERLOAD=.*|UBOOT_OVERLOAD='${UBOOT_OVERLOAD}'|g" ${op_release} 2>/dev/null sed -i "s|^MAINLINE_UBOOT=.*|MAINLINE_UBOOT='${MAINLINE_UBOOT}'|g" ${op_release} 2>/dev/null sed -i "s|^ANDROID_UBOOT=.*|ANDROID_UBOOT='${ANDROID_UBOOT}'|g" ${op_release} 2>/dev/null K510="1" [[ "$(hexdump -n 15 -x "/boot/zImage" 2>/dev/null | head -n 1 | awk '{print $7}')" == "0108" ]] && K510="0" echo -e "K510 [ ${K510} ]" # backup old bootloader if [[ ! -f "/root/BackupOldBootloader.img" ]]; then echo "Backup bootloader -> [ BackupOldBootloader.img ] ... " dd if=/dev/$EMMC_NAME of=/root/BackupOldBootloader.img bs=1M count=4 conv=fsync echo "Backup bootloader complete." echo fi swapoff -a # umount all other mount points MOUNTS=$(lsblk -l -o MOUNTPOINT) for mnt in $MOUNTS; do if [ "$mnt" == "MOUNTPOINT" ]; then continue fi if [ "$mnt" == "" ]; then continue fi if [ "$mnt" == "/" ]; then continue fi if [ "$mnt" == "/boot" ]; then continue fi if [ "$mnt" == "/opt" ]; then continue fi if [ "$mnt" == "[SWAP]" ]; then echo "swapoff -a" swapoff -a continue fi if echo $mnt | grep $EMMC_NAME; then echo "umount -f $mnt" umount -f $mnt if [ $? -ne 0 ]; then error_msg "$mnt Cannot be uninstalled, the installation process is aborted." fi fi done # Delete old partition if exists p=$(lsblk -l | grep -e "${EMMC_NAME}p" | wc -l) echo "A total of [ $p ] old partitions on EMMC will be deleted" >/tmp/fdisk.script while [ $p -ge 1 ]; do echo "d" >>/tmp/fdisk.script if [ $p -gt 1 ]; then echo "$p" >>/tmp/fdisk.script fi p=$((p - 1)) done # you can change ROOT size(MB) >= 320 ROOT1="960" ROOT2="960" if [[ "${AMLOGIC_SOC}" == "s912" ]] && [[ "${boxtype}" == "213" || "${boxtype}" == "2e" ]]; then BOOT="512" BLANK1="700" BLANK2="220" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s912" || "${AMLOGIC_SOC}" == "s905d" ]]; then BOOT="512" BLANK1="68" BLANK2="220" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s905x" ]]; then BOOT="160" BLANK1="700" BLANK2="0" BLANK3="0" BLANK4="0" elif [[ "${FDTFILE}" == "meson-sm1-skyworth-lb2004-a4091.dtb" ]]; then BOOT="512" BLANK1="108" BLANK2="562" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s905l3a" ]] && [[ "${boxtype}" == "304" || "${boxtype}" == "34" ]]; then # e900v22c/d(s905l3a) BOOT="256" BLANK1="570" BLANK2="0" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s905l3a" ]] && [[ "${boxtype}" == "305" || "${boxtype}" == "33" ]]; then # CM311-1a-YST(s905l3a) BOOT="512" BLANK1="108" BLANK2="778" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s905l3b" ]]; then # M302A/M304A(s905l3b) BOOT="513" BLANK1="128" BLANK2="720" BLANK3="0" BLANK4="0" elif [[ "${AMLOGIC_SOC}" == "s905x3" ]] && [[ "${boxtype}" == "525" || "${boxtype}" == "5n" ]]; then # Whale(s905x3) BOOT="512" BLANK1="108" BLANK2="650" BLANK3="0" BLANK4="0" elif [[ "${boxtype}" =~ ^(409|410|49|4a)$ ]]; then # WXY-OES(A311D):409/49, WXY-OES-PLUS(S922X):410/4a BOOT="512" BLANK1="700" BLANK2="0" BLANK3="0" BLANK4="0" else BOOT="160" BLANK1="68" BLANK2="0" BLANK3="162" BLANK4="0" fi DST_TOTAL_MB=$((EMMC_SIZE / 1024 / 1024)) start1=$((BLANK1 * 2048)) end1=$((start1 + (BOOT * 2048) - 1)) start2=$(((BLANK2 * 2048) + end1 + 1)) end2=$((start2 + (ROOT1 * 2048) - 1)) start3=$(((BLANK3 * 2048) + end2 + 1)) end3=$((start3 + (ROOT2 * 2048) - 1)) start4=$(((BLANK4 * 2048) + end3 + 1)) end4=$((DST_TOTAL_MB * 2048 - 1)) cat >>/tmp/fdisk.script <<EOF n p 1 $start1 $end1 n p 2 $start2 $end2 n p 3 $start3 $end3 n p $start4 $end4 t 1 c t 2 83 t 3 83 t 4 83 w EOF fdisk /dev/${EMMC_NAME} </tmp/fdisk.script 2>/dev/null if [ $? -ne 0 ]; then echo "The fdisk partition fails, Please try again." dd if=/root/BackupOldBootloader.img of=/dev/${EMMC_NAME} conv=fsync && sync dd if=/dev/zero of=/dev/${EMMC_NAME} bs=512 count=1 && sync exit 1 fi echo "Partition complete." # write some zero data to part begin seek=$((start1 / 2048)) dd if=/dev/zero of=/dev/${EMMC_NAME} bs=1M count=1 seek=$seek conv=fsync seek=$((start2 / 2048)) dd if=/dev/zero of=/dev/${EMMC_NAME} bs=1M count=1 seek=$seek conv=fsync seek=$((start3 / 2048)) dd if=/dev/zero of=/dev/${EMMC_NAME} bs=1M count=1 seek=$seek conv=fsync seek=$((start4 / 2048)) dd if=/dev/zero of=/dev/${EMMC_NAME} bs=1M count=1 seek=$seek conv=fsync #Mainline U-BOOT detection FLASH_MAINLINE_UBOOT=0 if [[ -n "${MAINLINE_UBOOT}" && -f "${MAINLINE_UBOOT}" ]]; then cat <<EOF ---------------------------------------------------------------------------------- Found an available mainline bootloader (Mainline u-boot), you can flash into EMMC. ---------------------------------------------------------------------------------- EOF while :; do # For [luci-app-amlogic] input parameter: SOC & DTB # When there is no input parameter, select manually if [[ "${AUTO_MAINLINE_UBOOT}" == "yes" ]]; then if [[ "${K510}" -eq "1" ]]; then yn="y" else yn="n" fi elif [[ "${AUTO_MAINLINE_UBOOT}" == "no" ]]; then yn="n" else read -p "Please choose whether to write the mainline bootloader to EMMC? y/n " yn fi case $yn in y | Y) FLASH_MAINLINE_UBOOT=1 break ;; n | N) FLASH_MAINLINE_UBOOT=0 break ;; esac done fi if [[ "${FLASH_MAINLINE_UBOOT}" -eq "1" ]]; then echo -e "Write Mainline bootloader: [ ${MAINLINE_UBOOT} ]" dd if=${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=1 count=444 conv=fsync dd if=${MAINLINE_UBOOT} of=/dev/${EMMC_NAME} bs=512 skip=1 seek=1 conv=fsync elif [[ -n "${ANDROID_UBOOT}" && -f "${ANDROID_UBOOT}" ]]; then echo -e "Write Android bootloader: [ ${ANDROID_UBOOT} ]" dd if=${ANDROID_UBOOT} of=/dev/${EMMC_NAME} bs=1 count=444 conv=fsync dd if=${ANDROID_UBOOT} of=/dev/${EMMC_NAME} bs=512 skip=1 seek=1 conv=fsync else echo "Did not change the original bootloader." fi # fix wifi macaddr if [ -x /usr/bin/fix_wifi_macaddr.sh ]; then /usr/bin/fix_wifi_macaddr.sh fi # mkfs echo "Start creating file system ... " echo "Create a boot file system ... " echo "format boot partiton..." mkfs.fat -n EMMC_BOOT -F 32 /dev/${EMMC_NAME}p1 mkdir -p /mnt/${EMMC_NAME}p1 sleep 2 umount -f /mnt/${EMMC_NAME}p1 2>/dev/null echo "format rootfs1 partiton..." ROOTFS1_UUID=$(/usr/bin/uuidgen) mkfs.btrfs -f -U ${ROOTFS1_UUID} -L EMMC_ROOTFS1 -m single /dev/${EMMC_NAME}p2 mkdir -p /mnt/${EMMC_NAME}p2 sleep 2 umount -f /mnt/${EMMC_NAME}p2 2>/dev/null echo "format rootfs2 partiton..." ROOTFS2_UUID=$(/usr/bin/uuidgen) mkfs.btrfs -f -U ${ROOTFS2_UUID} -L EMMC_ROOTFS2 -m single /dev/${EMMC_NAME}p3 mkdir -p /mnt/${EMMC_NAME}p3 sleep 2 umount -f /mnt/${EMMC_NAME}p3 2>/dev/null # mount and copy echo "Wait for the boot file system to mount ... " i=1 max_try=10 while [ $i -le $max_try ]; do mount -t vfat /dev/${EMMC_NAME}p1 /mnt/${EMMC_NAME}p1 2>/dev/null sleep 2 mnt=$(lsblk -l -o MOUNTPOINT | grep /mnt/${EMMC_NAME}p1) if [ "$mnt" == "" ]; then if [ $i -lt $max_try ]; then echo "Not mounted successfully, try again ..." i=$((i + 1)) else error_msg "Cannot mount the boot file system, give up!" fi else echo "Successfully mounted." echo "copy boot ..." cd /mnt/${EMMC_NAME}p1 rm -rf /boot/'System Volume Information/' (cd /boot && tar cf - .) | tar xf - sync echo "Edit uEnv.txt ..." cat >uEnv.txt <<EOF LINUX=/zImage INITRD=/uInitrd FDT=/dtb/amlogic/${FDTFILE} APPEND=root=UUID=${ROOTFS1_UUID} rootfstype=btrfs rootflags=compress=zstd:${ZSTD_LEVEL} console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1 EOF # Replace the UUID for extlinux/extlinux.conf if it exists [[ -f "extlinux/extlinux.conf" ]] && { sed -i -E "s|UUID=[^ ]*|UUID=${ROOTFS1_UUID}|" extlinux/extlinux.conf 2>/dev/null } rm -f s905_autoscript* aml_autoscript* if [ ${K510} -eq 1 ]; then if [ -f ${UBOOT_OVERLOAD} ]; then cp -f -v ${UBOOT_OVERLOAD} u-boot.emmc elif [ -f "u-boot.ext" ]; then cp -f -v u-boot.ext u-boot.emmc fi fi mv -f boot-emmc.ini boot.ini mv -f boot-emmc.cmd boot.cmd mv -f boot-emmc.scr boot.scr sync echo "complete." cd / umount -f /mnt/${EMMC_NAME}p1 break fi done echo "complete." echo "Wait for the rootfs file system to mount ... " i=1 while [ $i -le $max_try ]; do mount -t btrfs -o compress=zstd:${ZSTD_LEVEL} /dev/${EMMC_NAME}p2 /mnt/${EMMC_NAME}p2 2>/dev/null sleep 2 mnt=$(lsblk -l -o MOUNTPOINT | grep /mnt/${EMMC_NAME}p2) if [ "$mnt" == "" ]; then if [ $i -lt $max_try ]; then echo "Not mounted successfully, try again ..." i=$((i + 1)) else error_msg "Cannot mount rootfs file system, give up!" fi else echo "Successfully mounted" echo "Create folder ... " cd /mnt/${EMMC_NAME}p2 btrfs subvolume create etc mkdir -p bin boot dev lib opt mnt overlay proc rom root run sbin sys tmp usr www .reserved .snapshots ln -sf lib/ lib64 ln -sf tmp/ var sync echo "complete." COPY_SRC="root etc bin sbin lib opt usr www" echo "Copy data ... " for src in $COPY_SRC; do echo "copy [ $src ] ..." (cd / && tar cf - $src) | tar xf - sync done echo "Copy complete." sync cat >etc/docker/daemon.json <<EOF { "bip": "172.31.0.1/24", "data-root": "/mnt/${EMMC_NAME}p4/docker/", "log-level": "warn", "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "5" }, "registry-mirrors": [ "https://mirror.baidubce.com/", "https://hub-mirror.c.163.com" ] } EOF # change data_root value in /etc/config/dockerd if [[ -f "/etc/init.d/dockerman" ]] && [[ -f "/etc/config/dockerd" ]]; then sed -i "s|option data_root.*|option data_root '/mnt/${EMMC_NAME}p4/docker/'|g" etc/config/dockerd fi rm -rf opt/docker && ln -sf /mnt/${EMMC_NAME}p4/docker/ opt/docker >/dev/null rm -rf usr/bin/AdGuardHome && ln -sf /mnt/${EMMC_NAME}p4/AdGuardHome usr/bin/ >/dev/null echo "Edit configuration file ..." #cd /mnt/${EMMC_NAME}p2/usr/bin/ #rm -f openwrt-install-amlogic openwrt-update-amlogic cd /mnt/${EMMC_NAME}p2/etc/rc.d ln -sf ../init.d/dockerd S99dockerd rm -f S??shortcut-fe if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then ln -sf ../init.d/shortcut-fe S99shortcut-fe fi fi cd /mnt/${EMMC_NAME}p2/etc cat >fstab <<EOF UUID=${ROOTFS1_UUID} / btrfs compress=zstd:${ZSTD_LEVEL} 0 1 LABEL=EMMC_BOOT /boot vfat defaults 0 2 #tmpfs /tmp tmpfs defaults,nosuid 0 0 EOF cd /mnt/${EMMC_NAME}p2/etc/config cat >fstab <<EOF config global option anon_swap '0' option anon_mount '1' option auto_swap '0' option auto_mount '1' option delay_root '5' option check_fs '0' config mount option target '/rom' option uuid '${ROOTFS1_UUID}' option enabled '1' option enabled_fsck '1' option fstype 'btrfs' option options 'compress=zstd:${ZSTD_LEVEL}' config mount option target '/boot' option label 'EMMC_BOOT' option enabled '1' option enabled_fsck '1' option fstype 'vfat' EOF echo -n "Create initial etc snapshot -> .snapshots/etc-000" cd /mnt/${EMMC_NAME}p2 && btrfs subvolume snapshot -r etc .snapshots/etc-000 sync cd / umount -f /mnt/${EMMC_NAME}p2 break fi done echo "complete." echo "Create a shared file system." mkdir -p /mnt/${EMMC_NAME}p4 # When there is no input parameter, select manually if [[ -n "${SHARED_FSTYPE}" ]]; then TARGET_SHARED_FSTYPE=${SHARED_FSTYPE} else cat <<EOF --------------------------------------------------------------------------------- Please select the type of shared file system: 1. ext4: [Default options] suitable for general use. 2. btrfs: Which can extend the service life of ssd/mmc. 3. f2fs: Fast reading and writing speed, but the compatibility is slightly poor. 4. xfs: Very good file system, alternative to ext4. --------------------------------------------------------------------------------- EOF read -p "Please Input ID: " TARGET_SHARED_FSTYPE fi case $TARGET_SHARED_FSTYPE in 2 | btrfs) mkfs.btrfs -f -L EMMC_SHARED -m single /dev/${EMMC_NAME}p4 >/dev/null mount -t btrfs /dev/${EMMC_NAME}p4 /mnt/${EMMC_NAME}p4 ;; 3 | f2fs) mkfs.f2fs -f -l EMMC_SHARED /dev/${EMMC_NAME}p4 >/dev/null mount -t f2fs /dev/${EMMC_NAME}p4 /mnt/${EMMC_NAME}p4 ;; 4 | xfs) mkfs.xfs -f -L EMMC_SHARED /dev/${EMMC_NAME}p4 >/dev/null mount -t xfs /dev/${EMMC_NAME}p4 /mnt/${EMMC_NAME}p4 ;; *) mkfs.ext4 -F -L EMMC_SHARED /dev/${EMMC_NAME}p4 >/dev/null mount -t ext4 /dev/${EMMC_NAME}p4 /mnt/${EMMC_NAME}p4 ;; esac mkdir -p /mnt/${EMMC_NAME}p4/docker /mnt/${EMMC_NAME}p4/AdGuardHome/data sync echo "Successful installed, please unplug the USB, re-insert the power supply to start the openwrt." exit 0
2929004360/ruoyi-sign
2,182
ruoyi-framework/src/main/java/com/ruoyi/framework/config/MybatisPlusConfig.java
package com.ruoyi.framework.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * Mybatis Plus 配置 * * @author ruoyi */ @EnableTransactionManagement(proxyTargetClass = true) @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(paginationInnerInterceptor()); // 乐观锁插件 interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor()); // 阻断插件 interceptor.addInnerInterceptor(blockAttackInnerInterceptor()); return interceptor; } /** * 分页插件,自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html */ public PaginationInnerInterceptor paginationInnerInterceptor() { PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); // 设置数据库类型为mysql paginationInnerInterceptor.setDbType(DbType.MYSQL); // 设置最大单页限制数量,默认 500 条,-1 不受限制 paginationInnerInterceptor.setMaxLimit(-1L); return paginationInnerInterceptor; } /** * 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html */ public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() { return new OptimisticLockerInnerInterceptor(); } /** * 如果是对全表的删除或更新操作,就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html */ public BlockAttackInnerInterceptor blockAttackInnerInterceptor() { return new BlockAttackInnerInterceptor(); } }
2929004360/ruoyi-sign
1,846
ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java
package com.ruoyi.framework.config; import java.util.Random; import com.google.code.kaptcha.text.impl.DefaultTextCreator; /** * 验证码文本生成器 * * @author ruoyi */ public class KaptchaTextCreator extends DefaultTextCreator { private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); @Override public String getText() { Integer result = 0; Random random = new Random(); int x = random.nextInt(10); int y = random.nextInt(10); StringBuilder suChinese = new StringBuilder(); int randomoperands = random.nextInt(3); if (randomoperands == 0) { result = x * y; suChinese.append(CNUMBERS[x]); suChinese.append("*"); suChinese.append(CNUMBERS[y]); } else if (randomoperands == 1) { if ((x != 0) && y % x == 0) { result = y / x; suChinese.append(CNUMBERS[y]); suChinese.append("/"); suChinese.append(CNUMBERS[x]); } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } } else { if (x >= y) { result = x - y; suChinese.append(CNUMBERS[x]); suChinese.append("-"); suChinese.append(CNUMBERS[y]); } else { result = y - x; suChinese.append(CNUMBERS[y]); suChinese.append("-"); suChinese.append(CNUMBERS[x]); } } suChinese.append("=?@" + result); return suChinese.toString(); } }
281677160/openwrt-package
20,861
luci-app-amlogic/root/usr/sbin/openwrt-update-kvm
#!/bin/bash #====================================================================================== # Function: Update the QEMU AARCH64 KVM vitual machine openwrt firmware # Copyright (C) 2022-- https://github.com/unifreq/openwrt_packit # Copyright (C) 2022-- https://github.com/ophub #====================================================================================== # # The script supports directly setting parameters for update, skipping interactive selection # openwrt-update-amlogic ${OPENWRT_FILE} ${AUTO_MAINLINE_UBOOT} ${RESTORE_CONFIG} ${WORK_DIR} # E.g: openwrt-update-kvm openwrt_qemu-aarch64.img.gz no restore /mnt/vda4 # E.g: openwrt-update-kvm openwrt_qemu-aarch64.img.gz no no-restore /mnt/data # You can also execute the script directly, and interactively select related functions # E.g: openwrt-update-kvm # #====================================================================================== # Encountered a serious error, abort the script execution error_msg() { echo -e "[ERROR] ${1}" exit 1 } # Get the partition name of the root file system get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Get the partition message of the root file system get_root_partition_msg() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_msg=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ "^" "'"${path}"'" "$" {print $0}') [[ -n "${partition_msg}" ]] && break done [[ -z "${partition_msg}" ]] && error_msg "Cannot find the root partition message!" echo "${partition_msg}" } # Receive one-key command related parameters IMG_NAME="${1}" AUTO_MAINLINE_UBOOT="${2}" BACKUP_RESTORE_CONFIG="${3}" WORK_DIR="${4}" # Check the necessary dependencies DEPENDS="lsblk uuidgen grep awk btrfs mkfs.fat mkfs.btrfs md5sum fatlabel jq" echo "Check the necessary dependencies..." for dep in ${DEPENDS}; do WITCH=$(busybox which ${dep}) if [ "${WITCH}" == "" ]; then error_msg "Dependent command: ${dep} does not exist, upgrade cannot be performed!" else echo "${dep} path: ${WITCH}" fi done echo "Check passed" # Current device model source /etc/flippy-openwrt-release if [[ -z "${PLATFORM}" ]]; then error_msg "The platform is empty." elif [[ "${PLATFORM}" != "qemu-aarch64" ]]; then error_msg "The platform is missing, only support qemu-aarch64." else echo -e "Current platform: [ ${PLATFORM} ]" sleep 3 fi # Find the partition where root is located # vda2 or vda3 ROOT_PTNAME="$(get_root_partition_name)" # Find the disk where the partition is located, only supports sd?? hd?? vd?? case ${ROOT_PTNAME} in [hsv]d[a-z][1-4]) DISK_NAME=$(echo ${ROOT_PTNAME} | awk '{print substr($1, 1, length($1)-1)}') PART_PRESTR="" LABEL_PRESTR="" ;; *) error_msg "Unable to recognize the disk type of ${ROOT_PTNAME}!" ;; esac function get_docker_root { local data_root if [[ -f /etc/config/dockerd ]]; then data_root=$(uci get dockerd.globals.data_root) fi if [[ -z "${data_root}" ]] && [[ -f /etc/docker/daemon.json ]]; then data_root=$(jq -r '."data-root"' /etc/docker/daemon.json) fi echo "$data_root" } DOCKER_ROOT=$(get_docker_root) if [[ -z "${WORK_DIR}" ]]; then WORK_DIR="/mnt/${DISK_NAME}${PART_PRESTR}4/" fi if [[ ! -d "${WORK_DIR}" ]]; then error_msg "the work directory is not exists. [ ${WORK_DIR} ]" fi cd "${WORK_DIR}" if [[ -d "/tmp/upload" ]] && [[ -f "/tmp/upload/*img*" ]]; then mv -f /tmp/upload/*img* . if [[ $? -ne 0 ]]; then error_msg "move file failed." fi fi sync if [[ "${IMG_NAME}" == *.img ]]; then echo -e "Update using [ ${IMG_NAME} ] file. Please wait a moment ..." elif [ $(ls *.img -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then IMG_NAME=$(ls *.img | head -n 1) echo -e "Update using [ ${IMG_NAME} ] ] file. Please wait a moment ..." elif [ $(ls *.img.xz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then xz_file=$(ls *.img.xz | head -n 1) echo -e "Update using [ ${xz_file} ] file. Please wait a moment ..." xz -d ${xz_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.img.gz -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then gz_file=$(ls *.img.gz | head -n 1) echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..." gzip -df ${gz_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.7z -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then gz_file=$(ls *.7z | head -n 1) echo -e "Update using [ ${gz_file} ] file. Please wait a moment ..." bsdtar -xmf ${gz_file} 2>/dev/null [ $? -eq 0 ] || 7z x ${gz_file} -aoa -y 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) elif [ $(ls *.zip -l 2>/dev/null | grep "^-" | wc -l) -ge 1 ]; then zip_file=$(ls *.zip | head -n 1) echo -e "Update using [ ${zip_file} ] file. Please wait a moment ..." unzip -o ${zip_file} 2>/dev/null IMG_NAME=$(ls *.img | head -n 1) else echo -e "Please upload or specify the update openwrt firmware file." #echo -e "Upload method: system menu → Amlogic Service → Manually Upload Update" echo -e "Specify method: Place the openwrt firmware file in [ ${WORK_DIR} ]" echo -e "The supported file suffixes are: *.img, *.img.xz, *.img.gz, *.7z, *.zip" echo -e "After upload the openwrt firmware file, run again." exit 1 fi sync # check file if [ ! -f "${IMG_NAME}" ]; then error_msg "No update file found." else echo "Start update from [ ${IMG_NAME} ]" fi # find efi partition EFI_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | awk '$3~/^part$/ && $5 ~ /^\/boot\/efi$/ {print $0}') if [ "${EFI_PART_MSG}" == "" ]; then error_msg "The EFI partition does not exist, so the update cannot be continued!" fi EFI_NAME=$(echo $EFI_PART_MSG | awk '{print $1}') EFI_DEV=$(echo $EFI_PART_MSG | awk '{print $2}') EFI_UUID=$(echo $EFI_PART_MSG | awk '{print $4}') BR_FLAG=1 if [[ ${BACKUP_RESTORE_CONFIG} == "restore" ]]; then BR_FLAG=1 elif [[ ${BACKUP_RESTORE_CONFIG} == "no-restore" ]]; then BR_FLAG=0 else echo -ne "Whether to backup and restore the current config files? y/n [y]\b\b" read yn case $yn in n* | N*) BR_FLAG=0 ;; esac fi # find root partition ROOT_PART_MSG="$(get_root_partition_msg)" ROOT_NAME=$(echo ${ROOT_PART_MSG} | awk '{print $1}') ROOT_DEV=$(echo ${ROOT_PART_MSG} | awk '{print $2}') ROOT_UUID=$(echo ${ROOT_PART_MSG} | awk '{print $4}') case ${ROOT_NAME} in ${DISK_NAME}${PART_PRESTR}2) NEW_ROOT_NAME="${DISK_NAME}${PART_PRESTR}3" NEW_ROOT_LABEL="${LABEL_PRESTR}ROOTFS2" ;; ${DISK_NAME}${PART_PRESTR}3) NEW_ROOT_NAME="${DISK_NAME}${PART_PRESTR}2" NEW_ROOT_LABEL="${LABEL_PRESTR}ROOTFS1" ;; *) error_msg "ROOTFS The partition location is incorrect, so the update cannot continue!" ;; esac echo "NEW_ROOT_NAME: [ ${NEW_ROOT_NAME} ]" # find new root partition NEW_ROOT_PART_MSG=$(lsblk -l -o NAME,PATH,TYPE,UUID,MOUNTPOINT | grep "${NEW_ROOT_NAME}" | awk '$3 ~ /^part$/ && $5 !~ /^\/$/ && $5 !~ /^\/boot$/ {print $0}') if [ "${NEW_ROOT_PART_MSG}" == "" ]; then error_msg "The new ROOTFS partition does not exist, so the update cannot continue!" fi NEW_ROOT_NAME=$(echo $NEW_ROOT_PART_MSG | awk '{print $1}') NEW_ROOT_DEV=$(echo $NEW_ROOT_PART_MSG | awk '{print $2}') NEW_ROOT_UUID=$(echo $NEW_ROOT_PART_MSG | awk '{print $4}') NEW_ROOT_MOUNTPOINT=$(echo $NEW_ROOT_PART_MSG | awk '{print $5}') echo "NEW_ROOT_MOUNTPOINT: [ ${NEW_ROOT_MOUNTPOINT} ]" # losetup losetup -f -P $IMG_NAME if [ $? -eq 0 ]; then LOOP_DEV=$(losetup | grep "$IMG_NAME" | awk '{print $1}') if [ "$LOOP_DEV" == "" ]; then error_msg "loop device not found!" fi else error_msg "losetup [ $IMG_FILE ] failed!" fi # fix loopdev issue in kernel 5.19 function fix_loopdev() { local parentdev=${1##*/} if [ ! -d /sys/block/${parentdev} ]; then return fi subdevs=$(lsblk -l -o NAME | grep -E "^${parentdev}.+\$") for subdev in $subdevs; do if [ ! -d /sys/block/${parentdev}/${subdev} ]; then return elif [ -b /dev/${sub_dev} ]; then continue fi source /sys/block/${parentdev}/${subdev}/uevent mknod /dev/${subdev} b ${MAJOR} ${MINOR} unset MAJOR MINOR DEVNAME DEVTYPE DISKSEQ PARTN PARTNAME done } fix_loopdev ${LOOP_DEV} WAIT=3 echo "The loopdev is [ $LOOP_DEV ], wait [ ${WAIT} ] seconds. " while [ $WAIT -ge 1 ]; do sleep 1 WAIT=$((WAIT - 1)) done # umount loop devices (openwrt will auto mount some partition) MOUNTED_DEVS=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "$LOOP_DEV" | awk '$3 !~ /^$/ {print $2}') for dev in $MOUNTED_DEVS; do while :; do echo "umount [ $dev ] ... " umount -f $dev sleep 1 mnt=$(lsblk -l -o NAME,PATH,MOUNTPOINT | grep "$dev" | awk '$3 !~ /^$/ {print $2}') if [ "$mnt" == "" ]; then break else echo "Retry ..." fi done done # mount src part P1=${WORK_DIR}/efi P2=${WORK_DIR}/root mkdir -p $P1 $P2 echo "Mount [ ${LOOP_DEV}p1 ] -> [ ${P1} ] ... " mount -t vfat -o ro ${LOOP_DEV}p1 ${P1} if [ $? -ne 0 ]; then echo "Mount p1 [ ${LOOP_DEV}p1 ] failed!" losetup -D exit 1 fi echo "Mount [ ${LOOP_DEV}p2 ] -> [ ${P2} ] ... " ZSTD_LEVEL="6" mount -t btrfs -o ro,compress=zstd:${ZSTD_LEVEL} ${LOOP_DEV}p2 ${P2} if [ $? -ne 0 ]; then echo "Mount p2 [ ${LOOP_DEV}p2 ] failed!" umount -f ${P1} losetup -D exit 1 fi # Prepare the dockerman config file if [ -f ${P2}/etc/init.d/dockerman ] && [ -f ${P2}/etc/config/dockerd ]; then flg=0 # get current docker data root data_root=$(uci get dockerd.globals.data_root 2>/dev/null) if [ "$data_root" == "" ]; then flg=1 # get current config from /etc/docker/daemon.json if [ -f "/etc/docker/daemon.json" ] && [ -x "/usr/bin/jq" ]; then data_root=$(jq -r '."data-root"' /etc/docker/daemon.json) bip=$(jq -r '."bip"' /etc/docker/daemon.json) [ "$bip" == "null" ] && bip="172.31.0.1/24" log_level=$(jq -r '."log-level"' /etc/docker/daemon.json) [ "$log_level" == "null" ] && log_level="warn" _iptables=$(jq -r '."iptables"' /etc/docker/daemon.json) [ "$_iptables" == "null" ] && _iptables="true" registry_mirrors=$(jq -r '."registry-mirrors"[]' /etc/docker/daemon.json 2>/dev/null) fi fi if [ "$data_root" == "" ]; then data_root="/opt/docker/" # the default data root fi if ! uci get dockerd.globals >/dev/null 2>&1; then uci set dockerd.globals='globals' uci commit fi # delete alter config , use inner config if uci get dockerd.globals.alt_config_file >/dev/null 2>&1; then uci delete dockerd.globals.alt_config_file uci commit fi if [ $flg -eq 1 ]; then uci set dockerd.globals.data_root=$data_root [ "$bip" != "" ] && uci set dockerd.globals.bip=$bip [ "$log_level" != "" ] && uci set dockerd.globals.log_level=$log_level [ "$_iptables" != "" ] && uci set dockerd.globals.iptables=$_iptables if [ "$registry_mirrors" != "" ]; then for reg in $registry_mirrors; do uci add_list dockerd.globals.registry_mirrors=$reg done fi uci set dockerd.globals.auto_start='1' uci commit fi fi #format NEW_ROOT echo "umount [ ${NEW_ROOT_MOUNTPOINT} ]" umount -f "${NEW_ROOT_MOUNTPOINT}" if [ $? -ne 0 ]; then echo "Umount [ ${NEW_ROOT_MOUNTPOINT} ] failed, Please restart and try again!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi echo "Format [ ${NEW_ROOT_DEV} ]" NEW_ROOT_UUID=$(uuidgen) mkfs.btrfs -f -U ${NEW_ROOT_UUID} -L ${NEW_ROOT_LABEL} ${NEW_ROOT_DEV} if [ $? -ne 0 ]; then echo "Format [ ${NEW_ROOT_DEV} ] failed!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi echo "Mount [ ${NEW_ROOT_DEV} ] -> [ ${NEW_ROOT_MOUNTPOINT} ]" mount -t btrfs -o compress=zstd:${ZSTD_LEVEL} ${NEW_ROOT_DEV} ${NEW_ROOT_MOUNTPOINT} if [ $? -ne 0 ]; then echo "Mount [ ${NEW_ROOT_DEV} ] -> [ ${NEW_ROOT_MOUNTPOINT} ] failed!" umount -f ${P1} umount -f ${P2} losetup -D exit 1 fi # begin copy rootfs cd ${NEW_ROOT_MOUNTPOINT} echo "Start copying data, From [ ${P2} ] TO [ ${NEW_ROOT_MOUNTPOINT} ] ..." ENTRYS=$(ls) for entry in $ENTRYS; do if [ "$entry" == "lost+found" ]; then continue fi echo "Remove old [ $entry ] ... " rm -rf $entry if [ $? -ne 0 ]; then error_msg "failed." fi done echo "Create folder ... " btrfs subvolume create etc mkdir -p .snapshots .reserved bin boot dev lib opt mnt overlay proc rom root run sbin sys tmp usr www ln -sf lib/ lib64 ln -sf tmp/ var sync COPY_SRC="boot root etc bin sbin lib opt usr www" echo "Copy data begin ... " for src in $COPY_SRC; do echo "Copy [ $src ] ... " (cd ${P2} && tar cf - $src) | tar xf - sync done # if not backup, then force rewrite the etc/docker/daemon.json if [ "${BR_FLAG}" -eq 0 ]; then cat >./etc/docker/daemon.json <<EOF { "bip": "172.31.0.1/24", "data-root": "${DOCKER_ROOT}", "log-level": "warn", "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "5" }, "registry-mirrors": [ "https://mirror.baidubce.com/", "https://hub-mirror.c.163.com" ] } EOF fi cat >./etc/fstab <<EOF UUID=${NEW_ROOT_UUID} / btrfs compress=zstd:${ZSTD_LEVEL} 0 1 LABEL=EFI /boot/efi vfat defaults 0 2 #tmpfs /tmp tmpfs defaults,nosuid 0 0 EOF cat >./etc/config/fstab <<EOF config global option anon_swap '0' option anon_mount '1' option auto_swap '0' option auto_mount '1' option delay_root '5' option check_fs '0' config mount option target '/rom' option uuid '${NEW_ROOT_UUID}' option enabled '1' option enabled_fsck '1' option fstype 'btrfs' option options 'compress=zstd:${ZSTD_LEVEL}' config mount option target '/boot/efi' option label 'EFI' option enabled '1' option enabled_fsck '1' option fstype 'vfat' EOF ( cd etc/rc.d rm -f S??shortcut-fe if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then ln -sf ../init.d/shortcut-fe S99shortcut-fe fi fi ) # move /etc/config/balance_irq to /etc/balance_irq [ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/ sync echo "Create initial etc snapshot -> .snapshots/etc-000" btrfs subvolume snapshot -r etc .snapshots/etc-000 sync [ -d /mnt/${DISK_NAME}${PART_PRESTR}4/docker ] || mkdir -p /mnt/${DISK_NAME}${PART_PRESTR}4/docker rm -rf opt/docker && ln -sf /mnt/${DISK_NAME}${PART_PRESTR}4/docker/ opt/docker if [ -f /mnt/${NEW_ROOT_NAME}/etc/config/AdGuardHome ]; then [ -d /mnt/${DISK_NAME}${PART_PRESTR}4/AdGuardHome/data ] || mkdir -p /mnt/${DISK_NAME}${PART_PRESTR}4/AdGuardHome/data if [ ! -L /usr/bin/AdGuardHome ]; then [ -d /usr/bin/AdGuardHome ] && cp -a /usr/bin/AdGuardHome/* /mnt/${DISK_NAME}${PART_PRESTR}4/AdGuardHome/ fi ln -sf /mnt/${DISK_NAME}${PART_PRESTR}4/AdGuardHome /mnt/${NEW_ROOT_NAME}/usr/bin/AdGuardHome fi sync echo "Copy data complete ..." BACKUP_LIST=$(${P2}/usr/sbin/openwrt-backup -p) if [[ "${BR_FLAG}" -eq "1" && -n "${BACKUP_LIST}" ]]; then echo -n "Start restoring configuration files ... " ( cd / eval tar czf ${NEW_ROOT_MOUNTPOINT}/.reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null ) tar xzf ${NEW_ROOT_MOUNTPOINT}/.reserved/openwrt_config.tar.gz [ -f ./etc/config/dockerman ] && sed -e "s/option wan_mode 'false'/option wan_mode 'true'/" -i ./etc/config/dockerman 2>/dev/null [ -f ./etc/config/dockerd ] && sed -e "s/option wan_mode '0'/option wan_mode '1'/" -i ./etc/config/dockerd 2>/dev/null [ -f ./etc/config/verysync ] && sed -e 's/config setting/config verysync/' -i ./etc/config/verysync 2>/dev/null # Restore fstab cp -f .snapshots/etc-000/fstab ./etc/fstab cp -f .snapshots/etc-000/config/fstab ./etc/config/fstab # 还原 luci cp -f .snapshots/etc-000/config/luci ./etc/config/luci # 还原/etc/config/rpcd cp -f .snapshots/etc-000/config/rpcd ./etc/config/rpcd sync echo "Restore configuration information complete." fi echo "Modify the configuration file ... " rm -f "./etc/rc.local.orig" "./etc/first_run.sh" "./etc/part_size" rm -rf "./opt/docker" && ln -sf "/mnt/${DISK_NAME}${PART_PRESTR}4/docker" "./opt/docker" rm -f ./etc/bench.log cat >>./etc/crontabs/root <<EOF 37 5 * * * /etc/coremark.sh EOF sss=$(date +%s) ddd=$((sss / 86400)) sed -e "s/:0:0:99999:7:::/:${ddd}:0:99999:7:::/" -i ./etc/shadow # Fix the problem of repeatedly adding amule entries after each upgrade sed -e "/amule:x:/d" -i ./etc/shadow # Fix the problem of repeatedly adding sshd entries after each upgrade of dropbear sed -e "/sshd:x:/d" -i ./etc/shadow if ! grep "sshd:x:22:sshd" ./etc/group >/dev/null; then echo "sshd:x:22:sshd" >>./etc/group fi if ! grep "sshd:x:22:22:sshd:" ./etc/passwd >/dev/null; then echo "sshd:x:22:22:sshd:/var/run/sshd:/bin/false" >>./etc/passwd fi if ! grep "sshd:x:" ./etc/shadow >/dev/null; then echo "sshd:x:${ddd}:0:99999:7:::" >>./etc/shadow fi if [ "${BR_FLAG}" -eq "1" ]; then if [ -x ./bin/bash ] && [ -f ./etc/profile.d/30-sysinfo.sh ]; then sed -e 's/\/bin\/ash/\/bin\/bash/' -i ./etc/passwd fi sync fi sed -e "s/option hw_flow '1'/option hw_flow '0'/" -i ./etc/config/turboacc ( cd etc/rc.d rm -f S??shortcut-fe if grep "sfe_flow '1'" ../config/turboacc >/dev/null; then if find ../../lib/modules -name 'shortcut-fe-cm.ko'; then ln -sf ../init.d/shortcut-fe S99shortcut-fe fi fi ) eval tar czf .reserved/openwrt_config.tar.gz "${BACKUP_LIST}" 2>/dev/null rm -f ./etc/part_size ./etc/first_run.sh if [ -x ./usr/sbin/balethirq.pl ]; then if grep "balethirq.pl" "./etc/rc.local"; then echo "balance irq is enabled" else echo "enable balance irq" sed -e "/exit/i\/usr/sbin/balethirq.pl" -i ./etc/rc.local fi fi mv ./etc/rc.local ./etc/rc.local.orig cat >"./etc/rc.local" <<EOF if ! ls /etc/rc.d/S??dockerd >/dev/null 2>&1;then /etc/init.d/dockerd enable /etc/init.d/dockerd start fi if ! ls /etc/rc.d/S??dockerman >/dev/null 2>&1 && [ -f /etc/init.d/dockerman ];then /etc/init.d/dockerman enable /etc/init.d/dockerman start fi mv /etc/rc.local.orig /etc/rc.local chmod 755 /etc/rc.local exec /etc/rc.local exit EOF chmod 755 ./etc/rc.local* # move /etc/config/balance_irq to /etc/balance_irq [ -f "./etc/config/balance_irq" ] && mv ./etc/config/balance_irq ./etc/ echo "Create etc snapshot -> .snapshots/etc-001" btrfs subvolume snapshot -r etc .snapshots/etc-001 cd ${WORK_DIR} echo "Copy efi files ..." fatlabel ${EFI_DEV} "EFI" cd /boot/efi mv ./EFI/BOOT/grub.cfg /tmp/grub.cfg.prev rm -rf * cp -a ${P1}/* . # 如果想启动上一个版本的openwrt,可以把 /boot/efi/EFI/BOOT/grub.cfg.prev 复制成 /boot/efi/EFI/BOOT/grub.cfg mv /tmp/grub.cfg.prev ./EFI/BOOT/ echo "Modify efi configuration ... " cd /boot/efi/EFI/BOOT cat >grub.cfg <<EOF echo "search fs_uuid ${NEW_ROOT_UUID} ..." search.fs_uuid ${NEW_ROOT_UUID} root echo "root=\$root" echo "set prefix ... " set prefix=(\$root)'/boot/grub2' echo "prefix=\$prefix" source \${prefix}/grub.cfg EOF echo "Modify boot configuration ... " cd ${NEW_ROOT_MOUNTPOINT}/boot/grub2 cat >grub.cfg <<EOF insmod gzio insmod part_gpt insmod zstd insmod btrfs terminal_input console terminal_output console set default="0" set timeout=3 menuentry "OpenWrt" { echo 'Loading linux kernel ...' linux /boot/vmlinuz root=UUID=${NEW_ROOT_UUID} rootfstype=btrfs rootflags=compress=zstd:${ZSTD_LEVEL} console=ttyAMA0,115200n8 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1 echo 'Loading initial ramdisk ...' initrd /boot/initrd.img } EOF sync cd $WORK_DIR umount -f ${P1} ${P2} 2>/dev/null losetup -D 2>/dev/null rm -rf ${P1} ${P2} 2>/dev/null rm -f ${IMG_NAME} 2>/dev/null rm -f sha256sums 2>/dev/null sync wait echo "Successfully updated, automatic restarting..." sleep 3 reboot exit 0
2929004360/ruoyi-sign
1,034
ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedissonConfig.java
package com.ruoyi.framework.config; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * redisson配置 * * @author ruoyi */ @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Value("${spring.redis.password}") private String password; @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean(RedissonClient.class) public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer().setAddress("redis://" + host + ":" + port ); config.useSingleServer().setPassword(password); return Redisson.create(config); } }
281677160/openwrt-package
3,947
luci-app-amlogic/root/usr/sbin/fixcpufreq.pl
#!/usr/bin/perl use strict; use File::Basename; my $uci_config_name; if(-f "/etc/config/amlogic") { $uci_config_name="amlogic"; } elsif(-f "/etc/config/cpufreq") { $uci_config_name="cpufreq"; } else { print "Can not found amlogic or cpufreq config file!\n"; exit(0); } my @policy_ids; my @policy_homes = </sys/devices/system/cpu/cpufreq/policy?>; if(@policy_homes) { foreach my $policy_home (@policy_homes) { push @policy_ids, substr($policy_home, -1); } } else { print "Can not found any policy!\n"; exit 0; } our $need_commit = 0; for(my $i=0; $i <= $#policy_ids; $i++) { &fix_invalid_value($uci_config_name, $policy_ids[$i], $policy_homes[$i]); } if($need_commit > 0) { &uci_commit($uci_config_name); } exit 0; ################################# function #################################### sub fix_invalid_value { my($uci_config, $policy_id, $policy_home) = @_; my %gove_hash = &get_gove_hash($policy_home); my @freqs = &get_freq_list($policy_home); my %freq_hash = &get_freq_hash(@freqs); my $min_freq = &get_min_freq(@freqs); my $max_freq = &get_max_freq(@freqs); my $uci_section = "settings"; my $uci_option; if($uci_config eq "cpufreq" ) { $uci_option = "governor"; } else { $uci_option = "governor" . $policy_id; } # 如果未设置 governor, 或该 goveernor 不存在, 则修败默认值为 schedutil my $config_gove = &uci_get_by_type($uci_config, $uci_section, $uci_option, "NA"); if( ($config_gove eq "NA") || ($gove_hash{$config_gove} != 1)) { &uci_set_by_type($uci_config, $uci_section, $uci_option, "schedutil"); $need_commit++; } # 如果出现不存在的 minfreq, 则修改为实际的 min_freq if($uci_config eq "cpufreq" ) { # "minifreq" is a spelling error that has always existed in the upstream source code $uci_option = "minifreq"; } else { $uci_option = "minfreq" . $policy_id; } my $config_min_freq = &uci_get_by_type($uci_config, $uci_section, $uci_option, "0"); if($freq_hash{$config_min_freq} != 1) { &uci_set_by_type($uci_config, $uci_section, $uci_option, $min_freq); $need_commit++; } # 如果出现不存在的 maxfreq # 或 maxfreq < minfreq, 则修改为实际的 max_freq if($uci_config eq "cpufreq" ) { $uci_option = "maxfreq"; } else { $uci_option = "maxfreq" . $policy_id; } my $config_max_freq = &uci_get_by_type($uci_config, $uci_section, $uci_option, "0"); if( ( $freq_hash{$config_max_freq} != 1) || ( $config_max_freq < $config_min_freq)) { &uci_set_by_type($uci_config, $uci_section, $uci_option, $max_freq); $need_commit++; } } sub get_freq_list { my $policy_home = shift; my @ret_ary; open my $fh, "<", "${policy_home}/scaling_available_frequencies" or die; $_ = <$fh>; chomp; @ret_ary = split /\s+/; close($fh); return @ret_ary; } sub get_freq_hash { my @freq_ary = @_; my %ret_hash; foreach my $freq (@freq_ary) { if($freq =~ m/\d+/) { $ret_hash{$freq} = 1; } } return %ret_hash; } sub get_min_freq { my @freq_ary = @_; return (sort {$a<=>$b} @freq_ary)[0]; } sub get_max_freq { my @freq_ary = @_; return (sort {$a<=>$b} @freq_ary)[-1]; } sub get_gove_hash { my $policy_home = shift; my %ret_hash; open my $fh, "<", "${policy_home}/scaling_available_governors" or die; $_ = <$fh>; chomp; my @gov_ary = split /\s+/; foreach my $gov (@gov_ary) { #print "gov: $gov\n"; if($gov =~ m/\w+/) { $ret_hash{$gov} = 1; } } close($fh); return %ret_hash; } sub uci_get_by_type { my($config,$section,$option,$default) = @_; my $ret; $ret=`uci get ${config}.\@${section}\[0\].${option} 2>/dev/null`; # 消除回车换行 $ret =~ s/[\n\r]//g; if($ret eq '') { return $default; } else { return $ret; } } sub uci_set_by_type { my($config,$section,$option,$value) = @_; my $ret; system("uci set ${config}.\@${section}\[0\].${option}=${value}"); return; } sub uci_commit { my $config = shift; system("uci commit ${config}"); return; }
2929004360/ruoyi-sign
2,446
ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java
package com.ruoyi.framework.config; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置 * * @author ruoyi */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean @SuppressWarnings(value = { "unchecked", "rawtypes" }) public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); // 使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); // Hash的key也采用StringRedisSerializer的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.afterPropertiesSet(); return template; } @Bean public DefaultRedisScript<Long> limitScript() { DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); redisScript.setScriptText(limitScriptText()); redisScript.setResultType(Long.class); return redisScript; } /** * 限流脚本 */ private String limitScriptText() { return "local key = KEYS[1]\n" + "local count = tonumber(ARGV[1])\n" + "local time = tonumber(ARGV[2])\n" + "local current = redis.call('get', key);\n" + "if current and tonumber(current) > count then\n" + " return tonumber(current);\n" + "end\n" + "current = redis.call('incr', key)\n" + "if tonumber(current) == 1 then\n" + " redis.call('expire', key, time)\n" + "end\n" + "return tonumber(current);"; } }
281677160/openwrt-package
5,742
luci-app-amlogic/root/usr/sbin/openwrt-ddbr
#!/bin/bash #=========================================================================== # # This file is licensed under the terms of the GNU General Public # License version 2. This program is licensed "as is" without any # warranty of any kind, whether express or implied. # # This file is a part of the make OpenWrt for Amlogic s9xxx tv box # https://github.com/ophub/luci-app-amlogic # # Description: Backup and restore the system in emmc # Copyright (C) 2017- The function borrowed from armbian/ddbr, Author: xXx # Copyright (C) 2021- https://github.com/unifreq/openwrt_packit # Copyright (C) 2021- https://github.com/ophub/luci-app-amlogic # # Command: openwrt-ddbr # #========================= Set default parameters =========================== # # Set font color blue_font_prefix="\033[34m" purple_font_prefix="\033[35m" green_font_prefix="\033[32m" yellow_font_prefix="\033[33m" red_font_prefix="\033[31m" font_color_suffix="\033[0m" INFO="[${blue_font_prefix}INFO${font_color_suffix}]" STEPS="[${purple_font_prefix}STEPS${font_color_suffix}]" SUCCESS="[${green_font_prefix}SUCCESS${font_color_suffix}]" OPT="[${yellow_font_prefix}OPT${font_color_suffix}]" ERROR="[${red_font_prefix}ERROR${font_color_suffix}]" # # Check the output path out_path="/ddbr" # File name for backup/restore ddbr_image="BACKUP-arm-64-emmc.img.gz" # Need remaining space, unit: GB need_space="2" # #=========================================================================== # Encountered a serious error, abort the script execution error_msg() { echo -e "${ERROR} ${1}" exit 1 } # Get the partition name of the root file system get_root_partition_name() { local paths=("/" "/overlay" "/rom") local partition_name for path in "${paths[@]}"; do partition_name=$(df "${path}" | awk 'NR==2 {print $1}' | awk -F '/' '{print $3}') [[ -n "${partition_name}" ]] && break done [[ -z "${partition_name}" ]] && error_msg "Cannot find the root partition!" echo "${partition_name}" } # Check emmc do_checkemmc() { # Get device name mydevice_name="$(cat /proc/device-tree/model | tr -d '\000')" echo -e "${INFO} The device name: [ ${mydevice_name} ]" # Find the partition where root is located root_ptname="$(get_root_partition_name)" # Find the EMMC drive emmc="$(lsblk -l -o NAME | grep -oE "mmcblk[0-9]boot0" | sort | uniq | sed "s/boot0//g")" # Find emmc disk, find emmc that does not contain the boot0 partition [[ -z "${emmc}" ]] && emmc="$(lsblk -l -o NAME | grep -oE '(mmcblk[0-9]?)' | grep -vE ^${root_ptname:0:-2} | uniq)" # Check if emmc exists [[ -z "${emmc}" ]] && error_msg "The eMMC storage not found in this device!" # Show the emmc name echo -e "${INFO} The device eMMC name: [ /dev/${emmc} ]" # Find the disk where the partition is located, only supports mmcblk?p? sd?? hd?? vd?? and other formats case "${root_ptname}" in mmcblk?p[1-4]) disk_name="$(echo ${root_ptname} | awk '{print substr($1, 1, length($1)-2)}')" if lsblk -l -o NAME | grep "${disk_name}boot0" >/dev/null; then error_msg "The current system is running on emmc. Please perform backup/restore operation in [ SD/TF/USB ]!" fi link_ptname="p" ;; [hsv]d[a-z][1-4]) disk_name="$(echo ${root_ptname} | awk '{print substr($1, 1, length($1)-1)}')" link_ptname="" ;; nvme?n?p[1-4]) disk_name="$(echo ${root_ptname} | awk '{print substr($1, 1, length($1)-2)}')" link_ptname="p" ;; *) error_msg "Unable to recognize the disk type of ${root_ptname}!" ;; esac # Set check parameters out_path="/mnt/${disk_name}${link_ptname}4" dev_intsize="$(fdisk -s /dev/${emmc})" [[ -z "$(echo "${dev_intsize}" | sed -n "/^[0-9]\+$/p")" ]] && error_msg "Unable to get EMMC size." echo -e "${INFO} The device EMMC size: [ $(($dev_intsize / 1024 / 1024))GB ]" # check directory [[ -d "${out_path}" ]] || mkdir -p ${out_path} echo -e "${INFO} The ddbr file path: [ ${out_path}/${ddbr_image} ]\n" } # Check the remaining space do_checkspace() { remaining_space="$(df -Tk ${out_path} | grep '/dev/' | awk '{print $5}' | echo $(($(xargs) / 1024 / 1024)))" if [[ -z "$(echo "${remaining_space}" | sed -n "/^[0-9]\+$/p")" ]]; then error_msg "The path is not available, the remaining space cannot be obtained." fi if [[ "${remaining_space}" -lt "${need_space}" ]]; then error_msg "The remaining space is [ ${remaining_space} ] Gb, and more than [ ${need_space} ] Gb space is required." fi } # Backup the emmc system do_backup() { echo -e "${STEPS} Start to backup the system in emmc." do_checkspace echo -e "Saving and Compressing [ /dev/${emmc} ] to [ ${out_path}/${ddbr_image} ], Please wait..." rm -f ${out_path}/${ddbr_image} 2>/dev/null && sync dd if=/dev/${emmc} | pv -s ${dev_intsize}"K" | gzip >${out_path}/${ddbr_image} [[ "${?}" -eq "0" ]] && sync && echo -e "${SUCCESS} Backup is complete." } # Restore the emmc system do_restore() { echo -e "${STEPS} Start to restore the system in emmc." [[ ! -f ${out_path}/${ddbr_image} ]] && error_msg "The [ ${out_path}/${ddbr_image} ] File not found." echo -e "Restoring [ ${out_path}/${ddbr_image} ] to [ /dev/${emmc} ], Please wait..." gunzip -c ${out_path}/${ddbr_image} | pv -s ${dev_intsize}"K" | dd of=/dev/${emmc} [[ "${?}" -eq "0" ]] && sync && echo -e "${SUCCESS} Restore is complete." } echo -e "${STEPS} Welcome to use the EMMC system backup/restore service." # Check script permission [[ -x "/usr/sbin/openwrt-ddbr" ]] || error_msg "Please grant execution permission: [ chmod +x /usr/sbin/openwrt-ddbr ]" # Check emmc do_checkemmc # Prompt the user to select backup/restore echo -ne "${OPT} Do you want to backup or restore? Backup=(b) Restore=(r): " read br case "${br}" in b | B | backup) do_backup ;; r | R | restore) do_restore ;; *) exit 0 ;; esac
2929004360/ruoyi-sign
2,448
ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java
package com.ruoyi.framework.config; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.CacheControl; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.constant.Constants; import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor; /** * 通用配置 * * @author ruoyi */ @Configuration public class ResourcesConfig implements WebMvcConfigurer { @Autowired private RepeatSubmitInterceptor repeatSubmitInterceptor; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** 本地文件上传路径 */ registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**") .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/"); /** swagger配置 */ registry.addResourceHandler("/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/") .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic()); } /** * 自定义拦截规则 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); } /** * 跨域配置 */ @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 设置访问源地址 config.addAllowedOriginPattern("*"); // 设置访问源请求头 config.addAllowedHeader("*"); // 设置访问源请求方法 config.addAllowedMethod("*"); // 有效期 1800秒 config.setMaxAge(1800L); // 添加映射路径,拦截一切请求 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); // 返回新的CorsFilter return new CorsFilter(source); } }