code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package com.zmops.iot.domain.sys;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author nantian created at 2021/7/30 20:31
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "sys_user")
@Entity
public class SysUser extends BaseEntity {
@Id
Long userId;
String account;
String password;
String status;
String email;
String name;
String phone;
String salt;
Long userGroupId;
Long roleId;
String zbxToken;
String zbxId;
private Long tenantId;
String remark;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysUser.java
|
Java
|
gpl-3.0
| 695
|
package com.zmops.iot.domain.sys;
import com.zmops.iot.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei created at 2021/7/30 20:31
*/
@EqualsAndHashCode(callSuper = false)
@Data
@Table(name = "sys_user_group")
@Entity
public class SysUserGroup extends BaseEntity {
@Id
Long userGroupId;
String groupName;
String zbxId;
String status;
String remark;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/SysUserGroup.java
|
Java
|
gpl-3.0
| 551
|
package com.zmops.iot.domain.sys;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author yefei
**/
@Data
@Table(name = "token")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Token {
@Id
private Integer tokenId;
private String name;
private String description;
private Long userId;
private String token;
private String status;
private Long expiresAt;
private String account;
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/domain/sys/Token.java
|
Java
|
gpl-3.0
| 611
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.enums;
import lombok.Getter;
/**
* 公共状态
*
* @author fengshuonan
*/
public enum CommonStatus {
ENABLE("ENABLE", "启用"),
DISABLE("DISABLE", "禁用");
@Getter
String code;
@Getter
String message;
CommonStatus(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (CommonStatus s : CommonStatus.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/enums/CommonStatus.java
|
Java
|
gpl-3.0
| 1,376
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.enums;
import lombok.Getter;
/**
* 公共状态
*
* @author fengshuonan
*/
public enum CommonTimeUnit {
S("s", "秒"),
M("m", "分"),
H("h", "小时"),
D("d", "天");
@Getter
String code;
@Getter
String message;
CommonTimeUnit(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (CommonTimeUnit s : CommonTimeUnit.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/enums/CommonTimeUnit.java
|
Java
|
gpl-3.0
| 1,397
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.enums;
import lombok.Getter;
/**
* 是否来自产品 状态
*
* @author yefei
*/
public enum InheritStatus {
NO("0", "否"),
YES("1", "是");
@Getter
String code;
@Getter
String message;
InheritStatus(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (InheritStatus s : InheritStatus.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/enums/InheritStatus.java
|
Java
|
gpl-3.0
| 1,362
|
package com.zmops.iot.enums;
import lombok.Getter;
/**
* @author yefei
**/
@Getter
public enum SeverityEnum {
INFO("信息", "1"),
WARN("低级", "2"),
ALARM("中级", "3"),
HIGH("高级", "4"),
DISASTER("紧急", "5");
String code;
String value;
SeverityEnum(String code, String value) {
this.code = code;
this.value = value;
}
public static String getVal(String status) {
if (status == null) {
return "";
} else {
for (SeverityEnum s : SeverityEnum.values()) {
if (s.getCode().equals(status)) {
return s.getValue();
}
}
return "0";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/enums/SeverityEnum.java
|
Java
|
gpl-3.0
| 732
|
package com.zmops.iot.enums;
import lombok.Getter;
/**
* @author yefei
**/
@Getter
public enum ValueType {
CHARACTER("character", "字符型"),
NOTSUPPORT("not supported", "不支持的类型"),
LOG("log", "日志型"),
FLOAT("numeric (float)", "单精度型"),
NUMERIC("numeric (unsigned)", "数值型"),
TEXT("text", "文本型"),
AVG("avg", "平均值");
String code;
String value;
ValueType(String code, String value) {
this.code = code;
this.value = value;
}
public static String getVal(String status) {
if (status == null) {
return "";
} else {
for (ValueType s : ValueType.values()) {
if (s.getCode().equals(status)) {
return s.getValue();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/enums/ValueType.java
|
Java
|
gpl-3.0
| 868
|
package com.zmops.iot.model.exception;
/**
* @author nantian created at 2021/7/29 17:11
*/
public interface AbstractBaseExceptionEnum {
/**
* 获取异常的状态码
*/
Integer getCode();
/**
* 获取异常的提示信息
*/
String getMessage();
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/AbstractBaseExceptionEnum.java
|
Java
|
gpl-3.0
| 290
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.model.exception;
/**
* 验证码错误异常
*
* @author fengshuonan
*/
public class InvalidKaptchaException extends RuntimeException {
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/InvalidKaptchaException.java
|
Java
|
gpl-3.0
| 816
|
package com.zmops.iot.model.exception;
/**
* @author nantian created at 2021/7/29 20:35
*/
public class RequestEmptyException extends ServiceException {
public RequestEmptyException() {
super(400, "请求数据不完整或格式错误!");
}
public RequestEmptyException(String errorMessage) {
super(400, errorMessage);
}
/**
* 不拷贝栈信息,提高性能
*
* @author fengshuonan
*/
@Override
public synchronized Throwable fillInStackTrace() {
return null;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/RequestEmptyException.java
|
Java
|
gpl-3.0
| 550
|
package com.zmops.iot.model.exception;
/**
* @author nantian created at 2021/7/29 17:11
*/
public class ServiceException extends RuntimeException {
private Integer code;
private String errorMessage;
public ServiceException(Integer code, String errorMessage) {
super(errorMessage);
this.code = code;
this.errorMessage = errorMessage;
}
public ServiceException(AbstractBaseExceptionEnum exception) {
super(exception.getMessage());
this.code = exception.getCode();
this.errorMessage = exception.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/ServiceException.java
|
Java
|
gpl-3.0
| 898
|
package com.zmops.iot.model.exception;
/**
* @author nantian created at 2021/8/4 9:52
* <p>
* Zabbix 接口调用异常
*/
public class ZbxApiException extends ServiceException {
public ZbxApiException(Integer code, String errorMessage) {
super(code, errorMessage);
}
public ZbxApiException(AbstractBaseExceptionEnum exception) {
super(exception);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/ZbxApiException.java
|
Java
|
gpl-3.0
| 392
|
package com.zmops.iot.model.exception.enums;
import com.zmops.iot.model.exception.AbstractBaseExceptionEnum;
/**
* @author nantian created at 2021/7/29 17:12
*/
public enum CoreExceptionEnum implements AbstractBaseExceptionEnum {
/**
* 其他
*/
INVLIDE_DATE_STRING(400, "输入日期格式不对"),
/**
* 初始化数据库的异常
*/
NO_CURRENT_USER(700, "当前没有登录的用户"),
INIT_TABLE_EMPTY_PARAMS(701, "初始化数据库,存在为空的字段"),
/**
* 其他
*/
WRITE_ERROR(500, "渲染界面错误"),
ENCRYPT_ERROR(600, "加解密错误"),
/**
* 文件上传
*/
FILE_READING_ERROR(400, "FILE_READING_ERROR!"),
FILE_NOT_FOUND(400, "FILE_NOT_FOUND!"),
/**
* 数据库字段与实体字段不一致
*/
FIELD_VALIDATE_ERROR(700, "数据库字段与实体字段不一致!"),
/**
* 错误的请求
*/
PAGE_NULL(404, "请求页面不存在"),
IO_ERROR(500, "流读取异常"),
SERVICE_ERROR(500, "服务器异常"),
REMOTE_SERVICE_NULL(404, "远程服务不存在"),
ASYNC_ERROR(5000, "数据在被别人修改,请稍后重试"),
REPEATED_SUBMIT(500,"请勿重复请求");
CoreExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
private Integer code;
private String message;
@Override
public Integer getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/exception/enums/CoreExceptionEnum.java
|
Java
|
gpl-3.0
| 1,564
|
package com.zmops.iot.model.node;
import java.util.List;
public interface Tree {
/**
* 获取节点id
*/
String getNodeId();
/**
* 获取节点父id
*/
String getNodeParentId();
/**
* 获取子节点
*/
List<TreeNode> getChildrenNodes();
/**
* 设置children
*/
void setChildrenNodes(List childrenNodes);
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/node/Tree.java
|
Java
|
gpl-3.0
| 387
|
package com.zmops.iot.model.node;
import com.zmops.iot.util.ToolUtil;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author yefei
*/
@Data
public class TreeNode implements Tree {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
private Long id;
/**
* 父部门id
*/
private Long pId;
/**
* 所有父id
*/
private String pids;
/**
* 名称
*/
private String name;
private String tenantName;
/**
* URL
*/
private String url;
/**
* 是否菜单
*/
private String menuFlag;
/**
* 是否已授权
*/
private Boolean isChecked;
private LocalDateTime createTime;
private String createUserName;
/**
* 子节点
*/
private List<TreeNode> childrenNodes;
@Override
public String getNodeId() {
if (ToolUtil.isNotEmpty(id)) {
return String.valueOf(id);
} else {
return "0";
}
}
@Override
public String getNodeParentId() {
if (ToolUtil.isNotEmpty(pId)) {
return String.valueOf(pId);
} else {
return "0";
}
}
@Override
public List<TreeNode> getChildrenNodes() {
return childrenNodes;
}
@Override
public void setChildrenNodes(List childrenNodes) {
this.childrenNodes = childrenNodes;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/node/TreeNode.java
|
Java
|
gpl-3.0
| 1,464
|
package com.zmops.iot.model.page;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 分页结果的封装
*
* @author nantian
*/
@Data
public class Pager<T> {
private Integer code = 200;
/**
* 请求是否成功
*/
private Boolean success = true;
private String message = "请求成功";
private List<T> data = new ArrayList<>();
private long count = 0;
public Pager() {
}
public Pager(List<T> data, long count) {
this.data = data;
this.count = count;
}
public <V> Pager(List<V> data, long count, Function<V, T> mapFunc) {
this.data = data.stream().map(mapFunc).collect(Collectors.toList());
this.count = count;
}
public static Pager empty(long total) {
return new Pager<>(Collections.emptyList(), total);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/page/Pager.java
|
Java
|
gpl-3.0
| 961
|
package com.zmops.iot.model.response;
/**
* @author nantian created at 2021/7/29 20:29
*/
public class ErrorResponseData extends ResponseData {
/**
* 异常的具体类名称
*/
private String exceptionClazz;
public ErrorResponseData(String message) {
super(false, ResponseData.DEFAULT_ERROR_CODE, message, null);
}
public ErrorResponseData(Integer code, String message) {
super(false, code, message, null);
}
public ErrorResponseData(Integer code, String message, Object object) {
super(false, code, message, object);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/response/ErrorResponseData.java
|
Java
|
gpl-3.0
| 596
|
package com.zmops.iot.model.response;
import lombok.Data;
/**
* @author nantian created at 2021/7/29 20:28
*/
@Data
public class ResponseData {
public static final String DEFAULT_SUCCESS_MESSAGE = "请求成功";
public static final String DEFAULT_ERROR_MESSAGE = "网络异常";
public static final Integer DEFAULT_SUCCESS_CODE = 200;
public static final Integer DEFAULT_ERROR_CODE = 500;
/**
* 请求是否成功
*/
private Boolean success;
/**
* 响应状态码
*/
private Integer code;
/**
* 响应信息
*/
private String message;
/**
* 响应对象
*/
private Object data;
public ResponseData() {
}
public ResponseData(Boolean success, Integer code, String message, Object data) {
this.success = success;
this.code = code;
this.message = message;
this.data = data;
}
public static SuccessResponseData success() {
return new SuccessResponseData();
}
public static SuccessResponseData success(Object object) {
return new SuccessResponseData(object);
}
public static SuccessResponseData success(Integer code, String message, Object object) {
return new SuccessResponseData(code, message, object);
}
public static ErrorResponseData error(String message) {
return new ErrorResponseData(message);
}
public static ErrorResponseData error(Integer code, String message) {
return new ErrorResponseData(code, message);
}
public static ErrorResponseData error(Integer code, String message, Object object) {
return new ErrorResponseData(code, message, object);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/response/ResponseData.java
|
Java
|
gpl-3.0
| 1,711
|
package com.zmops.iot.model.response;
/**
* @author nantian created at 2021/7/29 20:29
*/
public class SuccessResponseData extends ResponseData {
public SuccessResponseData() {
super(true, DEFAULT_SUCCESS_CODE, DEFAULT_SUCCESS_MESSAGE, null);
}
public SuccessResponseData(Object object) {
super(true, DEFAULT_SUCCESS_CODE, DEFAULT_SUCCESS_MESSAGE, object);
}
public SuccessResponseData(Integer code, String message, Object object) {
super(true, code, message, object);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/model/response/SuccessResponseData.java
|
Java
|
gpl-3.0
| 527
|
package com.zmops.iot.util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* HashMap Builder
*
* @author yefei
* @param <K>
* @param <V>
*/
public abstract class ArgusMap<K, V> implements Serializable {
private static final long serialVersionUID = 1L;
public static <K, V> HashMapBuilder<K, V> builder() {
return new HashMapBuilder<K, V>();
}
public static <K, V> LinkedHashMapBuilder<K, V> linkedHashMapBuilder() {
return new LinkedHashMapBuilder<K, V>();
}
public static class HashMapBuilder<K, V> {
private Map<K, V> t;
public HashMapBuilder(){
this.t = new HashMap<>();
}
public HashMapBuilder<K, V> put(K key, V value) {
this.t.put(key, value);
return this;
}
public Map<K, V> build() {
return this.t;
}
}
public static class LinkedHashMapBuilder<K, V> {
private Map<K, V> t;
public LinkedHashMapBuilder(){
this.t = new LinkedHashMap<>();
}
public LinkedHashMapBuilder<K, V> put(K key, V value) {
this.t.put(key, value);
return this;
}
public Map<K, V> build() {
return this.t;
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/ArgusMap.java
|
Java
|
gpl-3.0
| 1,337
|
package com.zmops.iot.util;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 通用正则解析器
*
* @author yefei
*/
public class CommonRegexpResolver {
/**
* @param regexp 正则表达式
* @param input 待匹配的字符串
* @param groupNames 分组名
* @return
*/
public static Map<String, Collection<String>> resolve(String regexp, String input, List<String> groupNames) {
if (input == null) {
return new HashMap<>();
}
Multimap<String, String> res = ArrayListMultimap.create();
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(input);
if (Pattern.matches(regexp, input)) {
while (matcher.find()) {
groupNames.forEach(o -> {
if (matcher.group(o) != null) {
res.put(o, matcher.group(o));
}
for (int i = 0; i <= matcher.groupCount(); i++) {
res.put(String.valueOf(i), matcher.group(i));
}
});
}
} else {
int i = 0;
while (matcher.find()) {
res.put(String.valueOf(i++), matcher.group());
}
}
return res.asMap();
}
public static Map<Integer, Collection<String>> resolve(String regexp, String input) {
if (input == null) {
return new HashMap<Integer, Collection<String>>();
}
Multimap<Integer, String> res = ArrayListMultimap.create();
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(input);
if (Pattern.matches(regexp, input)) {
while (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
res.put(i, matcher.group(i));
}
}
} else {
int i = 0;
while (matcher.find()) {
res.put(i++, matcher.group());
}
}
return res.asMap();
}
// public static void main(String[] args) {
// final String regexp =
// "^(?<sign>[\\-+])?(?<number>(\\d)+)(?<suffix>[smhdw])?$";
// Map<String, Collection<String>> matches =
// CommonRegexpResolver.resolve(regexp, "-5m",
// Arrays.asList("sign","number","suffix"));
// matches.entrySet().forEach(o->{
// System.out.println(o.getKey()+"->"+o.getValue());
// });
// }
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/CommonRegexpResolver.java
|
Java
|
gpl-3.0
| 2,730
|
package com.zmops.iot.util;
import com.google.common.collect.Table;
import com.zmops.iot.domain.product.ProductServiceParam;
import com.zmops.iot.domain.sys.SysUser;
import com.zmops.iot.model.cache.*;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Map;
/**
* 枚举类工具类
*
* @author yefei
*/
public class DefinitionsUtil {
@Getter
private static DictionaryCache dictionaryCache = new DictionaryCache();
@Getter
@Setter
private static SysUserCache sysUserCache = new SysUserCache();
@Getter
@Setter
private static SysRoleCache sysRoleCache = new SysRoleCache();
@Getter
@Setter
private static ProductTypeCache productTypeCache = new ProductTypeCache();
@Getter
@Setter
private static TenantNameCache tenantNameCache = new TenantNameCache();
@Getter
@Setter
private static ProductServiceCache productServiceCache = new ProductServiceCache();
@Getter
@Setter
private static ProductServiceParamCache productServiceParamCache = new ProductServiceParamCache();
@Getter
@Setter
private static DeviceCache deviceCache = new DeviceCache();
@Getter
@Setter
private static ProductEventCache productEventCache = new ProductEventCache();
@Getter
@Setter
private static ProtocolServiceCache protocolServiceCache = new ProtocolServiceCache();
public static void updateDictionaries(Table<String, String, String> dictionarys) {
dictionaryCache.updateDictionaries(dictionarys);
}
public static void updateSysUser(List<SysUser> memberList) {
sysUserCache.updateSysUser(memberList);
}
public static String getNameByVal(String flag, String value) {
return dictionaryCache.getNameByVal(flag, value);
}
public static String getSysUserName(Long sysUserId) {
return sysUserCache.getSysUserName(sysUserId);
}
public static SysUser getSysUser(Long sysUserId) {
return sysUserCache.getSysUser(sysUserId);
}
public static void updateProductType(Map<Long, String> map) {
productTypeCache.updateProductType(map);
}
public static String getTypeName(long value) {
return productTypeCache.getTypeName(value);
}
public static void updateTenantName(Map<Long, String> map) {
tenantNameCache.updateTenantName(map);
}
public static String getTenantName(long value) {
return tenantNameCache.getTenantName(value);
}
public static void updateServiceCache(Map<Long, String> map) {
productServiceCache.updateProductService(map);
}
public static String getServiceName(long value) {
return productServiceCache.getServiceName(value);
}
public static void updateServiceParamCache(Map<Long, List<ProductServiceParam>> paramMap) {
productServiceParamCache.updateProductServiceParam(paramMap);
}
public static List<ProductServiceParam> getServiceParam(long value) {
return productServiceParamCache.getServiceParam(value);
}
public static void updateDeviceCache(Map<String, String> map) {
deviceCache.updateDeviceName(map);
}
public static String getDeviceName(String value) {
return deviceCache.getDeviceName(value);
}
public static void updateProductEventCache(Map<Long, String> map) {
productEventCache.updateTriggerName(map);
}
public static String getTriggerName(Long value) {
return productEventCache.getTriggerName(value);
}
public static void updateProtocolServiceCache(Map<Long, String> map) {
protocolServiceCache.updateName(map);
}
public static String getProtocolServiceName(Long value) {
return protocolServiceCache.getName(value);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/DefinitionsUtil.java
|
Java
|
gpl-3.0
| 3,800
|
package com.zmops.iot.util;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Calendar;
import java.util.Date;
public class LocalDateTimeUtils {
// 一天的毫秒
public static final long MILLISECONDS_PER_DAY = 24L * 3600 * 1000;
// 获取当前时间的LocalDateTime对象
// LocalDateTime.now();
// 根据年月日构建LocalDateTime
// LocalDateTime.of();
// 比较日期先后
// LocalDateTime.now().isBefore(),
// LocalDateTime.now().isAfter(),
// Date转换为LocalDateTime
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
// LocalDateTime转换为Date
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
// 获取指定日期的毫秒
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
// 获取指定日期的秒
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
// 获取指定日期的秒
public static Long getSecondsByStr(String date) {
return getSecondsByTime(dateToStamp(date));
}
/**
* 根据秒获取时间
*
* @param seconds
* @return
*/
public static LocalDateTime getLDTBySeconds(Integer seconds) {
return LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.ofHours(8));
}
public static LocalDateTime getLDTByMilliSeconds(Long mills) {
LocalDateTime time = getLDTBySeconds((int) (mills / 1000));
return time.withNano((int) (mills % 1000));
}
// 获取指定时间的指定格式
public static String formatTime(LocalDateTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
public static String formatTime(LocalDateTime time) {
return formatTime(time, "yyyy-MM-dd HH:mm:ss");
}
public static String formatTimeDate(LocalDateTime time) {
return formatTime(time, "yyyy-MM-dd");
}
// 获取当前时间的指定格式
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
// 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
// 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return period.getYears() * 12 + period.getMonths();
}
return field.between(startTime, endTime);
}
// 获取一天的开始时间,2017,7,22 00:00
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0).withMinute(0).withSecond(1).withNano(0);
}
// 获取一天的结束时间,2017,7,22 23:59:59.999999999
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
}
/*
* 时间戳转 LocalDateTime
*/
public static LocalDateTime convertDateToLocalDateTime(Integer time) {
if (time == null) {
return null;
}
return LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.ofHours(8));
}
/*
* 时间戳转 String
*/
public static String convertTimeToString(Long time, String pattern) {
if (time == null) {
return null;
}
return LocalDateTimeUtils.formatTime(LocalDateTimeUtils.getLDTByMilliSeconds(time), pattern);
}
/*
* 秒转 String
*/
public static String convertTimeToString(Integer time, String pattern) {
if (time == null) {
return null;
}
return LocalDateTimeUtils.formatTime(LocalDateTimeUtils.getLDTBySeconds(time), pattern);
}
public static LocalDateTime dateToStamp(String str) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = simpleDateFormat.parse(str.replace("T", " "));
return convertDateToLDT(date);
} catch (Exception e) {
e.printStackTrace();
}
return LocalDateTime.now();
}
public static String dateToStr(String str) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = simpleDateFormat.parse(str.replace("T", " "));
return formatTime(convertDateToLDT(date));
} catch (Exception e) {
return str;
}
}
public static LocalDateTime getThisWeekMonday() {
Calendar cal = Calendar.getInstance();
// cal.setTime(date);
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static void main(String[] args) {
System.out.println(formatTime(getDayStart(LocalDateTime.now())));
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/LocalDateTimeUtils.java
|
Java
|
gpl-3.0
| 6,630
|
package com.zmops.iot.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zmops.iot.constant.Constants;
import org.springframework.util.StringUtils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ObjectUtils {
public static List<Map<String, Object>> digitUnits = new ArrayList<>();
/**
* 获取指定实体对象中字段的值
*
* @param o 实体对象
* @param c 实体类
* @param fieldName 字段名称
* @return
*/
public static Object getFieldValue(Object o, Class<?> c, String fieldName) {
// 获取类中的全部定义字段
Field[] fields = c.getDeclaredFields();
// 循环遍历字段,获取字段相应的属性值
for (Field field : fields) {
// 设置字段可见,就可以用get方法获取属性值。
field.setAccessible(true);
try {
if (fieldName.equals(field.getName())) {
return field.get(o);
}
} catch (Exception e) {
return null;
}
}
return null;
}
public static Object getFieldValue(Object o, String fieldName) {
return getFieldValue(o, o.getClass(), fieldName);
}
public static void setFieldValue(Object o, Class<?> c, String fieldName, Object value) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.getName().equals(fieldName)) {
try {
PropertyDescriptor pd = new PropertyDescriptor(fieldName, c);
Method wM = pd.getWriteMethod();
wM.invoke(o, value);
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
public static void setFieldValue(Object o, String fieldName, Object value) {
setFieldValue(o, o.getClass(), fieldName, value);
}
/**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Field[] fields = obj.getClass().getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 检查IP地址是否合法
*
* @param ipAddress
* @return
*/
public static boolean isIpv4(String ipAddress) {
String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
Pattern pattern = Pattern.compile(ip);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}
/**
* 检查秘钥是否合法
*
* @param psk
* @return
*/
public static boolean validatePSK(String psk) {
String pskpatern = "^([0-9a-f]{2})+$";
Pattern pattern = Pattern.compile(pskpatern);
Matcher matcher = pattern.matcher(psk);
return matcher.matches();
}
/**
* 检查字符串是不是数字
*
* @param str
* @return
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/**
* 根据数字生成字母
*
* @param
* @return
*/
public static String num2letter(int number) {
int start = 65;
int base = 26;
String str = "";
int level = 0;
do {
if (level++ > 0) {
number--;
}
int remainder = number % base;
number = (number - remainder) / base;
str = (char) (start + remainder) + str;
} while (0 != number);
return str;
}
/**
* 返回两个list的去重并集
*
* @param output
* @param extend
* @return
*/
public static <R> List<R> outputExtend(List<R> output, List<R> extend) {
if (output.size() == 1 && output.get(0).equals("extend")) {
return output;
}
Set<R> result = new HashSet<>();
for (R o : output) {
result.add(o);
}
for (R e : extend) {
result.add(e);
}
return new ArrayList<>(result);
}
/**
* 返回两个list的交集
*
* @param array1
* @param array2
* @return
*/
public static List<?> arrayIntersectKey(List<?> array1, List<?> array2) {
array1.retainAll(array2);
return array1;
}
/**
* Convert timestamp to string representation. Return 'Never' if 0.
*
* @return
*/
public static String date2str(String format, String seconds) {
if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
return "";
}
if (format == null || format.isEmpty()) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(Long.valueOf(seconds + "000")));
}
public static String convertUnits(String value, String units) {
int convert = Constants.ITEM_CONVERT_WITH_UNITS;
@SuppressWarnings("unused")
boolean byteStep = false, pow = false, ignoreMillisec = false, length = false;
if ("unixtime".equals(units)) {
return date2str(Constants.DATE_TIME_FORMAT_SECONDS, value);
}
// special processing of uptime
if ("uptime".equals(units)) {
return convertUnitsUptime(value);
}
if ("s".equals(units)) {
return convertUnitsS(value, false);
}
// black list of units that should have no multiplier prefix (K, M, G
// etc) applied
List<String> blackList = Lists.newArrayList("%", "ms", "rpm", "RPM");
// add to the blacklist if unit is prefixed with '!'
if (units != null && units.startsWith("!")) {
units = units.substring(1);
blackList.add(units);
}
if (blackList.contains(units) || !StringUtils.hasText(units)) {
if (!CommonRegexpResolver.resolve("\\.\\d+$", "0.01").isEmpty()) {
BigDecimal decimal = new BigDecimal(value);
value = decimal
.setScale(decimal.abs().compareTo(new BigDecimal(0.01)) == 1 ? 2 : 6, RoundingMode.HALF_UP)
.toString();
}
value = value.replaceAll("^([\\-0-9]+)(\\.)([0-9]*?)[0]+$", "$1$2$3");
if (value.endsWith(".")) {
value = value.substring(0, value.length() - 1);
}
return value + " " + units;
}
int step;
// if one or more items is B or Bps, then Y-scale use base 8 and
// calculated in bytes
if (byteStep) {
step = 1024;
} else {
switch (units) {
case "Bps":
case "B":
step = 1024;
convert = convert != 0 ? convert : 1;
break;
case "b":
case "bps":
convert = convert != 0 ? convert : 1;
default:
step = 1000;
break;
}
}
BigDecimal abs = new BigDecimal(value).abs();
if (abs.compareTo(new BigDecimal(1)) == -1) {
value = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).toString();
if (length && abs.compareTo(new BigDecimal(0)) != 0) {
}
return (value + " " + units).trim();
}
List<String> steps = Arrays.asList("", "K", "M", "G", "T", "P", "E", "Z", "Y");
BigDecimal values = new BigDecimal(value);
int i = 0;
while (values.divide(new BigDecimal(step)).longValue() > 1 && i < steps.size()) {
values = values.divide(new BigDecimal(step));
i++;
}
if (values.intValue() == step) {
values = values.divide(new BigDecimal(step));
i++;
}
value = values.setScale(10, RoundingMode.HALF_UP).toString().replaceAll("^([\\-0-9]+)(\\.)([0-9]*?)[0]+$",
"$1$2$3");
if (value.endsWith(".")) {
value = value.substring(0, value.length() - 1);
}
if (value.contains(".")) {
int idx = value.lastIndexOf('.') + 3;
if (idx < value.length()) {
value = value.substring(0, idx);
}
}
return value + " " + steps.get(i) + units;
}
// @SuppressWarnings("unused")
// String step = "";
// int convert = Constants.ITEM_CONVERT_WITH_UNITS;
// // special processing for unix timestamps
// if ("unixtime".equals(units)) {
// return date2str(Constants.DATE_TIME_FORMAT_SECONDS, value);
// }
// // special processing of uptime
// if ("uptime".equals(units)) {
// return convertUnitsUptime(value);
// }
//
// if ("s".equals(units)) {
// return convertUnitsS(value, false);
// }
// // black list of units that should have no multiplier prefix (K, M, G
// // etc) applied
// List<String> blackList = Arrays.asList("% ", "ms ", "rpm ", "RPM ");
// // add to the blacklist if unit is prefixed with '!'
// if (!StringUtils.isBlank(units) && units.startsWith("!")) {
// blackList.add(units.substring(0, 1));
// }
// // any other unit
// if (blackList.contains(units) || StringUtils.isBlank(units)) {
// if (CommonRegexpResolver.resolve("\\.\\d*$", value).size() > 0) {
// String format = Math.abs(Double.parseDouble(
// value)) >= Constants.ARGUS_UNITS_ROUNDOFF_THRESHOLD ? "%."
// + Constants.ARGUS_UNITS_ROUNDOFF_UPPER_LIMIT
// + "f" : "%."
// + Constants.ARGUS_UNITS_ROUNDOFF_LOWER_LIMIT
// + "f";
// value = formt(format, value);
// }
// value = value.replaceAll("^([\\-0-9]+)(\\.)([0-9]*)[0]+$", "$1$2$3");
// value = value.split("\\.")[0];
// return value.trim();
// }
// switch (units) {
// case "Bps":
// case "B":
// step = Constants.ARGUS_KIBIBYTE;
// break;
// case "b":
// case "bps":
// default:
// step = "1000";
// }
// double abs = 0.0;
// if (Double.parseDouble(value) < 0) {
// abs = Math.abs(Double.parseDouble(value));
// } else {
// abs = Double.parseDouble(value);
// }
// if (abs < 1) {
// value = String.valueOf(round(value,
// Constants.ARGUS_UNITS_ROUNDOFF_MIDDLE_LIMIT));
// return value + " " + units;
// }
//
// if (isEmpty(digitUnits)) {
// initDigitUnits();
// for (Map<String, Object> map : digitUnits) {
// map.put("value", String.valueOf((long) Math.pow(1024, (int)
// map.get("pow"))));
// }
// }
// Map<String, Object> valUnit = new HashMap<>();
// valUnit.put("pow", 0);
// valUnit.put("short", "");
// valUnit.put("value", value);
// if (Double.parseDouble(value) == 0) {
// for (Map<String, Object> map : digitUnits) {
// if (abs >= Double.parseDouble(value)) {
// valUnit = map;
// } else {
// break;
// }
// }
// }
// if (round(value, Constants.ARGUS_UNITS_ROUNDOFF_MIDDLE_LIMIT).intValue()
// > 0) {
// double newVal = new BigDecimal(formt("%.10f", value))
// .divide(new BigDecimal(formt("%.10f",
// String.valueOf(valUnit.get("value")))),
// Constants.ARGUS_PRECISION_10,
// BigDecimal.ROUND_HALF_UP)
// .doubleValue();
// valUnit.put("value", newVal);
// } else {
// valUnit.put("value", 0);
// }
// String desc = "";
// switch (convert) {
// case 0:
// units = units.trim();
// case 1:
// desc = String.valueOf(valUnit.get("short"));
// break;
// }
// value = String.valueOf(round(String.valueOf(valUnit.get("value")),
// Constants.ARGUS_UNITS_ROUNDOFF_UPPER_LIMIT))
// .replaceAll("^([\\-0-9]+)(\\.)([0-9]*)[0]+$", "$1$2$3");
//
// value = value.split("\\.")[0];
//
// if (Double.parseDouble(value) == 0) {
// value = "0";
// }
// return value + " " + desc + units;
// }
@SuppressWarnings("unused")
private static void initDigitUnits() {
Map<String, Object> obj = new HashMap<>();
obj.put("pow", 0);
obj.put("short", "");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 1);
obj.put("short", "K");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 2);
obj.put("short", "M");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 3);
obj.put("short", "G");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 4);
obj.put("short", "T");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 5);
obj.put("short", "P");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 6);
obj.put("short", "E");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 7);
obj.put("short", "Z");
digitUnits.add(obj);
obj = new HashMap<>();
obj.put("pow", 8);
obj.put("short", "Y");
digitUnits.add(obj);
}
/**
* 将时间段转换为可读格式。 使用以下单位:年、月、日、小时、分钟、秒和毫秒。 仅显示三个最高单位:y m d,m d h,d h mm等等。
* 如果某个值等于零,则忽略该值。例如,如果周期为1y0m4d,它将显示为 1Y 4D,非1Y 0M 4D或1Y 4D H。
*
* @param value
* @param ignore_millisec
* @return
*/
private static String convertUnitsS(String value, boolean ignore_millisec) {
BigDecimal secs = round(new BigDecimal(value).multiply(BigDecimal.valueOf(1000)),
Constants.ARGUS_UNITS_ROUNDOFF_UPPER_LIMIT).divide(BigDecimal.valueOf(1000));
long sec = secs.longValue();
String str = "";
if (sec < 0) {
sec = -sec;
str = "-";
}
int[] steps = new int[]{
Constants.SEC_PER_YEAR, Constants.SEC_PER_MONTH,
Constants.SEC_PER_DAY, Constants.SEC_PER_HOUR,
Constants.SEC_PER_MIN
};
List<String> unitsEn = new ArrayList<>(units.keySet());
Map<String, Long> values = new LinkedHashMap<>();
for (int s = 0; s < steps.length; s++) {
int v = steps[s];
if (sec < v) {
continue;
}
long n = sec / v;
sec %= v;
values.put(unitsEn.get(s), n);
}
if (sec != 0) {
values.put("s", sec);
}
if (!ignore_millisec) {
values.put("ms", secs.subtract(BigDecimal.valueOf(secs.longValue())).multiply(BigDecimal.valueOf(1000)).longValue());
}
int size = 0;
for (Entry<String, Long> ent : values.entrySet()) {
str += " " + ent.getValue() + units.get(ent.getKey());
if (++size == 3) {
break;
}
}
return !StringUtils.hasText(str) ? "0" : str.trim();
}
public static void main(String[] args) {
System.out.println(convertUnitsS("86411.1", false));
}
private final static Map<String, String> units = ArgusMap.<String, String>linkedHashMapBuilder().put("y", "年").put("m", "月")
.put("d", "天").put("h", "小时").put("mm", "分").put("s", "秒").put("ms", "毫秒").build();
private static String convertUnitsUptime(String value) {
int secs = round(value, 0).intValue();
if (secs < 0) {
value = "-";
secs = -secs;
} else {
value = "";
}
int days = new BigDecimal(secs).divide(new BigDecimal(Constants.SEC_PER_DAY), RoundingMode.DOWN).intValue();
secs -= days * Constants.SEC_PER_DAY;
int hours = new BigDecimal(secs).divide(new BigDecimal(Constants.SEC_PER_HOUR), RoundingMode.DOWN).intValue();
secs -= hours * Constants.SEC_PER_HOUR;
int mins = new BigDecimal(secs).divide(new BigDecimal(Constants.SEC_PER_MIN), RoundingMode.DOWN).intValue();
secs -= mins * Constants.SEC_PER_MIN;
if (days != 0) {
value += days + "天,";
}
value += LocalDateTimeUtils.formatTime(LocalDateTime.now().withHour(hours).withMinute(mins).withSecond(secs),
"HH:mm:ss");
return value;
}
/**
* 计算差值 并保留digits位小数
*
* @param last
* @param prev
* @param digits
* @return
*/
public static double bcsub(String last, String prev, int digits) {
double lastVal = Double.parseDouble(last);
double prevVal = Double.parseDouble(prev);
double res = lastVal - prevVal;
if (digits == 0) {
return res;
} else {
BigDecimal bg = new BigDecimal(res);
double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return f1;
}
}
/**
* 格式化value 保留r位小数并四舍五入
*
* @param value
* @param r
* @return
*/
public static BigDecimal round(String value, int r) {
if (!StringUtils.hasText(value)) {
return new BigDecimal("0");
}
BigDecimal bvalue = new BigDecimal(value);
return round(bvalue, r);
}
public static BigDecimal round(BigDecimal value, int r) {
return value.divide(new BigDecimal("1"), r, BigDecimal.ROUND_HALF_UP);
}
/**
* 根据format 格式化value 小数点位数
*
* @param format
* @param value
* @return
*/
public static String formt(String format, String value) {
Formatter fmt = new Formatter();
value = fmt.format(format, Double.parseDouble(value)).toString();
fmt.close();
return value;
}
public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List<T> dest = (List<T>) in.readObject();
return dest;
}
public static <K, V> Map<K, V> deepCopy(Map<K, V> src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
Map<K, V> dest = (Map<K, V>) in.readObject();
return dest;
}
/**
* 根据map键值的交集 返回map1中的值
*
* @param map
* @param map2
* @return
*/
public static <Key, V, VV> Map<Key, V> mapIntersectKey(Map<Key, V> map, Map<Key, VV> map2) {
Set<Key> bigMapKey = map.keySet();
Set<Key> smallMapKey = map2.keySet();
Set<Key> differenceSet = Sets.intersection(bigMapKey, smallMapKey);
Map<Key, V> result = Maps.newHashMap();
for (Key key : differenceSet) {
result.put(key, map.get(key));
}
return result;
}
/**
* 根据map键值的差集 返回map1中的值
*
* @param map
* @param map2
* @return
*/
public static <Key, V, VV> Map<Key, V> mapDiffKey(Map<Key, V> map, Map<Key, VV> map2) {
Set<Key> bigMapKey = map.keySet();
Set<Key> smallMapKey = map2.keySet();
Set<Key> differenceSet = Sets.difference(bigMapKey, smallMapKey);
Map<Key, V> result = Maps.newHashMap();
for (Key key : differenceSet) {
result.put(key, map.get(key));
}
return result;
}
public static String substr_replace(String source, String replacement, int start, Integer length) {
if (length == null) {
return new StringBuilder(source.substring(0, start)).append(replacement).toString();
}
// 如果start <0 表示从source结尾处n个开始替换
if (start < 0) {
start = source.length() + start;
}
if (length >= 0) {
return new StringBuilder(source.substring(0, start)).append(replacement)
.append(source.substring(start + length)).toString();
}
return new StringBuilder(source.substring(0, start)).append(replacement)
.append(source.substring(source.length() + length)).toString();
}
public static String substr_replace(String source, String replacement, int start) {
return substr_replace(source, replacement, start, null);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/ObjectUtils.java
|
Java
|
gpl-3.0
| 22,408
|
package com.zmops.iot.util;
import java.math.BigDecimal;
import java.text.CharacterIterator;
import java.text.DecimalFormat;
import java.text.StringCharacterIterator;
/**
* @author yefei
**/
public class ParseUtil {
public static void main(String[] args) {
System.out.println(getCommaFormat("2097180.19677"));
}
//每3位中间添加逗号的格式化显示
public static String getCommaFormat(String value) {
if (ToolUtil.isEmpty(value)) {
return "0";
}
return getFormat(",###.##", new BigDecimal(value));
}
//自定义数字格式方法
public static String getFormat(String style, BigDecimal value) {
DecimalFormat df = new DecimalFormat();
df.applyPattern(style);
return df.format(value.doubleValue());
}
public static String getFormatFloat(String value) {
if (!isFloat(value)) {
return value;
}
return String.format("%1.2f", Float.parseFloat(value));
}
public static boolean isFloat(String value) {
try {
Float.parseFloat(value);
if (!value.contains(".")) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
public static String formatLagSize(String size) {
if (ToolUtil.isEmpty(size)) {
return "0";
}
long bytes = Long.parseLong(size);
if (-1000 < bytes && bytes < 1000) {
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/ParseUtil.java
|
Java
|
gpl-3.0
| 1,817
|
package com.zmops.iot.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author nantian created at 2021/7/29 17:08
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}
public static <T> List<T> getBeanOfType(Class<T> requiredType) {
assertApplicationContext();
Map<String, T> map = applicationContext.getBeansOfType(requiredType);
return map == null ? null : new ArrayList<>(map.values());
}
public static void autowireBean(Object bean) {
applicationContext.getAutowireCapableBeanFactory().autowireBean(bean);
}
private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/SpringContextHolder.java
|
Java
|
gpl-3.0
| 1,800
|
package com.zmops.iot.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
/**
* @Author nantian
* @Date 2/20/2020 0020 11:09 AM
* @Email nantian@zmops.com
* @Version 1.0
*/
@Component
public class SpringUtils implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*/
public static Object getBean(String name) {
return beanFactory.getBean(name);
}
/**
* 获取对象
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name, Class<T> clz) {
T result = (T) beanFactory.getBean(name);
return result;
}
/**
* 获取对象
*/
public static <T> T getBean(Class<T> clz) {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 判断是否包含对象
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 创建对象到spring context
*/
@SuppressWarnings("unchecked")
public static <T> T createBean(Class<T> clz) {
T result = (T) beanFactory.createBean(clz, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
return result;
}
/**
* 删除对象
*/
public static void destroyBean(String beanName) {
beanFactory.destroyScopedBean(beanName);
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/SpringUtils.java
|
Java
|
gpl-3.0
| 1,863
|
package com.zmops.iot.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.exception.enums.CoreExceptionEnum;
import org.apache.logging.log4j.core.util.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* @author nantian created at 2021/7/29 17:03
*/
public class ToolUtil {
/**
* 如果对象不是数字类型 就加上双引号返回
*/
public static String addQuotes(String value) {
if (isNum(value)) {
return value;
}
return "\\\\\"" + value + "\\\\\"";
}
/**
* 默认密码盐长度
*/
public static final int SALT_LENGTH = 6;
/**
* 获取随机字符,自定义长度
*
* @author fengshuonan
*/
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* md5加密(加盐)
*
* @author fengshuonan
*/
public static String md5Hex(String password, String salt) {
return md5Hex(password + salt);
}
/**
* md5加密(不加盐)
*
* @author fengshuonan
*/
public static String md5Hex(String str) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(str.getBytes());
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < bs.length; i++) {
if (Integer.toHexString(0xFF & bs[i]).length() == 1)
md5StrBuff.append("0").append(Integer.toHexString(0xFF & bs[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & bs[i]));
}
return md5StrBuff.toString();
} catch (Exception e) {
throw new ServiceException(CoreExceptionEnum.ENCRYPT_ERROR);
}
}
/**
* 过滤掉掉字符串中的空白
*
* @author fengshuonan
*/
public static String removeWhiteSpace(String value) {
if (isEmpty(value)) {
return "";
} else {
return value.replaceAll("\\s*", "");
}
}
/**
* 获取某个时间间隔以前的时间 时间格式:yyyy-MM-dd HH:mm:ss
*
* @author stylefeng
*/
public static String getCreateTimeBefore(int seconds) {
long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
Date date = new Date(currentTimeInMillis - seconds * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* 获取异常的具体信息
*
* @author fengshuonan
*/
public static String getExceptionMsg(Throwable e) {
StringWriter sw = new StringWriter();
try {
e.printStackTrace(new PrintWriter(sw));
} finally {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.getBuffer().toString().replaceAll("\\$", "T");
}
/**
* 获取应用名称
*
* @author fengshuonan
*/
public static String getApplicationName() {
try {
Environment environment = SpringContextHolder.getApplicationContext().getEnvironment();
String property = environment.getProperty("spring.application.name");
if (ToolUtil.isNotEmpty(property)) {
return property;
} else {
return "";
}
} catch (Exception e) {
Logger logger = LoggerFactory.getLogger(ToolUtil.class);
logger.error("获取应用名称错误!", e);
return "";
}
}
/**
* 获取ip地址
*
* @author fengshuonan
*/
public static String getIP() {
try {
StringBuilder IFCONFIG = new StringBuilder();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");
}
}
}
return IFCONFIG.toString();
} catch (SocketException ex) {
ex.printStackTrace();
}
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
/**
* 拷贝属性,为null的不拷贝
*
* @author fengshuonan
*/
public static void copyProperties(Object source, Object target) {
BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreNullValue(true).ignoreError());
}
/**
* 判断是否是windows操作系统
*
* @author stylefeng
*/
public static Boolean isWinOs() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
return true;
} else {
return false;
}
}
/**
* 获取临时目录
*
* @author stylefeng
*/
public static String getTempPath() {
return System.getProperty("java.io.tmpdir");
}
/**
* 把一个数转化为int
*
* @author fengshuonan
*/
public static Integer toInt(Object val) {
if (val instanceof Double) {
BigDecimal bigDecimal = new BigDecimal((Double) val);
return bigDecimal.intValue();
} else {
return Integer.valueOf(val.toString());
}
}
/**
* 是否为数字
*
* @author fengshuonan
*/
public static boolean isNum(Object obj) {
try {
Long.parseLong(obj.toString());
} catch (Exception e) {
try {
Double.parseDouble(obj.toString());
}catch (Exception el){
return false;
}
return true;
}
return true;
}
/**
* 获取项目路径
*
* @author fengshuonan
*/
public static String getWebRootPath(String filePath) {
try {
String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath();
path = path.replace("/WEB-INF/classes/", "");
path = path.replace("/target/classes/", "");
path = path.replace("file:/", "");
if (ToolUtil.isEmpty(filePath)) {
return path;
} else {
return path + "/" + filePath;
}
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
/**
* 获取文件后缀名 不包含点
*
* @author fengshuonan
*/
public static String getFileSuffix(String fileWholeName) {
if (ToolUtil.isEmpty(fileWholeName)) {
return "none";
}
int lastIndexOf = fileWholeName.lastIndexOf(".");
return fileWholeName.substring(lastIndexOf + 1);
}
/**
* 判断一个对象是否是时间类型
*
* @author stylefeng
*/
public static String dateType(Object o) {
if (o instanceof Date) {
return DateUtil.formatDate((Date) o);
} else {
return o.toString();
}
}
/**
* 当前时间
*
* @author stylefeng
*/
public static String currentTime() {
return DateUtil.formatDateTime(new Date());
}
/**
* object转化为map
*
* @author fengshuonan
*/
public static Map<String, Object> toMap(Object object) {
if (object instanceof Map) {
return (Map<String, Object>) object;
} else {
return BeanUtil.beanToMap(object);
}
}
/**
* 替换字符串的值
* <p>
* 例如:字符串为 #{name}导出文件
* 本方法可根据参数中map里的name值替换掉以上表达式的#{name}
*
* @author fengshuonan
*/
public static String stringReplaceBuild(String value, Map<String, Object> params) {
String result = value;
for (String key : params.keySet()) {
if (params.get(key) != null) {
result = result.replace("#{" + key + "}", params.get(key).toString());
}
}
return result;
}
/**
* 对象是否不为空(新增)
*
* @author fengshuonan
*/
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
/**
* 对象是否为空
*
* @author fengshuonan
*/
public static boolean isEmpty(Object o) {
if (o == null) {
return true;
}
if (o instanceof String) {
if (o.toString().trim().equals("")) {
return true;
}
} else if (o instanceof List) {
if (((List) o).size() == 0) {
return true;
}
} else if (o instanceof Map) {
if (((Map) o).size() == 0) {
return true;
}
} else if (o instanceof Set) {
if (((Set) o).size() == 0) {
return true;
}
} else if (o instanceof Object[]) {
if (((Object[]) o).length == 0) {
return true;
}
} else if (o instanceof int[]) {
if (((int[]) o).length == 0) {
return true;
}
} else if (o instanceof long[]) {
if (((long[]) o).length == 0) {
return true;
}
}
return false;
}
/**
* 对象组中是否存在空对象
*
* @author fengshuonan
*/
public static boolean isOneEmpty(Object... os) {
for (Object o : os) {
if (isEmpty(o)) {
return true;
}
}
return false;
}
/**
* 对象组中是否全是空对象
*
* @author fengshuonan
*/
public static boolean isAllEmpty(Object... os) {
for (Object o : os) {
if (!isEmpty(o)) {
return false;
}
}
return true;
}
/**
* 将一个对象转换为另一个对象
*
* @param <T1> 要转换的对象
* @param <T2> 转换后的类
* @param oriList 要转换的对象
* @param castClass 转换后的对象
* @return 转换后的对象
*/
public static <T1, T2> List<T2> convertBean(List<T1> oriList, Class<T2> castClass) {
if (isEmpty(oriList)) {
return Collections.emptyList();
}
List<T2> resList = new ArrayList<>();
oriList.forEach(orimodel -> {
try {
T2 returnModel = castClass.newInstance();
BeanUtils.copyProperties(orimodel, returnModel);
resList.add(returnModel);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
return resList;
}
public static boolean validCron(String cron){
//String regEx = "(((^([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]))|^([0-9]|[0-5][0-9])|^(\\* ))((([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|([0-9]|[0-5][0-9]) |(\\* ))((([0-9]|[01][0-9]|2[0-3])(\\,|\\-|\\/){1}([0-9]|[01][0-9]|2[0-3]) )|([0-9]|[01][0-9]|2[0-3]) |(\\* ))((([0-9]|[0-2][0-9]|3[01])(\\,|\\-|\\/){1}([0-9]|[0-2][0-9]|3[01]) )|(([0-9]|[0-2][0-9]|3[01]) )|(\\? )|(\\* )|(([1-9]|[0-2][0-9]|3[01])L )|([1-7]W )|(LW )|([1-7]\\#[1-4] ))((([1-9]|0[1-9]|1[0-2])(\\,|\\-|\\/){1}([1-9]|0[1-9]|1[0-2]) )|([1-9]|0[1-9]|1[0-2]) |(\\* ))(([1-7](\\,|\\-|\\/){1}[1-7])|([1-7])|(\\?)|(\\*)|(([1-7]L)|([1-7]\\#[1-4]))))|(((^([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|^([0-9]|[0-5][0-9]) |^(\\* ))((([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|([0-9]|[0-5][0-9]) |(\\* ))((([0-9]|[01][0-9]|2[0-3])(\\,|\\-|\\/){1}([0-9]|[01][0-9]|2[0-3]) )|([0-9]|[01][0-9]|2[0-3]) |(\\* ))((([0-9]|[0-2][0-9]|3[01])(\\,|\\-|\\/){1}([0-9]|[0-2][0-9]|3[01]) )|(([0-9]|[0-2][0-9]|3[01]) )|(\\? )|(\\* )|(([1-9]|[0-2][0-9]|3[01])L )|([1-7]W )|(LW )|([1-7]\\#[1-4] ))((([1-9]|0[1-9]|1[0-2])(\\,|\\-|\\/){1}([1-9]|0[1-9]|1[0-2]) )|([1-9]|0[1-9]|1[0-2]) |(\\* ))(([1-7](\\,|\\-|\\/){1}[1-7] )|([1-7] )|(\\? )|(\\* )|(([1-7]L )|([1-7]\\#[1-4]) ))((19[789][0-9]|20[0-9][0-9])\\-(19[789][0-9]|20[0-9][0-9])))";
//String tests = "0 0 0 L * ?";
return CronExpression.isValidExpression(cron);
}
public static boolean validDeviceName(String content){
return content.contains("\\") || content.contains("/");
}
/**
* List<Map<String,Object>> 根据相同key的值去重
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
|
2301_81045437/zeus-iot
|
zeus-common/src/main/java/com/zmops/iot/util/ToolUtil.java
|
Java
|
gpl-3.0
| 14,431
|
package com.zmops.iot.core.auth.context;
import com.zmops.iot.core.auth.model.LoginUser;
/**
* 当前登录用户信息获取的接口
*
* @author fengshuonan
*/
public interface LoginContext {
/**
* 获取当前登录用户
*
* @author fengshuonan
*/
LoginUser getUser();
/**
* 获取当前登录用户的token
*
* @author fengshuonan
*/
String getToken();
/**
* 获取 Zabbix 登陆 Token
*
* @return
*/
String getZbxToken();
/**
* 是否登录
*
* @author fengshuonan
*/
boolean hasLogin();
/**
* 获取当前登录用户id
*
* @author fengshuonan
*/
Long getUserId();
/**
* 验证当前用户是否包含该角色
*
* @param roleName 角色名称
* @return 包含:true, 否则false
*/
boolean hasRole(String roleName);
/**
* 验证当前用户是否属于以下任意一个角色
*
* @param roleNames 角色列表,逗号分隔
* @return 包含:true, 否则false
*/
boolean hasAnyRoles(String roleNames);
/**
* 验证当前用户是否拥有指定权限
*
* @param permission 权限名
* @return 拥有权限:true,否则false
*/
boolean hasPermission(String permission);
/**
* 判断当前用户是否是超级管理员
*/
boolean isAdmin();
/**
* 判断用户是否是从oauth2登录过来的
*/
boolean oauth2Flag();
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/context/LoginContext.java
|
Java
|
gpl-3.0
| 1,521
|
package com.zmops.iot.core.auth.context;
import com.zmops.iot.util.SpringContextHolder;
/**
* 当前登录用户信息获取的接口
*
* @author fengshuonan
*/
public class LoginContextHolder {
public static LoginContext getContext() {
return SpringContextHolder.getBean(LoginContext.class);
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/context/LoginContextHolder.java
|
Java
|
gpl-3.0
| 322
|
package com.zmops.iot.core.auth.entrypoint;
import com.alibaba.fastjson.JSON;
import com.zmops.iot.core.auth.exception.enums.AuthExceptionEnum;
import com.zmops.iot.model.response.ErrorResponseData;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
/**
* 这个端点用在用户访问受保护资源但是不提供任何token的情况下
* <p>
* 当前用户没有登录(没有token),访问了系统中的一些需要权限的接口,就会进入这个处理器
*
* @author fengshuonan
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -1L;
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// GET请求跳转到主页
if ("get".equalsIgnoreCase(request.getMethod())
&& !request.getHeader("Accept").contains("application/json")) {
response.sendRedirect(request.getContextPath() + "/global/sessionError");
} else {
// POST请求返回json
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
ErrorResponseData errorResponseData = new ErrorResponseData(
AuthExceptionEnum.NO_PAGE_ERROR.getCode(),
AuthExceptionEnum.NO_PAGE_ERROR.getMessage());
response.getWriter().write(JSON.toJSONString(errorResponseData));
}
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/entrypoint/JwtAuthenticationEntryPoint.java
|
Java
|
gpl-3.0
| 1,878
|
package com.zmops.iot.core.auth.exception;
import com.zmops.iot.model.exception.AbstractBaseExceptionEnum;
import lombok.Data;
/**
* 认证失败(账号密码错误,账号被冻结,token过期等)
*
* @author fengshuonan
*/
@Data
public class AuthException extends RuntimeException {
private Integer code;
private String errorMessage;
public AuthException() {
super("认证失败!");
this.code = 500;
this.errorMessage = "认证失败!";
}
public AuthException(AbstractBaseExceptionEnum exception) {
super(exception.getMessage());
this.code = exception.getCode();
this.errorMessage = exception.getMessage();
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/exception/AuthException.java
|
Java
|
gpl-3.0
| 707
|
package com.zmops.iot.core.auth.exception;
import com.zmops.iot.model.exception.AbstractBaseExceptionEnum;
import lombok.Data;
import static com.zmops.iot.core.auth.exception.enums.AuthExceptionEnum.NO_PERMISSION;
/**
* 没有访问权限
*
* @author fengshuonan
*/
@Data
public class PermissionException extends RuntimeException {
private Integer code;
private String errorMessage;
public PermissionException() {
super(NO_PERMISSION.getMessage());
this.code = NO_PERMISSION.getCode();
this.errorMessage = NO_PERMISSION.getMessage();
}
public PermissionException(AbstractBaseExceptionEnum exception) {
super(exception.getMessage());
this.code = exception.getCode();
this.errorMessage = exception.getMessage();
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/exception/PermissionException.java
|
Java
|
gpl-3.0
| 797
|
package com.zmops.iot.core.auth.exception.enums;
import com.zmops.iot.model.exception.AbstractBaseExceptionEnum;
import lombok.Getter;
/**
* 认证失败的异常枚举
*
* @author fengshuonan
*/
@Getter
public enum AuthExceptionEnum implements AbstractBaseExceptionEnum {
NOT_LOGIN_ERROR(1401, "用户未登录"),
NOT_EXIST_ERROR(1408, "用户不存在"),
USERNAME_PWD_ERROR(1402, "账号密码错误"),
LOGIN_EXPPIRED(1403, "登录已过期,请重新登录"),
ACCOUNT_FREEZE_ERROR(1404, "账号被冻结"),
NO_ROLE_ERROR(1405, "用户没有分配角色,获取菜单失败"),
VALID_CODE_ERROR(1406, "验证码错误"),
ZBX_LOGIN_ERROR(1407, "Zabbix平台登录获取Token失败"),
//用在PermissonException
NO_PERMISSION(1500, "用户没有此操作权限"),
NO_PAGE_ERROR(1502, "请求接口不存在或用户未登录"),
LOGIN_TIMEOUT(409, "登录超时,请重新登录!");
AuthExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
private Integer code;
private String message;
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/exception/enums/AuthExceptionEnum.java
|
Java
|
gpl-3.0
| 1,125
|
package com.zmops.iot.core.auth.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;
/**
* @author yefei
**/
@Slf4j
public class CommonFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
CommonHttpServletRequestWrapper customHttpServletRequestWrapper = null;
try {
HttpServletRequest req = (HttpServletRequest)request;
customHttpServletRequestWrapper = new CommonHttpServletRequestWrapper(req);
}catch (Exception e){
log.warn("commonHttpServletRequestWrapper Error:", e);
}
chain.doFilter((Objects.isNull(customHttpServletRequestWrapper) ? request : customHttpServletRequestWrapper), response);
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/filter/CommonFilter.java
|
Java
|
gpl-3.0
| 922
|
package com.zmops.iot.core.auth.filter;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
* @author yefei
**/
public class CommonHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String body;
public CommonHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
InputStream inputStream = null;
try {
inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
public void setBody(String body) {
this.body = body;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/filter/CommonHttpServletRequestWrapper.java
|
Java
|
gpl-3.0
| 2,792
|
package com.zmops.iot.core.auth.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.core.auth.util.FixLengthLinkedList;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.exception.enums.CoreExceptionEnum;
import com.zmops.iot.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author yefei
**/
@Slf4j
public class CommonInterceptor implements HandlerInterceptor {
// FixLengthLinkedList<Integer> list = new FixLengthLinkedList<>(10);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
// if (request instanceof CommonHttpServletRequestWrapper) {
// CommonHttpServletRequestWrapper requestWrapper = (CommonHttpServletRequestWrapper) request;
// int code = requestWrapper.getBody().hashCode();
// log.debug("*************************" + code);
// if (list.contains(code)) {
// throw new ServiceException(CoreExceptionEnum.REPEATED_SUBMIT);
// }
// list.add(code);
// }
HandlerMethod handlerMethod = (HandlerMethod) handler;
pushTenantId2Body(request, handlerMethod);
return true;
}
private void pushTenantId2Body(HttpServletRequest request, HandlerMethod handlerMethod) {
try {
MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
if (ArrayUtils.isEmpty(methodParameters)) {
return;
}
for (MethodParameter methodParameter : methodParameters) {
Class clazz = methodParameter.getParameterType();
if (request instanceof CommonHttpServletRequestWrapper) {
CommonHttpServletRequestWrapper requestWrapper = (CommonHttpServletRequestWrapper) request;
String body = requestWrapper.getBody();
JSONObject param = JSONObject.parseObject(body);
if (param == null || ToolUtil.isNotEmpty(param.getString("tenantId"))) {
return;
}
param.put("tenantId", LoginContextHolder.getContext().getUser().getTenantId());
requestWrapper.setBody(JSON.toJSONString(param));
}
}
} catch (Exception e) {
log.warn("fill userInfo to request body Error ", e);
}
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/filter/CommonInterceptor.java
|
Java
|
gpl-3.0
| 2,950
|
package com.zmops.iot.core.auth.filter;
import com.zmops.iot.core.auth.cache.SessionManager;
import com.zmops.iot.core.auth.jwt.JwtTokenUtil;
import com.zmops.iot.core.auth.util.TokenUtil;
import com.zmops.iot.util.ToolUtil;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.zmops.iot.constant.ConstantsContext.getTokenHeaderName;
/**
* 这个过滤器,在所有请求之前,也在spring security filters之前
* <p>
* 这个过滤器的作用是:接口在进业务之前,添加登录上下文(SecurityContext和LoginContext)
* <p>
* 没有用session,只能token来校验当前的登录人的身份,所以在进业务之前要给当前登录人设置登录状态
*
* @author fengshuonan
*/
@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
@Autowired
private SessionManager sessionManager;
public JwtAuthorizationTokenFilter() {
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
// 1.静态资源直接过滤,不走此过滤器
for (String reg : NoneAuthedResources.FRONTEND_RESOURCES) {
if (new AntPathMatcher().match(reg, request.getServletPath())) {
chain.doFilter(request, response);
return;
}
}
// 2.从cookie和header获取token
String authToken = TokenUtil.getToken();
// 3.通过token获取用户名
String username = null;
if (ToolUtil.isNotEmpty(authToken)) {
try {
username = JwtTokenUtil.getJwtPayLoad(authToken).getAccount();
} catch (IllegalArgumentException | JwtException e) {
//请求token为空或者token不正确,忽略,并不是所有接口都要鉴权
}
}
// 4.如果账号不为空,并且没有设置security上下文
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// 5.从缓存中拿userDetails,如果不为空,就设置登录上下文和权限上下文
UserDetails userDetails = sessionManager.getSession(authToken);
if (userDetails != null) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
return;
} else {
// 6.当用户的token过期了,缓存中没有用户信息,则删除相关cookies
Cookie[] tempCookies = request.getCookies();
if (tempCookies != null) {
for (Cookie cookie : tempCookies) {
if (getTokenHeaderName().equals(cookie.getName())) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
temp.setPath("/");
response.addCookie(temp);
}
}
}
//如果是不需要权限校验的接口不需要返回session超时
for (String reg : NoneAuthedResources.BACKEND_RESOURCES) {
if (new AntPathMatcher().match(reg, request.getServletPath())) {
chain.doFilter(request, response);
return;
}
}
//跳转到登录超时
response.setHeader("Zeus-Session-Timeout", "true");
request.getRequestDispatcher("/global/sessionError").forward(request, response);
}
}
chain.doFilter(request, response);
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/filter/JwtAuthorizationTokenFilter.java
|
Java
|
gpl-3.0
| 4,588
|
package com.zmops.iot.core.auth.filter;
/**
* 不需要身份验证的资源
*
* @author fengshuonan
*/
public class NoneAuthedResources {
/**
* 前端接口资源
*/
public static final String[] FRONTEND_RESOURCES = {
"/static/**",
"/favicon.ico"
};
/**
* 不走 filter 调用链 API
*/
public static final String[] NO_AUTH_API = {
"/login",
"/device/status",
"/device/service",
"/device/problem"
};
/**
* 不要权限校验的后端接口资源
* <p>
* ANT风格的接口正则表达式:
* <p>
* ? 匹配任何单字符<br/>
* * 匹配0或者任意数量的 字符<br/>
* ** 匹配0或者更多的 目录<br/>
*/
public static final String[] BACKEND_RESOURCES = {
//主页
"/",
//获取验证码
"/kaptcha",
//rest方式获取token入口
"/rest/login",
// 登录接口放开过滤
"/login",
"/device/service/execute",
//oauth登录的接口
"/oauth/render/*",
"/oauth/callback/*",
//单点登录接口
"/ssoLogin",
"/sysTokenLogin",
// session登录失效之后的跳转
"/global/sessionError",
// 图片预览 头像
"/system/preview/*",
// 错误页面的接口
"/error",
"/global/error"
};
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/filter/NoneAuthedResources.java
|
Java
|
gpl-3.0
| 1,549
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (sn93@qq.com)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.core.auth.jwt;
import com.zmops.iot.constant.ConstantsContext;
import com.zmops.iot.core.auth.jwt.payload.JwtPayLoad;
import com.zmops.iot.util.ToolUtil;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.Map;
/**
* <p>jwt token工具类</p>
* <pre>
* jwt的claim里一般包含以下几种数据:
* 1. iss -- token的发行者
* 2. sub -- 该JWT所面向的用户
* 3. aud -- 接收该JWT的一方
* 4. exp -- token的失效时间
* 5. nbf -- 在此时间段之前,不会被处理
* 6. iat -- jwt发布时间
* 7. jti -- jwt唯一标识,防止重复使用
* </pre>
*
* @author fengshuonan nantian
*/
public class JwtTokenUtil {
/**
* 生成token,根据userId和默认过期时间
*/
public static String generateToken(JwtPayLoad jwtPayLoad) {
Long expiredSeconds = getExpireSeconds();
final Date expirationDate = new Date(System.currentTimeMillis() + expiredSeconds * 1000);
return generateToken(String.valueOf(jwtPayLoad.getUserId()), expirationDate, jwtPayLoad.toMap());
}
/**
* 获取jwt的payload部分
*/
public static JwtPayLoad getJwtPayLoad(String token) {
Claims claimFromToken = getClaimFromToken(token);
return JwtPayLoad.toBean(claimFromToken);
}
/**
* 解析token是否正确(true-正确, false-错误)
*/
public static Boolean checkToken(String token) {
try {
String jwtSecret = getJwtSecret();
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
return true;
} catch (JwtException e) {
return false;
}
}
/**
* 验证token是否失效
*/
public static Boolean isTokenExpired(String token) {
try {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
} catch (ExpiredJwtException expiredJwtException) {
return true;
}
}
/**
* 获取jwt失效时间
*/
public static Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token).getExpiration();
}
/**
* 生成token,根据userId和过期时间
*/
public static String generateToken(String userId, Date exppiredDate, Map<String, Object> claims) {
final Date createdDate = new Date();
String secret = getJwtSecret();
if (claims == null) {
return Jwts.builder()
.setSubject(userId)
.setIssuedAt(createdDate)
.setExpiration(exppiredDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
} else {
return Jwts.builder()
.setClaims(claims)
.setSubject(userId)
.setIssuedAt(createdDate)
.setExpiration(exppiredDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
}
/**
* 获取jwt的payload部分
*/
public static Claims getClaimFromToken(String token) {
if (ToolUtil.isEmpty(token)) {
throw new IllegalArgumentException("token参数为空!");
}
String jwtSecret = getJwtSecret();
return Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody();
}
private static String getJwtSecret() {
return ConstantsContext.getJwtSecret();
}
private static Long getExpireSeconds() {
return ConstantsContext.getJwtSecretExpireSec();
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/jwt/JwtTokenUtil.java
|
Java
|
gpl-3.0
| 4,400
|
package com.zmops.iot.core.auth.jwt.payload;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* jwt的第二部分
*
* @author fengshuonan
*/
@Data
public class JwtPayLoad {
/**
* 用户id
*/
private Long userId;
/**
* 账号
*/
private String account;
/**
* 用户的键
*/
private String userKey;
public JwtPayLoad() {
}
public JwtPayLoad(Long userId, String account, String userKey) {
this.userId = userId;
this.account = account;
this.userKey = userKey;
}
/**
* payload转化为map形式
*
* @author fengshuonan
*/
public Map<String, Object> toMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("userId", this.userId);
map.put("account", this.account);
map.put("userKey", this.userKey);
return map;
}
/**
* payload转化为map形式
*
* @author fengshuonan
*/
public static JwtPayLoad toBean(Map<String, Object> map) {
if (map == null || map.size() == 0) {
return new JwtPayLoad();
} else {
JwtPayLoad jwtPayLoad = new JwtPayLoad();
Object userId = map.get("userId");
if (userId instanceof Long) {
jwtPayLoad.setUserId(Long.valueOf(map.get("userId").toString()));
}
jwtPayLoad.setAccount((String) map.get("account"));
jwtPayLoad.setUserKey((String) map.get("userKey"));
return jwtPayLoad;
}
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/jwt/payload/JwtPayLoad.java
|
Java
|
gpl-3.0
| 1,585
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.core.auth.model;
import com.zmops.iot.util.ToolUtil;
import lombok.Data;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 当前登录用户信息
*
* @author fengshuonan
*/
@Data
public class LoginUser implements UserDetails, Serializable {
private static final long serialVersionUID = 1L;
public LoginUser() {
super();
}
public LoginUser(Long id, String token) {
super();
this.id = id;
this.zbxToken = token;
}
/**
* 用户主键ID
*/
private Long id;
/**
* 账号
*/
private String account;
/**
* 姓名
*/
private String name;
/**
* 邮箱
*/
private String email;
/**
* 用户组
*/
private Long userGroupId;
/**
* 角色集
*/
private List<Long> roleList;
/**
* 角色名称集
*/
private List<String> roleNames;
/**
* 角色备注(code)
*/
private List<String> roleTips;
/**
* 系统标识集合
*/
private List<Map<String, Object>> systemTypes;
/**
* 拥有的权限
*/
private Set<String> permissions;
/**
* 租户ID
*/
private Long tenantId;
/**
* zabbix token
*
* @return
*/
private String zbxToken;
@Override
public List<UserRole> getAuthorities() {
ArrayList<UserRole> grantedAuthorities = new ArrayList<>();
if (ToolUtil.isNotEmpty(this.roleNames)) {
for (String roleName : this.roleNames) {
grantedAuthorities.add(new UserRole(roleName));
}
}
return grantedAuthorities;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return this.account;
}
@Override
public boolean isAccountNonExpired() {
//能生成loginUser就是jwt解析成功,没锁定
return true;
}
@Override
public boolean isAccountNonLocked() {
//能生成loginUser就是jwt解析成功,没锁定
return true;
}
@Override
public boolean isCredentialsNonExpired() {
//能生成loginUser就是jwt解析成功,没锁定
return true;
}
@Override
public boolean isEnabled() {
//能生成loginUser就是jwt解析成功,没锁定
return true;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/model/LoginUser.java
|
Java
|
gpl-3.0
| 3,241
|
package com.zmops.iot.core.auth.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
/**
* @author nantian created at 2021/7/29 18:16
*/
@Data
@AllArgsConstructor
public class UserRole implements GrantedAuthority {
private String roleName;
@Override
public String getAuthority() {
return roleName;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/model/UserRole.java
|
Java
|
gpl-3.0
| 400
|
package com.zmops.iot.core.auth.util;
import java.util.LinkedList;
/**
* @author yefei
**/
public class FixLengthLinkedList<T> extends LinkedList<T> {
private int capacity;
public FixLengthLinkedList(int capacity) {
super();
this.capacity = capacity;
}
@Override
public boolean add(T t) {
if (size() + 1 > capacity) {
super.removeFirst();
}
return super.add(t);
}
public static void main(String[] args) {
FixLengthLinkedList<String> linkedList = new FixLengthLinkedList<>(3);
for (int i = 0; i < 100; i++) {
linkedList.add(i + "");
}
linkedList.forEach(l -> System.out.println(l));
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/util/FixLengthLinkedList.java
|
Java
|
gpl-3.0
| 723
|
package com.zmops.iot.core.auth.util;
import com.zmops.iot.core.util.HttpContext;
import com.zmops.iot.util.ToolUtil;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static com.zmops.iot.constant.ConstantsContext.getTokenHeaderName;
/**
* 获取token的封装
*
* @author fengshuonan
*/
public class TokenUtil {
/**
* 获取token的两种方法
*
* @author fengshuonan
*/
public static String getToken() {
String authToken = null;
HttpServletRequest request = HttpContext.getRequest();
//权限校验的头部
String tokenHeader = getTokenHeaderName();
authToken = request.getHeader(tokenHeader);
//header中没有的话去cookie拿值,以header为准
if (ToolUtil.isEmpty(authToken)) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (tokenHeader.equals(cookie.getName())) {
authToken = cookie.getValue();
}
}
}
}
return authToken;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/auth/util/TokenUtil.java
|
Java
|
gpl-3.0
| 1,178
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.core.log;
import com.zmops.iot.dict.AbstractDictMap;
import com.zmops.iot.dict.SystemDict;
import java.lang.annotation.*;
/**
* 标记需要做业务日志的方法
*
* @author fengshuonan
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface BussinessLog {
/**
* 业务的名称,例如:"修改菜单"
*/
String value() default "";
/**
* 被修改的实体的唯一标识,例如:菜单实体的唯一标识为"id"
*/
String key() default "id";
/**
* 字典(用于查找key的中文名称和字段的中文名称)
*/
Class<? extends AbstractDictMap> dict() default SystemDict.class;
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/log/BussinessLog.java
|
Java
|
gpl-3.0
| 1,365
|
package com.zmops.iot.core.tree;
import java.util.List;
/**
* 树构建的抽象类,定义构建tree的基本步骤
*
* @author nantian
* @Date 2018/7/25 下午5:59
*/
public abstract class AbstractTreeBuildFactory<T> {
/**
* 树节点构建整体过程
*
* @author nantian
* @Date 2018/7/26 上午9:45
*/
public List<T> doTreeBuild(List<T> nodes) {
//构建之前的节点处理工作
List<T> readyToBuild = beforeBuild(nodes);
//具体构建的过程
List<T> builded = executeBuilding(readyToBuild);
//构建之后的处理工作
return afterBuild(builded);
}
/**
* 构建之前的处理工作
*
* @author nantian
* @Date 2018/7/26 上午10:10
*/
protected abstract List<T> beforeBuild(List<T> nodes);
/**
* 具体的构建过程
*
* @author nantian
* @Date 2018/7/26 上午10:11
*/
protected abstract List<T> executeBuilding(List<T> nodes);
/**
* 构建之后的处理工作
*
* @author nantian
* @Date 2018/7/26 上午10:11
*/
protected abstract List<T> afterBuild(List<T> nodes);
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/tree/AbstractTreeBuildFactory.java
|
Java
|
gpl-3.0
| 1,187
|
package com.zmops.iot.core.tree;
import com.zmops.iot.model.node.Tree;
import com.zmops.iot.util.ToolUtil;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 默认递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
*
* @author nantian
* @Date 2018/7/25 下午5:59
*/
@Data
public class DefaultTreeBuildFactory<T extends Tree> extends AbstractTreeBuildFactory<T> {
/**
* 顶级节点的父节点id(默认-1)
*/
private String rootParentId = "0";
/**
* 查询子节点的集合
*
* @param totalNodes 所有节点的集合
* @param node 被查询节点的id
* @param childNodeLists 被查询节点的子节点集合
*/
private void buildChildNodes(List<T> totalNodes, T node, List<T> childNodeLists) {
if (totalNodes == null || node == null) {
return;
}
List<T> nodeSubLists = getSubChildsLevelOne(totalNodes, node);
if (nodeSubLists.size() == 0) {
} else {
for (T nodeSubList : nodeSubLists) {
buildChildNodes(totalNodes, nodeSubList, new ArrayList<>());
}
}
childNodeLists.addAll(nodeSubLists);
node.setChildrenNodes(childNodeLists);
}
/**
* 获取子一级节点的集合
*
* @param list 所有节点的集合
* @param node 被查询节点的model
* @author nantian
*/
private List<T> getSubChildsLevelOne(List<T> list, T node) {
List<T> nodeList = new ArrayList<>();
for (T nodeItem : list) {
if (nodeItem.getNodeParentId().equals(node.getNodeId())) {
nodeList.add(nodeItem);
}
}
return nodeList;
}
@Override
protected List<T> beforeBuild(List<T> nodes) {
//默认不进行前置处理,直接返回
return nodes;
}
@Override
protected List<T> executeBuilding(List<T> nodes) {
for (T treeNode : nodes) {
this.buildChildNodes(nodes, treeNode, new ArrayList<>());
}
return nodes;
}
@Override
protected List<T> afterBuild(List<T> nodes) {
//去掉所有的二级节点
ArrayList<T> results = new ArrayList<>();
for (T node : nodes) {
if (node.getNodeParentId().equals(rootParentId)) {
results.add(node);
}
if (ToolUtil.isEmpty(node.getChildrenNodes())) {
node.setChildrenNodes(null);
}
}
return results;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/tree/DefaultTreeBuildFactory.java
|
Java
|
gpl-3.0
| 2,604
|
package com.zmops.iot.core.util;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.exception.enums.CoreExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author nantian created at 2021/7/30 15:32
*/
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
public static byte[] toByteArray(String filename) {
File f = new File(filename);
if (!f.exists()) {
log.error("文件未找到!" + filename);
throw new ServiceException(CoreExceptionEnum.FILE_NOT_FOUND);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
} finally {
try {
channel.close();
} catch (IOException e) {
throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
}
try {
fs.close();
} catch (IOException e) {
throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
}
}
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/util/FileUtil.java
|
Java
|
gpl-3.0
| 1,716
|
package com.zmops.iot.core.util;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @author nantian created at 2021/7/29 18:13
*/
public class HttpContext {
private static final String LOCALHOST = "127.0.0.1";
/**
* 获取请求的ip地址
*
* @author fengshuonan
*/
public static String getIp() {
HttpServletRequest request = HttpContext.getRequest();
if (request == null) {
return "127.0.0.1";
} else {
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 ) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 ) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 ) {
ipAddress = request.getRemoteAddr();
if (LOCALHOST.equals(ipAddress)) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
}
/**
* 获取当前请求的Request对象
*
* @author fengshuonan
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return null;
} else {
return requestAttributes.getRequest();
}
}
/**
* 获取当前请求的Response对象
*
* @author fengshuonan
*/
public static HttpServletResponse getResponse() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return null;
} else {
return requestAttributes.getResponse();
}
}
/**
* 获取所有请求的值
*
* @author fengshuonan
*/
public static Map<String, String> getRequestParameters() {
HashMap<String, String> values = new HashMap<>();
HttpServletRequest request = HttpContext.getRequest();
if (request == null) {
return values;
}
Enumeration enums = request.getParameterNames();
while (enums.hasMoreElements()) {
String paramName = (String) enums.nextElement();
String paramValue = request.getParameter(paramName);
values.put(paramName, paramValue);
}
return values;
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/util/HttpContext.java
|
Java
|
gpl-3.0
| 3,373
|
package com.zmops.iot.core.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author nantian created at 2021/7/31 19:56
*/
public class MD5Util {
public static String encrypt(String source) {
return encodeMd5(source.getBytes());
}
private static String encodeMd5(byte[] source) {
try {
return encodeHex(MessageDigest.getInstance("MD5").digest(source));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private static String encodeHex(byte[] bytes) {
StringBuffer buffer = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10)
buffer.append("0");
buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buffer.toString();
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/util/MD5Util.java
|
Java
|
gpl-3.0
| 944
|
package com.zmops.iot.core.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
/**
* Rsa加解密工具
*
* @author yefei
*/
public class RsaUtil {
/**
* RSA私钥解密
*/
public static String decrypt(String str, String privateKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/util/RsaUtil.java
|
Java
|
gpl-3.0
| 1,008
|
package com.zmops.iot.core.util;
import com.zmops.iot.util.ToolUtil;
/**
* 密码加盐的工具
*
* @author yefei
*/
public class SaltUtil {
/**
* 获取密码盐
*
* @author yefei
*/
public static String getRandomSalt() {
return ToolUtil.getRandomString(5);
}
/**
* md5加密,带盐值
*
* @author yefei
*/
public static String md5Encrypt(String password, String salt) {
if (ToolUtil.isOneEmpty(password, salt)) {
throw new IllegalArgumentException("密码为空!");
} else {
return MD5Util.encrypt(password + salt);
}
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/util/SaltUtil.java
|
Java
|
gpl-3.0
| 659
|
package com.zmops.iot.core.web.base;
import com.zmops.iot.core.util.HttpContext;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.exception.enums.CoreExceptionEnum;
import com.zmops.iot.model.response.SuccessResponseData;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Objects;
/**
* @author nantian created at 2021/7/29 20:32
*/
public class BaseController {
protected final String REDIRECT = "redirect:";
protected final String FORWARD = "forward:";
protected static SuccessResponseData SUCCESS_TIP = new SuccessResponseData();
protected HttpServletRequest getHttpServletRequest() {
return HttpContext.getRequest();
}
protected HttpServletResponse getHttpServletResponse() {
return HttpContext.getResponse();
}
protected HttpSession getSession() {
return Objects.requireNonNull(HttpContext.getRequest()).getSession();
}
protected HttpSession getSession(Boolean flag) {
return Objects.requireNonNull(HttpContext.getRequest()).getSession(flag);
}
protected String getPara(String name) {
return Objects.requireNonNull(HttpContext.getRequest()).getParameter(name);
}
protected void setAttr(String name, Object value) {
Objects.requireNonNull(HttpContext.getRequest()).setAttribute(name, value);
}
/**
* 删除cookie
*/
protected void deleteCookieByName(String cookieName) {
Cookie[] cookies = this.getHttpServletRequest().getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
this.getHttpServletResponse().addCookie(temp);
}
}
}
/**
* 删除所有cookie
*/
protected void deleteAllCookie() {
Cookie[] cookies = this.getHttpServletRequest().getCookies();
for (Cookie cookie : cookies) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
this.getHttpServletResponse().addCookie(temp);
}
}
/**
* 返回前台文件流
*
* @author fengshuonan
*/
protected ResponseEntity<InputStreamResource> renderFile(String fileName, String filePath) {
try {
final FileInputStream inputStream = new FileInputStream(filePath);
return renderFile(fileName, inputStream);
} catch (FileNotFoundException e) {
throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
}
}
/**
* 返回前台文件流
*
* @author fengshuonan
*/
protected ResponseEntity<InputStreamResource> renderFile(String fileName, byte[] fileBytes) {
return renderFile(fileName, new ByteArrayInputStream(fileBytes));
}
/**
* 返回前台文件流
*
* @param fileName 文件名
* @param inputStream 输入流
* @return
* @author 0x0001
*/
protected ResponseEntity<InputStreamResource> renderFile(String fileName, InputStream inputStream) {
InputStreamResource resource = new InputStreamResource(inputStream);
String dfileName = null;
try {
dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", dfileName);
return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
}
}
|
2301_81045437/zeus-iot
|
zeus-core/src/main/java/com/zmops/iot/core/web/base/BaseController.java
|
Java
|
gpl-3.0
| 4,106
|
package com.zmops.zeus.driver.annotation;
import java.lang.annotation.*;
/**
* @author nantian
* <p>
* 指定接口文件 路径
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JsonPath {
String value() default "";
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/annotation/JsonPath.java
|
Java
|
gpl-3.0
| 278
|
package com.zmops.zeus.driver.annotation;
/**
* @author nantian
* <p>
* 标记单个值 name
*/
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ParamName {
String value() default "";
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/annotation/ParamName.java
|
Java
|
gpl-3.0
| 278
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class Interface {
private String interfaceid;
private String hostid;
private String deviceId;
private String main = "1";
private String type = "1";
private String useip="1";
private String ip;
private String dns="";
private String port;
private String avaiable;
private String error;
private String errors_from;
private String disable_until;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/Interface.java
|
Java
|
gpl-3.0
| 507
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class ItemParam {
private String host;
private String key;
private String value;
private Long clock;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ItemParam.java
|
Java
|
gpl-3.0
| 220
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
public class SendParam {
private List<ItemParam> params;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/SendParam.java
|
Java
|
gpl-3.0
| 179
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author yefei
*/
@Data
public class ZbxHostGrpInfo {
private String groupid;
private String name;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxHostGrpInfo.java
|
Java
|
gpl-3.0
| 178
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
import java.util.List;
/**
* @author nantian created at 2021/8/10 17:52
*/
@Data
public class ZbxItemInfo {
private String itemid;
private String hostid;
private String name;
private String key_;
private String status;
private String value_type;
private String units;
private String valuemapid;
private String interfaceid;
private String error;
private List<HostInfo> hosts;
@Data
public static class HostInfo {
private String hostid;
private String host;
}
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxItemInfo.java
|
Java
|
gpl-3.0
| 607
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author nantian created at 2021/8/10 17:52
*/
@Data
public class ZbxProblemInfo {
private String eventid;
private String source;
private String object;
private String objectid;
private String clock;
private String ns;
private String r_eventid;
private String r_clock;
private String r_ns;
private String correlationid;
private String userid;
private String name;
private String acknowledged;
private String severity;
private String opdata;
private String acknowledges;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxProblemInfo.java
|
Java
|
gpl-3.0
| 621
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author nantian created at 2021/8/5 11:22
*/
@Data
public class ZbxProcessingStep {
private String type;
private String params;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxProcessingStep.java
|
Java
|
gpl-3.0
| 209
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author nantian created at 2021/8/2 16:59
*/
@Data
public class ZbxResponseData {
private String jsonrpc;
private String result;
private ErrorInfo error;
@Data
public static class ErrorInfo {
private Integer code;
private String message;
private String data;
}
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxResponseData.java
|
Java
|
gpl-3.0
| 389
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author yefei
*/
@Data
public class ZbxUserGrpInfo {
private String usrgrpid;
private String name;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxUserGrpInfo.java
|
Java
|
gpl-3.0
| 179
|
package com.zmops.zeus.driver.entity;
import lombok.Data;
/**
* @author yefei
*/
@Data
public class ZbxUserInfo {
private String userid;
private String username;
private String name;
private String surname;
private String roleid;
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/entity/ZbxUserInfo.java
|
Java
|
gpl-3.0
| 258
|
package com.zmops.zeus.driver.inteceptor;
import com.alibaba.fastjson.JSON;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.reflection.ForestMethod;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.model.exception.ZbxApiException;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.entity.ZbxResponseData;
import com.zmops.zeus.driver.parser.JsonParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Created by nantian on 2021-03-12 23:00
*
* @version 1.0 拦截器 基于 JSON 文件构建 JSON String 参数
*/
@Slf4j
public class JsonBodyBuildInterceptor implements Interceptor<String> {
private static final String NO_AUTH_TAG = "authTag";
/**
* 方法调用之前获取 JSON path
*/
@Override
public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {
Map<String, Object> paramMap = new HashMap<>();
if (request.getHeader(NO_AUTH_TAG) == null || !"noAuth".equals(request.getHeader(NO_AUTH_TAG).getValue())) {
paramMap.put("userAuth", LoginContextHolder.getContext().getUser().getZbxToken());
}
if (null != args && args.length > 0) {
// 优先 Map 的处理
if (args[0] instanceof Map) {
paramMap.putAll((Map) args[0]);
} else {
Annotation[][] paramAnnos = method.getMethod().getParameterAnnotations();
for (int i = 0; i < args.length; i++) {
if (paramAnnos[i].length > 0 && paramAnnos[i][0] instanceof ParamName) {
ParamName paramAnno = (ParamName) paramAnnos[i][0];
paramMap.put(paramAnno.value(), args[i]);
}
}
}
}
JsonPath jsonPath = method.getMethod().getAnnotation(JsonPath.class);
if (null != jsonPath && StringUtils.isNotBlank(jsonPath.value())) {
String body = Objects.requireNonNull(JsonParseUtil.parse(jsonPath.value() + ".ftl", paramMap));
String sendBody = StringEscapeUtils.unescapeJava(body);
log.debug("\n" + sendBody + "\n");
request.replaceBody(sendBody);
request.setContentType("application/json");
}
}
/**
* Zabbix 接口异常返回异常信息捕捉
*/
@Override
public void onSuccess(String data, ForestRequest request, ForestResponse response) {
ZbxResponseData responseData = JSON.parseObject(data, ZbxResponseData.class);
if (null != responseData.getError()) {
log.error(response.getContent());
throw new ZbxApiException(responseData.getError().getCode(), responseData.getError().getData());
}
response.setResult(responseData.getResult());
Interceptor.super.onSuccess(data, request, response);
}
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/inteceptor/JsonBodyBuildInterceptor.java
|
Java
|
gpl-3.0
| 3,261
|
package com.zmops.zeus.driver.parser;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.StringWriter;
import java.util.Map;
/**
* Created by nantian on 2021-03-13 0:17
*
* @version 1.0
*/
public class JsonParseUtil {
private static final Configuration configuration;
static {
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(JsonParseUtil.class, "/api-json");
configuration.setCacheStorage(new NullCacheStorage());
configuration.setTemplateUpdateDelayMilliseconds(1000);
try {
configuration.setSetting("number_format", "computer");
} catch (TemplateException e) {
e.printStackTrace();
}
}
/**
* Freemarker 解析 JSON API 请求数据
*
* @param jsonPath json 文件路径
* @param args 入参
* @return 返回 JSON 串
*/
public static String parse(String jsonPath, Map<String, Object> args) {
try {
Template template = configuration.getTemplate(jsonPath);
StringWriter out = new StringWriter();
template.process(args, out);
return out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/parser/JsonParseUtil.java
|
Java
|
gpl-3.0
| 1,516
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Body;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.extensions.BasicAuth;
import com.dtflys.forest.http.ForestResponse;
/**
* @author yefei
**/
@BaseRequest(
baseURL = "${taosUrl}"
)
public interface TDEngineRest {
/**
* TDEngine execute sql, 必须 2.2.0 以上版本
*
* @param sql
* @return String
*/
@Post(
contentType = "application/json;charset=utf-8"
)
@BasicAuth(username = "${taosUser}", password = "${taosPwd}")
ForestResponse<String> executeSql(@Body String sql);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/TDEngineRest.java
|
Java
|
gpl-3.0
| 692
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.*;
import com.dtflys.forest.http.ForestResponse;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
@BaseRequest(baseURL = "http://172.16.50.1:3000/logkit")
public interface TransferKit {
/**
* 配置信息
*
* @return
*/
@Get(url = "/configs")
String getConfigs();
/**
* 状态信息
*
* @return
*/
@Get(url = "/status")
String getStatus();
@Post(url = "/configs/${runnerName}",
interceptor = JsonBodyBuildInterceptor.class)
@JsonPath("/transfer/create")
String createRunner(@DataVariable("runnerName") String runnerName,
@ParamName("runnerName") String name,
@ParamName("logPath") String logPath,
@ParamName("batchInterval") Integer batchInterval,
@ParamName("batchSize") Integer batchSize);
@Put(url = "/configs/${runnerName}",
interceptor = JsonBodyBuildInterceptor.class)
@JsonPath("/transfer/create")
String updateRunner(@DataVariable("runnerName") String runnerName,
@ParamName("runnerName") String name,
@ParamName("logPath") String logPath,
@ParamName("httpSendUrl") String httpSendUrl);
/**
* 关闭 采集器 Runner
*
* @param runnerName 采集器 runner 名称
* @return
*/
@Post(url = "/configs/${runnerName}/stop")
ForestResponse<String> stopRunner(@DataVariable("runnerName") String runnerName);
/**
* 开启 采集器 Runner
*
* @param runnerName 采集器 runner 名称
* @return
*/
@Post(url = "/configs/${runnerName}/start")
ForestResponse<String> startRunner(@DataVariable("runnerName") String runnerName);
/**
* 重置 采集器 Runner
*
* @param runnerName 采集器 runner 名称
* @return
*/
@Post(url = "/configs/${runnerName}/reset")
ForestResponse<String> resetRunner(@DataVariable("runnerName") String runnerName);
/**
* 开启 采集器 Runner
*
* @param runnerName 采集器 runner 名称
* @return
*/
@Delete(url = "/configs/${runnerName}")
ForestResponse<String> deleteRunner(@DataVariable("runnerName") String runnerName);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/TransferKit.java
|
Java
|
gpl-3.0
| 2,496
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
/**
* @author nantian created at 2021/8/3 11:58
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxApiInfo {
/**
* 接口信息
*
* @return String apiinfo
*/
@Post(headers = "authTag: noAuth")
@JsonPath("/apiinfo/apiinfo")
public String getApiInfo();
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxApiInfo.java
|
Java
|
gpl-3.0
| 654
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.DataVariable;
import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Var;
import com.zmops.zeus.driver.entity.SendParam;
/**
* @author yefei
*/
public interface ZbxConfig {
/**
* 读取 zbx 配置信息
*
* @return String
*/
@Post(url = "http://127.0.0.1:12800/zabbix/config")
String getConfig();
/**
* 读取 zbx 配置信息
*
* @return String
*/
@Post(url = "http://${ip}:12800/device/attr/send")
String sendData(@Var("ip") String ip, @JSONBody SendParam sendParam);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxConfig.java
|
Java
|
gpl-3.0
| 689
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
/**
* @author nantian created at 2021/8/10 16:32
* <p>
* 设备离线 在线触发器,判断设备 在线,离线 状态
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxDeviceStatusTrigger {
/**
* 创建 设备 在线,离线 触发器
*
* @return String
*/
@Post
@JsonPath("/trigger/device.status.trigger")
String createDeviceStatusTrigger(@ParamName("ruleId") String ruleId,
@ParamName("deviceId") String deviceId,
@ParamName("itemKey") String itemKey,
@ParamName("ruleCondition") String ruleCondition,
@ParamName("ruleFunction") String ruleFunction,
@ParamName("itemKeyRecovery") String itemKeyRecovery,
@ParamName("ruleConditionRecovery") String ruleConditionRecovery,
@ParamName("ruleFunctionRecovery") String ruleFunctionRecovery);
/**
* 修改 设备 在线,离线 触发器
*
* @return String
*/
@Post
@JsonPath("/trigger/device.status.trigger.update")
String updateDeviceStatusTrigger(@ParamName("triggerId") String triggerId,
@ParamName("ruleId") String ruleId,
@ParamName("deviceId") String deviceId,
@ParamName("itemKey") String itemKey,
@ParamName("ruleCondition") String ruleCondition,
@ParamName("ruleFunction") String ruleFunction,
@ParamName("itemKeyRecovery") String itemKeyRecovery,
@ParamName("ruleConditionRecovery") String ruleConditionRecovery,
@ParamName("ruleFunctionRecovery") String ruleFunctionRecovery,
@ParamName("recoveryTriggerId") String recoveryTriggerId);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxDeviceStatusTrigger.java
|
Java
|
gpl-3.0
| 2,486
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* @author nantian created at 2021/8/3 14:50
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxHistoryGet {
@Post
@JsonPath("/history/history.get")
String historyGet(@ParamName("hostid") String hostid,
@ParamName("itemids") List<String> itemids,
@ParamName("hisNum") Integer hisNum,
@ParamName("valueType") Integer valueType,
@ParamName("timeFrom") Long timeFrom,
@ParamName("timeTill") Long timeTill);
@Post(headers = "authTag: noAuth")
@JsonPath("/history/history.get")
String historyGetWithNoAuth(@ParamName("hostid") String hostid,
@ParamName("itemids") List<String> itemids,
@ParamName("hisNum") Integer hisNum,
@ParamName("valueType") Integer valueType,
@ParamName("userAuth") String zbxApiToken);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxHistoryGet.java
|
Java
|
gpl-3.0
| 1,413
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.entity.Interface;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* @author nantian created at 2021/8/3 14:54
* <p>
* 主机驱动
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxHost {
/**
* 创建主机
*
* @param hostName 主机名
* @param groupids 主机分组IDs
* @param templateid 主机模板ID,对应产品物模型ID
* @return
*/
@Post
@JsonPath("/host/host.create")
String hostCreate(@ParamName("hostName") String hostName,
@ParamName("groupids") List<String> groupids,
@ParamName("templateid") String templateid,
@ParamName("proxyid") String proxyid,
@ParamName("interfaces") Interface interfaces);
/**
* 修改主机
*
* @param hostid 主机ID
* @param groupids 主机分组IDs
* @param templateid 主机模板ID,对应产品物模型ID
* @return
*/
@Post
@JsonPath("/host/host.update")
String hostUpdate(@ParamName("hostid") String hostid,
@ParamName("groupids") List<String> groupids,
@ParamName("templateid") String templateid,
@ParamName("proxyid") String proxyid,
@ParamName("interfaces") Interface interfaces);
/**
* 修改主机状态
*
* @param hostid 主机ID
* @param status 主机状态
* @return
*/
@Post
@JsonPath("/host/host.status.update")
String hostStatusUpdate(@ParamName("hostid") String hostid,
@ParamName("status") String status);
/**
* 删除主机
*
* @param hostIds 主机ID
* @return
*/
@Post
@JsonPath("/host/host.delete")
String hostDelete(@ParamName("hostIds") List<String> hostIds);
/**
* 查询主机详情
*
* @param hostid 主机ID
*/
@Post
@JsonPath("/host/host.get")
String hostDetail(@ParamName("hostid") String hostid);
/**
* 查询主机
*
* @param host 主机ID
*/
@Post
@JsonPath("/host/host.get")
String hostGet(@ParamName("host") String host);
/**
* 更新主机宏
*
* @param hostId 主机ID
* @param macroList macro 列表
* @return
*/
@Post
@JsonPath("/host/host.macro.update")
String hostMacroUpdate(@ParamName("hostId") String hostId,
@ParamName("macros") List<Macro> macroList);
/**
* 更新主机标签
*
* @param tagMap 标签Map
* @return String
*/
@Post
@JsonPath("/host/host.tag.update")
String hostTagUpdate(@ParamName("hostId") String hostId,
@ParamName("tagMap") Map<String, String> tagMap);
/**
* 通过主机名获取 模板IDS
*
* @param hostname
* @return
*/
@Post
@JsonPath("/host/host.tempid.get")
String hostTempidGet(@ParamName("hostname") String hostname);
@Data
class Macro {
String key;
String value;
String desc;
}
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxHost.java
|
Java
|
gpl-3.0
| 3,580
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* @author nantian created at 2021/8/3 16:02
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxHostGroup {
/**
* 获取 全局 主机组
*
* @param userAuth api token
* @return String
*/
@Post(headers = "authTag: noAuth")
@JsonPath("/hostgroup/hostgroup.global.get")
String getGlobalHostGroup(@ParamName("userAuth") String userAuth);
/**
* 创建默认全局主机组
*
* @param userAuth userToken
* @return String
*/
@Post(headers = "authTag: noAuth")
@JsonPath("/hostgroup/hostgroup.init.create")
String createGlobalHostGroup(@ParamName("userAuth") String userAuth);
/**
* 创建主机组
*
* @param hostGroupName 主机组名称
* @return String
*/
@Post
@JsonPath("/hostgroup/hostgroup.create")
String hostGroupCreate(@ParamName("hostGroupName") String hostGroupName);
/**
* 删除主机组
*
* @param hostGrpIds 主机组IDS
* @return String
*/
@Post
@JsonPath("/hostgroup/hostgroup.delete")
String hostGroupDelete(@ParamName("hostGroupIds") List<String> hostGrpIds);
/**
* 获取 主机组
*
* @return String
*/
@Post
@JsonPath("/hostgroup/hostgroup.get")
String getHostGroup(@ParamName("groupids") String groupids);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxHostGroup.java
|
Java
|
gpl-3.0
| 1,776
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
/**
* @author nantian created at 2021/8/26 12:20
*/
public interface ZbxInitService {
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/usergroup/cookieUserGroupCreate")
String createCookieUserGroup(@ParamName("hostGroupId") String hostGroupId, @ParamName("userAuth") String userAuth);
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/usergroup/cookieUserGroupGet")
String getCookieUserGroup(@ParamName("userAuth") String userAuth);
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/user/cookieUserGet")
String getCookieUser(@ParamName("userAuth") String userAuth);
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/user/cookieUserAdd")
String createCookieUser(@ParamName("usrGrpId") String usrGrpId,
@ParamName("userAuth") String userAuth,
@ParamName("roleId") String roleId);
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/role/adminRole.get")
String getAdminRole(@ParamName("userAuth") String zbxApiToken);
@Post(
url = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
headers = "authTag: noAuth",
interceptor = JsonBodyBuildInterceptor.class
)
@JsonPath("/role/guestRole.get")
String getGuestRole(@ParamName("userAuth") String zbxApiToken);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxInitService.java
|
Java
|
gpl-3.0
| 2,308
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
/**
* @author yefei
**/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}/zabbix/api_jsonrpc.php",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxInterface {
/**
* 查询主机接口
*
* @param hostid 主机ID
*/
@Post
@JsonPath("/hostinterface/hostinterface.get")
String hostinterfaceGet(@ParamName("hostid") String hostid);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxInterface.java
|
Java
|
gpl-3.0
| 715
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.entity.ZbxProcessingStep;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
import java.util.Map;
/**
* @author nantian created at 2021/8/4 18:07
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxItem {
/**
* 创建 Zabbix Trapper ITEM
*
* @param itemName 名称
* @param itemKey 唯一Key
* @param hostId 主机ID
* @param valueType 值类型 0 和 3 数字
* @param units 单位
* @param processingStepList 预处理步骤
* @param valuemapid 值映射ID
* @param tagMap 标签
* @return String
*/
@Post
@JsonPath("/item/item.trapper.create")
String createTrapperItem(@ParamName("itemName") String itemName,
@ParamName("itemKey") String itemKey,
@ParamName("hostId") String hostId,
@ParamName("source") String source,
@ParamName("delay") String delay,
@ParamName("masterItemid") String masterItemid,
@ParamName("valueType") String valueType,
@ParamName("units") String units,
@ParamName("processList") List<ZbxProcessingStep> processingStepList,
@ParamName("valuemapid") String valuemapid,
@ParamName("tagMap") Map<String, String> tagMap,
@ParamName("interfaceid") String interfaceid);
/**
* 修改 Zabbix Trapper ITEM
*
* @param itemid ID
* @param itemName 名称
* @param itemKey 唯一Key
* @param hostId 主机ID
* @param valueType 值类型 0 和 3 数字
* @param units 单位
* @param processingStepList 预处理步骤
* @param valuemapid 值映射ID
* @param tagMap 标签
* @return String
*/
@Post
@JsonPath("/item/item.trapper.update")
String updateTrapperItem(@ParamName("itemid") String itemid,
@ParamName("itemName") String itemName,
@ParamName("itemKey") String itemKey,
@ParamName("hostId") String hostId,
@ParamName("source") String source,
@ParamName("delay") String delay,
@ParamName("masterItemid") String masterItemid,
@ParamName("valueType") String valueType,
@ParamName("units") String units,
@ParamName("processList") List<ZbxProcessingStep> processingStepList,
@ParamName("valuemapid") String valuemapid,
@ParamName("tagMap") Map<String, String> tagMap,
@ParamName("interfaceid") String interfaceid);
/**
* 删称 Zabbix Trapper ITEM
*
* @param itemIds ID
*/
@Post
@JsonPath("/item/item.trapper.delete")
String deleteTrapperItem(@ParamName("itemIds") List<String> itemIds);
/**
* 根据itemid 获取 ITEM 基本信息
*
* @param itemId itemid
* @return String
*/
@Post
@JsonPath("/item/item.get")
String getItemInfo(@ParamName("itemId") String itemId, @ParamName("hostid") String hostid);
/**
* 根据item key 获取 ITEM 信息
*
* @param key key
* @return String
*/
@Post
@JsonPath("/item/item.get")
String getItemList(@ParamName("key") String key, @ParamName("hostid") String hostid);
/**
* 根据item name 获取 ITEM 信息
*
* @param name name
* @return String
*/
@Post
@JsonPath("/item/item.name.get")
String getItemListByName(@ParamName("name") String name);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxItem.java
|
Java
|
gpl-3.0
| 4,367
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* 宏定义接口
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxMacro {
/**
* 创建宏
*
* @param hostid 主机ID
* @param macro 宏 Key
* @param value 宏 Value
* @return
*/
@Post
@JsonPath("/macro/usermacro.create")
String macroCreate(@ParamName("hostid") String hostid,
@ParamName("macro") String macro,
@ParamName("value") String value,
@ParamName("description") String description);
/**
* 更新 宏
*
* @param macroid 宏 ID
* @param macro 宏 Key
* @param value 宏 Value
* @return
*/
@Post
@JsonPath("/macro/usermacro.update")
String macroUpdate(@ParamName("macroid") String macroid,
@ParamName("macro") String macro,
@ParamName("value") String value,
@ParamName("description") String description);
/**
* 获取 宏
*
* @param hostid 主机ID
* @return
*/
@Post
@JsonPath("/macro/usermacro.get")
String macroGet(@ParamName("hostid") String hostid);
/**
* 搜索 宏 ID
*
* @param hostid 主机ID
* @param macro 宏 Key
* @return
*/
@Post
@JsonPath("/macro/usermacro.filter.get")
String macroQuery(@ParamName("hostid") String hostid,
@ParamName("macro") String macro);
/**
* 删除宏
*
* @param macroids 宏IDs
* @return
*/
@Post
@JsonPath("/macro/usermacro.delete")
String macroDelete(@ParamName("macroids") List<String> macroids);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxMacro.java
|
Java
|
gpl-3.0
| 2,099
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
/**
* @author nantian created at 2021/8/7 23:27
*/
@BaseRequest(baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}", interceptor = JsonBodyBuildInterceptor.class)
public interface ZbxProblem {
/**
* 告警列表
*
* @param hostId
* @return String
*/
@Post
@JsonPath("/problem/problem.get")
String getProblem(@ParamName("hostId") String hostId,
@ParamName("timeFrom") Long timeFrom,
@ParamName("timeTill") Long timeTill,
@ParamName("recent") String recent,
@ParamName("severity") String severity);
@Post
@JsonPath("/problem/problem.event.get")
String getEventProblem(@ParamName("hostId") String hostId,
@ParamName("timeFrom") Long timeFrom,
@ParamName("timeTill") Long timeTill,
@ParamName("recent") String recent);
@Post
@JsonPath("/problem/problem.acknowledgement")
String acknowledgement(@ParamName("eventId") String eventId, @ParamName("action") int action);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxProblem.java
|
Java
|
gpl-3.0
| 1,415
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* @author yefei
* <p>
* 代理驱动
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}/zabbix/api_jsonrpc.php",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxProxy {
/**
* 创建代理
*
* @param name 代理名称
* @return
*/
@Post
@JsonPath("/proxy/proxy.create")
String proxyCreate(@ParamName("name") String name);
/**
* 删除代理
*
* @param hostIds 主机ID
* @return
*/
@Post
@JsonPath("/proxy/proxy.delete")
String proxyDelete(@ParamName("hostIds") List<String> hostIds);
/**
* 代理列表
*
* @return
*/
@Post
@JsonPath("/proxy/proxy.get")
String get(@ParamName("proxyids") String proxyids);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxProxy.java
|
Java
|
gpl-3.0
| 1,112
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.Map;
/**
* @author nantian created at 2021/8/3 15:47
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxTemplate {
/**
* 创建模板
*
* @param templateName 模板名称
* @param groupId 模板分组ID
* @return String
*/
@Post
@JsonPath("/template/template.create")
String templateCreate(@ParamName("templateName") String templateName,
@ParamName("groupId") String groupId);
/**
* 删除模板
*
* @param templateid 模板ID
* @return String
*/
@Post
@JsonPath("/template/template.delete")
String templateDelete(@ParamName("templateid") String templateid);
/**
* 更新模板标签
*
* @param tagMap 标签Map
* @return String
*/
@Post
@JsonPath("/template/template.tag.update")
String templateTagUpdate(@ParamName("templateId") String templateId,
@ParamName("tagMap") Map<String, String> tagMap);
/**
* 查询模板详情
*
* @param templateid 模板ID
*/
@Post
@JsonPath("/template/template.detail.get")
String templateDetail(@ParamName("templateid") String templateid);
/**
* 查询模板信息
*
* @param templateid 模板ID
*/
@Post
@JsonPath("/template/template.get")
String templateGet(@ParamName("templateid") String templateid);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxTemplate.java
|
Java
|
gpl-3.0
| 1,842
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.Map;
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxTrigger {
/**
* 创建告警触发器
*
* @param triggerName 触发器名称
* @param expression 触发器 表达式
* @param ruleLevel 告警等级
* @return
*/
@Post
@JsonPath("/trigger/trigger.create")
String triggerCreate(@ParamName("triggerName") String triggerName,
@ParamName("expression") String expression,
@ParamName("ruleLevel") Byte ruleLevel,
@ParamName("type") Integer type);
/**
* 创建场景联动触发器
*
* @param triggerName 触发器名称
* @param expression 触发器 表达式
* @param ruleLevel 告警等级
* @return
*/
@Post
@JsonPath("/trigger/trigger.execute.create")
String executeTriggerCreate(@ParamName("triggerName") String triggerName,
@ParamName("expression") String expression,
@ParamName("ruleLevel") Byte ruleLevel);
/**
* 更新告警触发器
*
* @param triggerId 触发器ID
* @param expression 触发器 表达式
* @param ruleLevel 告警等级
* @return
*/
@Post
@JsonPath("/trigger/trigger.update")
String triggerUpdate(@ParamName("triggerId") String triggerId,
@ParamName("expression") String expression,
@ParamName("ruleLevel") Byte ruleLevel);
/**
* 更新创建 触发器 Tag
*
* @param triggerId 触发器ID
* @param tags 标签
* @return
*/
@Post
@JsonPath("/trigger/trigger.tags.update")
String triggerTagCreate(@ParamName("triggerId") String triggerId,
@ParamName("tagMap") Map<String, String> tags);
/**
* 根据TRIGGER ID查询触发器
*
* @param triggerIds 触发器IDs
*/
@Post
@JsonPath("/trigger/trigger.get")
String triggerGet(@ParamName("triggerIds") String triggerIds);
/**
* 根据TRIGGER ID查询触发器及触发器标签
*
* @param triggerIds 触发器IDs
*/
@Post
@JsonPath("/trigger/triggerAndTags.get")
String triggerAndTagsGet(@ParamName("triggerIds") String triggerIds);
/**
* 根据host 查询触发器
*
* @param host 设备ID
*/
@Post
@JsonPath("/trigger/trigger.get")
String triggerGetByHost(@ParamName("host") String host);
/**
* 根据触发器名称 查询触发器
*
* @param description 触发器名称
*/
@Post
@JsonPath("/trigger/trigger.get")
String triggerGetByName(@ParamName("description") String description);
/**
* 修改触发器状态
*
* @param triggerId
* @param status
* @return
*/
@Post
@JsonPath("/trigger/trigger.status.update")
String triggerStatusUpdate(@ParamName("triggerid") String triggerId,
@ParamName("status") String status);
/**
* 修改触发器状态
*
* @param triggerId
* @return
*/
@Post
@JsonPath("/trigger/trigger.delete")
String triggerDelete(@ParamName("triggerid") String triggerId);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxTrigger.java
|
Java
|
gpl-3.0
| 3,682
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* @author nantian created at 2021/8/2 13:09
* <p>
* ZABBIX User 接口
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxUser {
/**
* 用户登录
*
* @param username 用户名
* @param password 密码
* @return 登录返回的状态信息
*/
@Post(headers = "authTag: noAuth")
@JsonPath("/user/userLogin")
String userLogin(@ParamName("username") String username,
@ParamName("password") String password);
/**
* 用户创建
*
* @param name 账号
* @param password 密码
* @param usrGrpId 用户组ID
* @return 用户信息
*/
@Post
@JsonPath("/user/userAdd")
String userAdd(@ParamName("name") String name,
@ParamName("password") String password,
@ParamName("usrGrpId") String usrGrpId,
@ParamName("roleId") String roleId);
/**
* 用户修改
*
* @param userId 用户id
* @param usrGrpId 用户组ID
* @return 用户信息
*/
@Post
@JsonPath("/user/userUpdate")
String userUpdate(@ParamName("userId") String userId,
@ParamName("usrGrpId") String usrGrpId,
@ParamName("roleId") String roleId);
/**
* 用户删除
*
* @param usrids 用户id
* @return 用户信息
*/
@Post
@JsonPath("/user/userDelete")
String userDelete(@ParamName("usrids") List<String> usrids);
/**
* 用户修改密码
*
* @param userId 用户id
* @param passwd 用户组ID
* @return 用户信息
*/
@Post
@JsonPath("/user/userUpdatePwd")
String updatePwd(@ParamName("userId") String userId, @ParamName("passwd") String passwd);
/**
* 用户查询
*
* @return
*/
@Post
@JsonPath("/user/userGet")
String getUser(@ParamName("userids") String userIds);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxUser.java
|
Java
|
gpl-3.0
| 2,368
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.List;
/**
* @author nantian created at 2021/8/2 13:09
* <p>
* ZABBIX UserGrp 接口
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxUserGroup {
/**
* 用户组创建
*
* @param userGroupName 名称
* @return 用户组信息
*/
@Post
@JsonPath("/usergroup/userGroupCreate")
String userGrpAdd(@ParamName("userGroupName") String userGroupName);
/**
* 用户组删除
*
* @param usrGrpIds 用户组id
*/
@Post
@JsonPath("/usergroup/userGroupDelete")
String userGrpDelete(@ParamName("usrgrpids") List<String> usrGrpIds);
/**
* 用户组绑定主机组
*
* @param hostGroupIds 主机组IDs 修改和删除 都是这个方法
* @param userGroupId 用户组ID
* @return
*/
@Post
@JsonPath("/usergroup/userGroupBindHostGroup")
String userGrpBindHostGroup(@ParamName("hostGroupIds") List<String> hostGroupIds,
@ParamName("userGroupId") String userGroupId);
@Post
@JsonPath("/usergroup/userGroupGet")
String getUserGrp(@ParamName("usrgrpids") String usrgrpids);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxUserGroup.java
|
Java
|
gpl-3.0
| 1,566
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.BaseRequest;
import com.dtflys.forest.annotation.Post;
import com.zmops.zeus.driver.annotation.JsonPath;
import com.zmops.zeus.driver.annotation.ParamName;
import com.zmops.zeus.driver.inteceptor.JsonBodyBuildInterceptor;
import java.util.Map;
/**
* @author nantian created at 2021/8/4 15:04
* <p>
* 值映射设置
*/
@BaseRequest(
baseURL = "http://${zbxServerIp}:${zbxServerPort}${zbxApiUrl}",
interceptor = JsonBodyBuildInterceptor.class
)
public interface ZbxValueMap {
/**
* 创建值映射
*
* @param hostId 主机ID
* @param valueMapName 值映射名称
* @param valMaps 值映射 翻译map
* @return
*/
@Post
@JsonPath("/valuemap/valuemap.create")
String valueMapCreate(@ParamName("hostId") String hostId,
@ParamName("valueMapName") String valueMapName,
@ParamName("valMaps") Map<String, String> valMaps);
/**
* 删除值映射
*
* @param valueMapId 值映射ID
* @return String
*/
@Post
@JsonPath("/valuemap/valuemap.delete")
String valueMapDelete(@ParamName("valueMapId") String valueMapId);
/**
* 修改值映射
*
* @param hostId 主机ID
* @param valueMapName 值映射名称
* @param valMaps 值映射 翻译map
* @param valueMapId 值映射ID
* @return
*/
@Post
@JsonPath("/valuemap/valuemap.update")
String valueMapUpdate(@ParamName("hostId") String hostId,
@ParamName("valueMapName") String valueMapName,
@ParamName("valMaps") Map<String, String> valMaps,
@ParamName("valueMapId") String valueMapId);
/**
* 删除值映射
*
* @param valuemapids 值映射ID
* @return String
*/
@Post
@JsonPath("/valuemap/valuemap.get")
String valueMapGet(@ParamName("valuemapids") String valuemapids);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZbxValueMap.java
|
Java
|
gpl-3.0
| 2,052
|
package com.zmops.zeus.driver.service;
import com.dtflys.forest.annotation.DataFile;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Var;
import com.dtflys.forest.callback.OnProgress;
import org.springframework.web.multipart.MultipartFile;
/**
* @author yefei
**/
public interface ZeusServer {
/**
* 上传 协议包
*
* @param ip 服务器IP
* @param file 文件
* @param onProgress 进度处理
* @return map
*/
@Post(url = "http://${ip}:12800/protocol/component/upload")
void upload(@Var("ip") String ip, @DataFile("file") MultipartFile file, OnProgress onProgress);
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/java/com/zmops/zeus/driver/service/ZeusServer.java
|
Java
|
gpl-3.0
| 668
|
{
"jsonrpc": "2.0",
"method": "action.create",
"params": {
"name": "${name}",
"eventsource": 0,
"status": 0,
"esc_period": "2m",
"filter": {
"evaltype": 0,
"conditions": [
{
"conditiontype": 25,
"operator": 0,
"value": "${tagName}"
}
]
},
"operations": [
{
"operationtype": 1,
"opcommand_hst": [
{
"hostid": "0"
}
],
"opcommand": {
"scriptid": "${scriptId}"
}
}
]
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/action/action.create.ftl
|
Fluent
|
gpl-3.0
| 799
|
{
"jsonrpc": "2.0",
"method": "action.create",
"params": {
"name": "${name}",
"eventsource": 0,
"status": 0,
"esc_period": "2m",
"filter": {
"evaltype": 0,
"conditions": [
{
"conditiontype": 25,
"operator": 0,
"value": "${tagName}"
}
]
},
"operations": [
{
"operationtype": 1,
"opcommand_hst": [
{
"hostid": "0"
}
],
"opcommand": {
"scriptid": "${scriptId}"
}
}
],
"recovery_operations": [
{
"operationtype": "1",
"opcommand_hst": [
{
"hostid": "0"
}
],
"opcommand": {
"scriptid": "${scriptId}"
}
}
]
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/action/action.init.create.ftl
|
Fluent
|
gpl-3.0
| 1,144
|
{
"jsonrpc": "2.0",
"method": "action.get",
"params": {
"output": [
"actionid"
],
"search": {
"name": "${name}"
}
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/action/action.offline.get.ftl
|
Fluent
|
gpl-3.0
| 229
|
{
"jsonrpc": "2.0",
"method": "apiinfo.version",
"params": [],
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/apiinfo/apiinfo.ftl
|
Fluent
|
gpl-3.0
| 88
|
{
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": ${valueType},
<#if hostid??>
"hostids": "${hostid}",
</#if>
<#if itemids??>
"itemids": [
<#list itemids as itemid>
${itemid}<#if itemid_has_next>,</#if>
</#list>
],
</#if>
<#if timeFrom??>
"time_from":${timeFrom},
</#if>
<#if timeTill??>
"time_till":${timeTill},
</#if>
"sortfield": "clock",
"sortorder": "DESC",
"limit": ${hisNum}
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/history/history.get.ftl
|
Fluent
|
gpl-3.0
| 683
|
{
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "${hostName}",
<#if interfaces??>
"interfaces": [
{
"type": ${interfaces.type},
"main": ${interfaces.main},
"useip": ${interfaces.useip},
"ip": "${interfaces.ip}",
"dns": "",
"port": "${interfaces.port}"
}
],
</#if>
<#if proxyid??>
"proxy_hostid":"${proxyid}",
</#if>
"groups": [
<#if groupids??>
<#list groupids as groupid>
{ "groupid": "${groupid}" }<#if groupid_has_next>,</#if>
</#list>
</#if>
],
"templates": [
{
"templateid": "${templateid}"
}
]
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.create.ftl
|
Fluent
|
gpl-3.0
| 908
|
{
"jsonrpc": "2.0",
"method": "host.delete",
"params": [
<#if hostIds??>
<#list hostIds as hostId>
"${hostId}"<#if hostId_has_next>,</#if>
</#list>
</#if>
],
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.delete.ftl
|
Fluent
|
gpl-3.0
| 270
|
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
<#if host??>
"filter": {
"host": "${host}"
},
</#if>
<#if hostid??>
"hostids": "${hostid}",
</#if>
"output": "extend",
"selectTags":"extend",
"selectMacros":"extend",
"selectValueMaps":"extend",
"selectInterface":"extend"
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.get.ftl
|
Fluent
|
gpl-3.0
| 443
|
{
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": "${hostId}",
"macros": [
<#if macros??>
<#list macros as macro>
{
"macro": "${macro.key}",
"value": "${macro.value}",
"description": "${macro.desc}"
}<#if macro_has_next>,</#if>
</#list>
</#if>
]
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.macro.update.ftl
|
Fluent
|
gpl-3.0
| 514
|
{
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid":"${hostid}",
"status":"${status}"
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.status.update.ftl
|
Fluent
|
gpl-3.0
| 175
|
{
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid":"${hostId}",
"tags": [
<#if tagMap??>
<#list tagMap? keys as key>
{
"tag": "${key}",
"value": "${tagMap[key]}"
}<#if key_has_next>,</#if>
</#list>
</#if>
]
},
"auth": "${userAuth}",
"id": 1
}
|
2301_81045437/zeus-iot
|
zeus-driver/src/main/resources/api-json/host/host.tag.update.ftl
|
Fluent
|
gpl-3.0
| 441
|