diff --git a/README.md b/README.md index 7d7a6b8..a16d827 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,6 @@ +<<<<<<< HEAD +# stand_lms +======= # nl_platform +>>>>>>> 9f65e6a27463ef0ec964119aae4c663aba274482 diff --git a/nladmin-system/.gitignore b/nladmin-system/.gitignore index 54ef48a..8c1a75b 100644 --- a/nladmin-system/.gitignore +++ b/nladmin-system/.gitignore @@ -7,5 +7,3 @@ /.gradle/ /target/* */application-dev.yml -nlsso-server/src/main/java/org/nl/common/constant/ -nlsso-server/src/main/java/org/nl/common/core/ diff --git a/nladmin-system/doc/sch2.xls b/nladmin-system/doc/sch2.xls deleted file mode 100644 index 4085eed..0000000 Binary files a/nladmin-system/doc/sch2.xls and /dev/null differ diff --git a/nladmin-system/doc/wms.xls b/nladmin-system/doc/wms.xls new file mode 100644 index 0000000..b03532e Binary files /dev/null and b/nladmin-system/doc/wms.xls differ diff --git a/nladmin-system/nlsso-server/pom.xml b/nladmin-system/nlsso-server/pom.xml index c464c5c..599d93a 100644 --- a/nladmin-system/nlsso-server/pom.xml +++ b/nladmin-system/nlsso-server/pom.xml @@ -24,122 +24,17 @@ 2.5.0 1.3.1.Final 1.31.0 - 5.8.1 + 5.7.14 0.11.1 - 5.8.0 + 5.9.0 + 8.2.0 1.9 - 4.1.59.Final - - - p6spy - p6spy - 3.8.6 - - - - - com.yomahub - tlog-all-spring-boot-starter - 1.5.0 - - - - - - org.springframework.boot - spring-boot-starter-data-elasticsearch - 2.7.5 - - - - - com.internetitem - logback-elasticsearch-appender - 1.6 - - - - - org.fusesource.jansi - jansi - 1.9 - - - - - cn.dynamictp - dynamic-tp-spring-boot-starter-common - 1.0.9 - - - cn.dynamictp - dynamic-tp-spring-boot-starter-adapter-webserver - 1.0.9 - - - - org.springframework.boot - spring-boot-starter-actuator - - - - io.netty - netty-common - ${netty.version} - - - io.netty - netty-buffer - ${netty.version} - - - io.netty - netty-handler - ${netty.version} - - - io.netty - netty-transport - ${netty.version} - - - io.netty - netty-codec-http - ${netty.version} - - - - com.taobao.arthas - arthas-spring-boot-starter - 3.5.4 - - - - org.flywaydb - flyway-core - - - com.github.pagehelper - pagehelper-spring-boot-starter - 1.2.12 - - - org.mybatis - mybatis - - - - - org.redisson - redisson-spring-boot-starter - 3.19.1 - cn.hutool @@ -187,8 +82,11 @@ mybatis-plus-generator 3.4.0 - - + + + + + cn.dev33 @@ -286,7 +184,7 @@ mysql mysql-connector-java - 8.0.20 + runtime @@ -404,14 +302,6 @@ 1.9.2 - - - - org.springframework.retry - spring-retry - - - org.springframework.boot @@ -441,15 +331,8 @@ com.alicp.jetcache jetcache-starter-redis 2.5.14 - - - com.esotericsoftware - kryo - - - com.oracle.database.jdbc ojdbc5 @@ -504,7 +387,7 @@ com.github.oshi oshi-core - 6.1.4 + 5.0.1 @@ -522,6 +405,48 @@ jakarta.persistence-api 2.2.3 + + + commons-io + commons-io + 2.8.0 + + + + + org.apache.lucene + lucene-core + ${lucene.version} + + + org.apache.lucene + lucene-highlighter + ${lucene.version} + + + org.apache.lucene + lucene-analyzers-common + ${lucene.version} + + + com.github.magese + ik-analyzer + ${lucene.version} + + + + + org.apache.lucene + lucene-analyzers-smartcn + ${lucene.version} + + + + org.apache.lucene + lucene-queryparser + ${lucene.version} + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/AppRun.java b/nladmin-system/nlsso-server/src/main/java/org/nl/AppRun.java index 14cca84..9f17133 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/AppRun.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/AppRun.java @@ -4,16 +4,18 @@ import cn.dev33.satoken.annotation.SaIgnore; import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation; import com.alicp.jetcache.anno.config.EnableMethodCache; import io.swagger.annotations.Api; -import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; -import org.nl.common.utils.SpringContextHolder; +import org.nl.common.mnt.websocket.WebSocketServer; +import org.nl.config.SpringContextHolder; +import org.nl.system.service.notice.ISysNoticeService; +import org.nl.system.service.notice.impl.SysNoticeServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; -import org.springframework.retry.annotation.EnableRetry; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.bind.annotation.GetMapping; @@ -30,20 +32,20 @@ import org.springframework.web.bind.annotation.RestController; @RestController @Api(hidden = true) @SpringBootApplication(exclude = { - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class, - org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration.class + org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class }) @ServletComponentScan //https://blog.csdn.net/qq_36850813/article/details/101194250 @EnableTransactionManagement @EnableMethodCache(basePackages = "org.nl") @EnableCreateCacheAnnotation @MapperScan("org.nl.**.mapper") -@EnableRetry //https://juejin.cn/post/7094613787973517343 - -@Slf4j public class AppRun { + @Autowired + private ISysNoticeService noticeService; + public static void main(String[] args) { + SpringApplication.run(AppRun.class, args); } @@ -67,7 +69,6 @@ public class AppRun { @GetMapping("/") @SaIgnore public String index() { - log.info("123"); return "Backend service started successfully"; } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/InterfaceLogType.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/InterfaceLogType.java deleted file mode 100644 index cfada7f..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/InterfaceLogType.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.nl.common.annotation; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年02月07日 10:27 - * @desc desc - */ -public enum InterfaceLogType { - DEFAULT("默认"), - LMS_TO_MES("LMS请求MES"), - MES_TO_LMS("MES请求LMS"), - LMS_TO_CRM("LMS请求CRM"), - CRM_TO_LMS("CRM请求LMS"), - LMS_TO_SAP("LMS请求SAP"), - SAP_TO_LMS("SAP请求LMS"), - LMS_TO_ACS("LMS请求ACS"), - ACS_TO_LMS("ACS请求LMS"); - - private String desc; - - InterfaceLogType(String desc) { - this.desc=desc; - } - - public String getDesc() { - return desc; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/MethodConstants.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/MethodConstants.java deleted file mode 100755 index 7c66983..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/MethodConstants.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.nl.common.arthas; - -/** - * tunnel client和server之间通过 URI来通迅,在URI里定义了一个 method的参数,定义不同的行为 - * - * @author hengyunabc 2020-10-22 - * - */ -public class MethodConstants { - - /** - * - *
-     * tunnel client启动时注册的 method
-     *
-     * ws://192.168.1.10:7777/ws?method=agentRegister
-     *
-     * tunnel server回应:
-     *
-     * response:/?method=agentRegister&id=bvDOe8XbTM2pQWjF4cfw
-     *
-     * id不指定,则随机生成
-     * 
- */ - public static final String AGENT_REGISTER = "agentRegister"; - - /** - *
-     * tunnel server 通知 tunnel client启动一个新的连接
-     *
-     * response:/?method=startTunnel&id=bvDOe8XbTM2pQWjF4cfw&clientConnectionId=AMku9EFz2gxeL2gedGOC
-     * 
- */ - public static final String START_TUNNEL = "startTunnel"; - /** - *
-     * browser 通知tunnel server去连接 tunnel client
-     *
-     * ws://192.168.1.10:7777/ws?method=connectArthas&id=bvDOe8XbTM2pQWjF4cfw
-     * 
- */ - public static final String CONNECT_ARTHAS = "connectArthas"; - - /** - *
-     * tunnel client收到 startTunnel 指令之后,以下面的 URI新建一个连接:
-     *
-     * ws://127.0.0.1:7777/ws/?method=openTunnel&clientConnectionId=AMku9EFz2gxeL2gedGOC&id=bvDOe8XbTM2pQWjF4cfw
-     * 
- */ - public static final String OPEN_TUNNEL = "openTunnel"; - - /** - *
-     * tunnel server向 tunnel client请求 http中转,比如访问 http://localhost:3658/arthas-output/xxx.svg
-     * 
- */ - public static final String HTTP_PROXY = "httpProxy"; - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/SimpleHttpResponse.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/SimpleHttpResponse.java deleted file mode 100755 index dced2d8..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/SimpleHttpResponse.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.nl.common.arthas; - -import java.io.*; -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author hengyunabc 2020-10-22 - * - */ -public class SimpleHttpResponse implements Serializable { - - private static final long serialVersionUID = 1L; - - private int status = 200; - - private Map headers = new HashMap(); - - private byte[] content; - - public void addHeader(String key, String value) { - headers.put(key, value); - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public static byte[] toBytes(SimpleHttpResponse response) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream out = null; - try { - out = new ObjectOutputStream(bos); - out.writeObject(response); - out.flush(); - return bos.toByteArray(); - } finally { - try { - bos.close(); - } catch (IOException ex) { - // ignore close exception - } - } - } - - public static SimpleHttpResponse fromBytes(byte[] bytes) throws IOException, ClassNotFoundException { - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - ObjectInput in = null; - try { - in = new ObjectInputStream(bis); - return (SimpleHttpResponse) in.readObject(); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ex) { - // ignore close exception - } - } - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/URIConstans.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/URIConstans.java deleted file mode 100755 index 4c74963..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/arthas/URIConstans.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.nl.common.arthas; - -/** - * - * @author hengyunabc 2020-10-22 - * - */ -public class URIConstans { - - /** - * @see MethodConstants - */ - public static final String METHOD = "method"; - public static final String RESPONSE = "response"; - - /** - * agent id - */ - public static final String ID = "id"; - - /** - * tunnel server用于区分不同 tunnel client的内部 id - */ - public static final String CLIENT_CONNECTION_ID = "clientConnectionId"; - - /** - * tunnel server向 tunnel client请求http代理时的目标 url - * - */ - public static final String TARGET_URL = "targetUrl"; - - /** - * 标识一次proxy请求,随机生成 - */ - public static final String PROXY_REQUEST_ID = "requestId"; - - /** - * proxy请求的返回值,base64编码 - */ - public static final String PROXY_RESPONSE_DATA = "responseData"; - - public static final String ARTHAS_VERSION = "arthasVersion"; - - public static final String APP_NAME = "appName"; -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LimitAspect.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LimitAspect.java index 25d0cdf..a669c5e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LimitAspect.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LimitAspect.java @@ -23,22 +23,19 @@ import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; - -import org.nl.common.aspect.exception.BadRequestException; -import org.nl.common.utils.InetAddUtil; +import org.nl.common.annotation.Limit; +import org.nl.common.exception.BadRequestException; +import org.nl.common.utils.RequestHolder; +import org.nl.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; -import java.util.Objects; -import org.nl.common.annotation.Limit; /** * @author / @@ -61,7 +58,7 @@ public class LimitAspect { @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { - HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + HttpServletRequest request = RequestHolder.getHttpServletRequest(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method signatureMethod = signature.getMethod(); Limit limit = signatureMethod.getAnnotation(Limit.class); @@ -69,7 +66,7 @@ public class LimitAspect { String key = limit.key(); if (StrUtil.isEmpty(key)) { if (limitType == LimitType.IP) { - key = InetAddUtil.getIp(request); + key = StringUtils.getIp(request); } else { key = signatureMethod.getName(); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseDTO.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseDTO.java new file mode 100644 index 0000000..7920b7c --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseDTO.java @@ -0,0 +1,33 @@ +package org.nl.common.base; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author Zheng Jie + * @date 2019年10月24日20:48:53 + */ +@Data +public class BaseDTO implements Serializable { + + private String create_name; + + private String create_id; + + private String update_name; + + private String update_id; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date create_time; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date update_time; + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/OnlineUserDto.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseMapper.java similarity index 52% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/OnlineUserDto.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseMapper.java index c1e93e0..c1b43a0 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/OnlineUserDto.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/BaseMapper.java @@ -13,62 +13,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.secutiry.dto; +package org.nl.common.base; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.Date; +import java.util.List; /** - * 在线用户 * @author Zheng Jie + * @date 2018-11-23 */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class OnlineUserDto { +public interface BaseMapper { /** - * 用户名 + * DTO转Entity + * @param dto / + * @return / */ - private String userName; + E toEntity(D dto); /** - * 昵称 + * Entity转DTO + * @param entity / + * @return / */ - private String nickName; + D toDto(E entity); /** - * 岗位 + * DTO集合转Entity集合 + * @param dtoList / + * @return / */ - private String dept; + List toEntity(List dtoList); /** - * 浏览器 + * Entity集合转DTO集合 + * @param entityList / + * @return / */ - private String browser; - - /** - * IP - */ - private String ip; - - /** - * 地址 - */ - private String address; - - /** - * token - */ - private String key; - - /** - * 登录时间 - */ - private Date loginTime; - - + List toDto(List entityList); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/TableDataInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/TableDataInfo.java similarity index 98% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/TableDataInfo.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/base/TableDataInfo.java index 8c70be2..a05a05a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/TableDataInfo.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/base/TableDataInfo.java @@ -1,4 +1,4 @@ -package org.nl.common.domain; +package org.nl.common.base; import cn.hutool.http.HttpStatus; import com.baomidou.mybatisplus.core.metadata.IPage; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/BaseDTO.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/BaseDTO.java deleted file mode 100644 index 7cff88e..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/BaseDTO.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.nl.common.domain; - -import com.fasterxml.jackson.annotation.JsonFormat; -import lombok.Getter; -import lombok.Setter; - -import java.io.Serializable; -import java.util.Date; - -/** - * @author Zheng Jie - * @date 2019年10月24日20:48:53 - */ -@Getter -@Setter -public class BaseDTO implements Serializable { - - private String createBy; - - private String updatedBy; - - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; - - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date updateTime; -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/query/BaseQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/query/BaseQuery.java index cc50708..71ccd84 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/query/BaseQuery.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/query/BaseQuery.java @@ -6,7 +6,7 @@ import com.baomidou.mybatisplus.core.toolkit.LambdaUtils; import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache; import lombok.Data; import org.nl.common.enums.QueryTEnum; -import org.nl.common.utils.MapOf; +import org.nl.config.MapOf; import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl; import java.lang.reflect.Type; @@ -27,12 +27,12 @@ public class BaseQuery { /** * 是否启用 */ - private Boolean isUsed; + private Boolean is_used; /** * 创建时间范围查询 */ - private Date startTime; - private Date endTime; + private Date start_time; + private Date end_time; /** diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptVo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/DeptVo.java similarity index 76% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptVo.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/DeptVo.java index 0b25984..62d400b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptVo.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/DeptVo.java @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.dept.dto; +package org.nl.common.domain.vo; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; -import org.nl.common.domain.BaseDTO; +import org.nl.common.base.BaseDTO; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @@ -34,15 +34,15 @@ import java.util.List; public class DeptVo extends BaseDTO implements Serializable { - private String deptId; + private String dept_id; private String code; - private String extId; + private String ext_id; @ApiModelProperty(value = "排序") - private Integer deptSort; + private Integer dept_sort; @NotBlank @@ -51,22 +51,22 @@ public class DeptVo extends BaseDTO implements Serializable { @NotNull @ApiModelProperty(value = "是否启用") - private Boolean isUsed; + private Boolean is_used; @ApiModelProperty(value = "上级部门") private Long pid; @ApiModelProperty(value = "子节点数目", hidden = true) - private Integer subCount = 0; + private Integer sub_count = 0; //前端显示 - private Boolean hasChildren =Boolean.FALSE; + private Boolean has_children =Boolean.FALSE; private List children; - public void setSubCount(Integer subCount) { - this.subCount = subCount; - if (subCount>0){ - this.hasChildren=Boolean.TRUE; + public void setSub_count(Integer sub_count) { + this.sub_count = sub_count; + if (sub_count >0){ + this.has_children =Boolean.TRUE; } } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuMetaVo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuMetaVo.java similarity index 95% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuMetaVo.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuMetaVo.java index b2338b5..e5b22a0 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuMetaVo.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuMetaVo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.menu.dto; +package org.nl.common.domain.vo; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuVo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuVo.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuVo.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuVo.java index c086365..07cb902 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuVo.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/MenuVo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.menu.dto; +package org.nl.common.domain.vo; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/RoleVo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/RoleVo.java new file mode 100644 index 0000000..88cb9d1 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/RoleVo.java @@ -0,0 +1,54 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * 角色 + * @author Zheng Jie + * @date 2018-11-22 + */ +@Getter +@Setter +public class RoleVo implements Serializable { + + + @ApiModelProperty(value = "ID", hidden = true) + private Long role_id; + + @NotBlank + @ApiModelProperty(value = "名称", hidden = true) + private String name; + + @ApiModelProperty(value = "级别,数值越小,级别越大") + private Integer level = 3; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty(value = "描述") + private String order_seq; + + @ApiModelProperty(value = "描述") + private String is_used; + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/UserPassVo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/UserPassVo.java new file mode 100644 index 0000000..6420b97 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/vo/UserPassVo.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.domain.vo; + +import lombok.Data; + +/** + * 修改密码的 Vo 类 + * @author Zheng Jie + * @date 2019年7月11日13:59:49 + */ +@Data +public class UserPassVo { + + private String oldPass; + + private String newPass; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeBiEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeBiEnum.java new file mode 100644 index 0000000..9dcdd2b --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeBiEnum.java @@ -0,0 +1,50 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + *

+ * 验证码业务场景 + *

+ * @author Zheng Jie + * @date 2020-05-02 + */ +@Getter +@AllArgsConstructor +public enum CodeBiEnum { + + /* 旧邮箱修改邮箱 */ + ONE(1, "旧邮箱修改邮箱"), + + /* 通过邮箱修改密码 */ + TWO(2, "通过邮箱修改密码"); + + private final Integer code; + private final String description; + + public static CodeBiEnum find(Integer code) { + for (CodeBiEnum value : CodeBiEnum.values()) { + if (code.equals(value.getCode())) { + return value; + } + } + return null; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeEnum.java new file mode 100644 index 0000000..d5dc14e --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/CodeEnum.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + *

+ * 验证码业务场景对应的 Redis 中的 key + *

+ * @author Zheng Jie + * @date 2020-05-02 + */ +@Getter +@AllArgsConstructor +public enum CodeEnum { + + /* 通过手机号码重置邮箱 */ + PHONE_RESET_EMAIL_CODE("phone_reset_email_code_", "通过手机号码重置邮箱"), + + /* 通过旧邮箱重置邮箱 */ + EMAIL_RESET_EMAIL_CODE("email_reset_email_code_", "通过旧邮箱重置邮箱"), + + /* 通过手机号码重置密码 */ + PHONE_RESET_PWD_CODE("phone_reset_pwd_code_", "通过手机号码重置密码"), + + /* 通过邮箱重置密码 */ + EMAIL_RESET_PWD_CODE("email_reset_pwd_code_", "通过邮箱重置密码"); + + private final String key; + private final String description; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/DataScopeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/DataScopeEnum.java new file mode 100644 index 0000000..71213ba --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/DataScopeEnum.java @@ -0,0 +1,53 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + *

+ * 数据权限枚举 + *

+ * @author Zheng Jie + * @date 2020-05-07 + */ +@Getter +@AllArgsConstructor +public enum DataScopeEnum { + + /* 全部的数据权限 */ + ALL("全部", "全部的数据权限"), + + /* 自己部门的数据权限 */ + THIS_LEVEL("本级", "自己部门的数据权限"), + + /* 自定义的数据权限 */ + CUSTOMIZE("自定义", "自定义的数据权限"); + + private final String value; + private final String description; + + public static DataScopeEnum find(String val) { + for (DataScopeEnum dataScopeEnum : DataScopeEnum.values()) { + if (val.equals(dataScopeEnum.getValue())) { + return dataScopeEnum; + } + } + return null; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/LogTypeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/LogTypeEnum.java new file mode 100644 index 0000000..112429a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/LogTypeEnum.java @@ -0,0 +1,15 @@ +package org.nl.common.enums; + +public enum LogTypeEnum { + DEVICE_LOG("设备日志"), + INTERFACE_LOG("接口日志"); + + private String desc; + + LogTypeEnum(String desc) { + this.desc = desc; + } + public String getDesc() { + return desc; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/NoticeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/NoticeEnum.java new file mode 100644 index 0000000..4e6be7b --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/NoticeEnum.java @@ -0,0 +1,22 @@ +package org.nl.common.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * @Author: lyd + * @Description: + * @Date: 2023/5/9 + */ +@Getter +@AllArgsConstructor +public enum NoticeEnum { + HAVE_READ_OFF("1","未读"), + HAVE_READ_ON("2", "已读"), + DEAL_STATUS_NO("1", "未处理"), + DEAL_STATUS_YES("2", "已处理"), + DEAL_STATUS_NO_NEED("3", "无需处理"); + + private final String value; + private final String desc; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/RequestMethodEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/RequestMethodEnum.java new file mode 100644 index 0000000..0ba462c --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/enums/RequestMethodEnum.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * @author Zheng Jie + * @website https://el-admin.vip + * @description + * @date 2020-06-10 + **/ +@Getter +@AllArgsConstructor +public enum RequestMethodEnum { + + /** + * 搜寻 @AnonymousGetMapping + */ + GET("GET"), + + /** + * 搜寻 @AnonymousPostMapping + */ + POST("POST"), + + /** + * 搜寻 @AnonymousPutMapping + */ + PUT("PUT"), + + /** + * 搜寻 @AnonymousPatchMapping + */ + PATCH("PATCH"), + + /** + * 搜寻 @AnonymousDeleteMapping + */ + DELETE("DELETE"), + + /** + * 否则就是所有 Request 接口都放行 + */ + ALL("All"); + + /** + * Request 类型 + */ + private final String type; + + public static RequestMethodEnum find(String type) { + for (RequestMethodEnum value : RequestMethodEnum.values()) { + if (type.equals(value.getType())) { + return value; + } + } + return ALL; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadConfigurationException.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadConfigurationException.java similarity index 98% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadConfigurationException.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadConfigurationException.java index 1bbe462..c8bda76 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadConfigurationException.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadConfigurationException.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception; +package org.nl.common.exception; /** * 统一关于错误配置信息 异常 diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadRequestException.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadRequestException.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadRequestException.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadRequestException.java index 3ef6a3c..ce1a3f3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/BadRequestException.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/BadRequestException.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception; +package org.nl.common.exception; import lombok.Getter; import org.springframework.http.HttpStatus; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityExistException.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityExistException.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityExistException.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityExistException.java index 6a8d6cc..e73e764 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityExistException.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityExistException.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception; +package org.nl.common.exception; import org.springframework.util.StringUtils; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityNotFoundException.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityNotFoundException.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityNotFoundException.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityNotFoundException.java index e85b26d..3918eb9 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/EntityNotFoundException.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/EntityNotFoundException.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception; +package org.nl.common.exception; import org.springframework.util.StringUtils; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/ApiError.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/ApiError.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/ApiError.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/ApiError.java index 222f98c..c596d1d 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/ApiError.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/ApiError.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception.handler; +package org.nl.common.exception.handler; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/GlobalExceptionHandler.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/GlobalExceptionHandler.java similarity index 94% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/GlobalExceptionHandler.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/GlobalExceptionHandler.java index 03775b8..9e3bbc5 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/exception/handler/GlobalExceptionHandler.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/exception/handler/GlobalExceptionHandler.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.aspect.exception.handler; +package org.nl.common.exception.handler; import cn.dev33.satoken.exception.NotLoginException; import lombok.extern.slf4j.Slf4j; -import org.nl.common.aspect.exception.BadRequestException; -import org.nl.common.aspect.exception.EntityExistException; -import org.nl.common.aspect.exception.EntityNotFoundException; +import org.nl.common.exception.BadRequestException; +import org.nl.common.exception.EntityExistException; +import org.nl.common.exception.EntityNotFoundException; import org.nl.common.utils.ThrowableUtil; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/Log.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/annotation/Log.java similarity index 64% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/Log.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/annotation/Log.java index 2794c2c..4d8105b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/annotation/Log.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/annotation/Log.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.annotation; +package org.nl.common.logging.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -28,34 +28,4 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) public @interface Log { String value() default ""; - - /** - * 是否打印到日志文件 - * - * @return - */ - boolean isPrintToLogFile() default false; - - - /** - * 是否插入操作日志表 - * - * @return - */ - boolean isAddLogTable() default true; - - /** - * 是否接口日志 - * - * @return - */ - boolean isInterfaceLog() default false; - - /** - * 接口日志类型 - * - * @return - */ - InterfaceLogType interfaceLogType() default InterfaceLogType.DEFAULT; } - diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LogAspect.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/aspect/LogAspect.java similarity index 62% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LogAspect.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/aspect/LogAspect.java index dae0b4c..297b3dd 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/aspect/LogAspect.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/aspect/LogAspect.java @@ -12,83 +12,109 @@ * 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 org.nl.common.aspect; + *//* + +package org.nl.common.logging.aspect; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; +import org.nl.common.utils.RequestHolder; import org.nl.common.utils.SecurityUtils; +import org.nl.common.utils.StringUtils; +import org.nl.common.utils.ThrowableUtil; +import org.nl.common.logging.domain.Log; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; +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.lang.reflect.Method; import java.lang.reflect.Parameter; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +*/ /** * @author Zheng Jie * @date 2018-11-24 - */ + *//* + @Component @Aspect @Slf4j public class LogAspect { + private final LogService logService; ThreadLocal currentTime = new ThreadLocal<>(); + public LogAspect(LogService logService) { + this.logService = logService; + } - /** + */ +/** * 配置切入点 - */ - @Pointcut("@annotation(org.nl.common.annotation.Log)") + *//* + + @Pointcut("@annotation(org.nl.common.logging.annotation.Log)") public void logPointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } - /** + */ +/** * 配置环绕通知,使用在方法logPointcut()上注册的切入点 * * @param joinPoint join point for advice - */ + *//* + @Around("logPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { - String trackId = UUID.randomUUID().toString(); + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + HttpServletResponse response = attributes.getResponse(); +// HttpServletRequest request = RequestHolder.getHttpServletRequest(); + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); // 方法路径 String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()"; - String params = getParameter(method, joinPoint.getArgs()); + String params=getParameter(method, joinPoint.getArgs()); - org.nl.common.annotation.Log logInfo = method.getAnnotation(org.nl.common.annotation.Log.class); + log.info("请求uri:{}", request.getRequestURI()); + log.info("请求方法:{}",methodName); + log.info("请求方法参数:{}",params); - //是否输出到日志文件 - if (logInfo.isPrintToLogFile()) { - log.info("track_id:{},请求方法:{},请求方法参数:{}",trackId,methodName,params); - } Object result; currentTime.set(System.currentTimeMillis()); - try { - result = joinPoint.proceed(); -// log.info("返回结果:"+JSONObject.parse(((ResponseEntity) result).getBody().toString())); - }catch (Exception ex){ - log.error("track_id:{},error:{}",trackId,ex.getMessage()); - throw ex; - } + result = joinPoint.proceed(); + Log log = new Log("INFO",System.currentTimeMillis() - currentTime.get()); + currentTime.remove(); + + logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, log); return result; } - /** + */ +/** * 根据方法和传入的参数获取请求参数 - */ + *//* + private String getParameter(Method method, Object[] args) { List argList = new ArrayList<>(); Parameter[] parameters = method.getParameters(); @@ -116,22 +142,29 @@ public class LogAspect { return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList); } - /** + */ +/** * 配置异常通知 * * @param joinPoint join point for advice - * @param e exception - */ -// @AfterThrowing(pointcut = "logPointcut()", throwing = "e") + * @param e exception + *//* + + @AfterThrowing(pointcut = "logPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { -// logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint) joinPoint, log); + Log log = new Log("ERROR",System.currentTimeMillis() - currentTime.get()); + currentTime.remove(); + log.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); + HttpServletRequest request = RequestHolder.getHttpServletRequest(); + logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, log); } public String getUsername() { try { return SecurityUtils.getCurrentUsername(); - } catch (Exception e) { + }catch (Exception e){ return ""; } } } +*/ diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/domain/Log.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/domain/Log.java new file mode 100644 index 0000000..2d9f1c6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/logging/domain/Log.java @@ -0,0 +1,74 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.logging.domain; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serializable; +import java.util.Date; + +/** + * @author Zheng Jie + * @date 2018-11-24 + */ +@Getter +@Setter + +@NoArgsConstructor +public class Log implements Serializable { + private String id; + + /** 操作用户 */ + private String username; + + /** 描述 */ + private String description; + + /** 方法名 */ + private String method; + + /** 参数 */ + private String params; + + /** 日志类型 */ + private String logType; + + /** 请求ip */ + private String requestIp; + + /** 地址 */ + private String address; + + /** 浏览器 */ + private String browser; + + /** 请求耗时 */ + private Long time; + + /** 异常详细 */ + private byte[] exceptionDetail; + + /** 创建日期 */ + private Date createTime; + + public Log(String logType, Long time) { + this.logType = logType; + this.time = time; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/DataTypeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/DataTypeEnum.java new file mode 100644 index 0000000..99ab108 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/DataTypeEnum.java @@ -0,0 +1,140 @@ +/* + * << + * Davinci + * == + * Copyright (C) 2016 - 2019 EDP + * == + * 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 + * http://www.apache.org/licenses/LICENSE-2.0 + * 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 org.nl.common.mnt.util; +import lombok.extern.slf4j.Slf4j; + +/** + * @author / + */ +@Slf4j +@SuppressWarnings({"unchecked","all"}) +public enum DataTypeEnum { + + /** mysql */ + MYSQL("mysql", "mysql", "com.mysql.cj.jdbc.Driver", "`", "`", "'", "'"), + + /** oracle */ + ORACLE("oracle", "oracle", "oracle.jdbc.driver.OracleDriver", "\"", "\"", "\"", "\""), + + /** sql server */ + SQLSERVER("sqlserver", "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "\"", "\"", "\"", "\""), + + /** h2 */ + H2("h2", "h2", "org.h2.Driver", "`", "`", "\"", "\""), + + /** phoenix */ + PHOENIX("phoenix", "hbase phoenix", "org.apache.phoenix.jdbc.PhoenixDriver", "", "", "\"", "\""), + + /** mongo */ + MONGODB("mongo", "mongodb", "mongodb.jdbc.MongoDriver", "`", "`", "\"", "\""), + + /** sql4es */ + ELASTICSEARCH("sql4es", "elasticsearch", "nl.anchormen.sql4es.jdbc.ESDriver", "", "", "'", "'"), + + /** presto */ + PRESTO("presto", "presto", "com.facebook.presto.jdbc.PrestoDriver", "", "", "\"", "\""), + + /** moonbox */ + MOONBOX("moonbox", "moonbox", "moonbox.jdbc.MbDriver", "`", "`", "`", "`"), + + /** cassandra */ + CASSANDRA("cassandra", "cassandra", "com.github.adejanovski.cassandra.jdbc.CassandraDriver", "", "", "'", "'"), + + /** click house */ + CLICKHOUSE("clickhouse", "clickhouse", "ru.yandex.clickhouse.ClickHouseDriver", "", "", "\"", "\""), + + /** kylin */ + KYLIN("kylin", "kylin", "org.apache.kylin.jdbc.Driver", "\"", "\"", "\"", "\""), + + /** vertica */ + VERTICA("vertica", "vertica", "com.vertica.jdbc.Driver", "", "", "'", "'"), + + /** sap */ + HANA("sap", "sap hana", "com.sap.db.jdbc.Driver", "", "", "'", "'"), + + /** impala */ + IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'"); + + private String feature; + private String desc; + private String driver; + private String keywordPrefix; + private String keywordSuffix; + private String aliasPrefix; + private String aliasSuffix; + + private static final String JDBC_URL_PREFIX = "jdbc:"; + + DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) { + this.feature = feature; + this.desc = desc; + this.driver = driver; + this.keywordPrefix = keywordPrefix; + this.keywordSuffix = keywordSuffix; + this.aliasPrefix = aliasPrefix; + this.aliasSuffix = aliasSuffix; + } + + public static DataTypeEnum urlOf(String jdbcUrl) { + String url = jdbcUrl.toLowerCase().trim(); + for (DataTypeEnum dataTypeEnum : values()) { + if (url.startsWith(JDBC_URL_PREFIX + dataTypeEnum.feature)) { + try { + Class aClass = Class.forName(dataTypeEnum.getDriver()); + if (null == aClass) { + throw new RuntimeException("Unable to get driver instance for jdbcUrl: " + jdbcUrl); + } + } catch (ClassNotFoundException e) { + throw new RuntimeException("Unable to get driver instance: " + jdbcUrl); + } + return dataTypeEnum; + } + } + return null; + } + + public String getFeature() { + return feature; + } + + public String getDesc() { + return desc; + } + + public String getDriver() { + return driver; + } + + public String getKeywordPrefix() { + return keywordPrefix; + } + + public String getKeywordSuffix() { + return keywordSuffix; + } + + public String getAliasPrefix() { + return aliasPrefix; + } + + public String getAliasSuffix() { + return aliasSuffix; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ExecuteShellUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ExecuteShellUtil.java new file mode 100644 index 0000000..cf5d26f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ExecuteShellUtil.java @@ -0,0 +1,103 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.util; + +import cn.hutool.core.io.IoUtil; +import com.jcraft.jsch.ChannelShell; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; +import lombok.extern.slf4j.Slf4j; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Vector; + +/** + * 执行shell命令 + * + * @author: ZhangHouYing + * @date: 2019/8/10 + */ +@Slf4j +public class ExecuteShellUtil { + + private Vector stdout; + + Session session; + + public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) { + try { + JSch jsch = new JSch(); + session = jsch.getSession(username, ipAddress, port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(3000); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + + } + + public int execute(final String command) { + int returnCode = 0; + ChannelShell channel = null; + PrintWriter printWriter = null; + BufferedReader input = null; + stdout = new Vector(); + try { + channel = (ChannelShell) session.openChannel("shell"); + channel.connect(); + input = new BufferedReader(new InputStreamReader(channel.getInputStream())); + printWriter = new PrintWriter(channel.getOutputStream()); + printWriter.println(command); + printWriter.println("exit"); + printWriter.flush(); + log.info("The remote command is: "); + String line; + while ((line = input.readLine()) != null) { + stdout.add(line); + System.out.println(line); + } + } catch (Exception e) { + log.error(e.getMessage(),e); + return -1; + }finally { + IoUtil.close(printWriter); + IoUtil.close(input); + if (channel != null) { + channel.disconnect(); + } + } + return returnCode; + } + + public void close(){ + if (session != null) { + session.disconnect(); + } + } + + public String executeForResult(String command) { + execute(command); + StringBuilder sb = new StringBuilder(); + for (String str : stdout) { + sb.append(str); + } + return sb.toString(); + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ScpClientUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ScpClientUtil.java new file mode 100644 index 0000000..0df287d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ScpClientUtil.java @@ -0,0 +1,105 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.util; + +import ch.ethz.ssh2.Connection; +import ch.ethz.ssh2.SCPClient; +import com.google.common.collect.Maps; + +import java.io.IOException; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * 远程执行linux命令 + * @author: ZhangHouYing + * @date: 2019-08-10 10:06 + */ +public class ScpClientUtil { + + static private Map instance = Maps.newHashMap(); + + static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String password) { + if (instance.get(ip) == null) { + instance.put(ip, new ScpClientUtil(ip, port, username, password)); + } + return instance.get(ip); + } + + public ScpClientUtil(String ip, int port, String username, String password) { + this.ip = ip; + this.port = port; + this.username = username; + this.password = password; + } + + public void getFile(String remoteFile, String localTargetDirectory) { + Connection conn = new Connection(ip, port); + try { + conn.connect(); + boolean isAuthenticated = conn.authenticateWithPassword(username, password); + if (!isAuthenticated) { + System.err.println("authentication failed"); + } + SCPClient client = new SCPClient(conn); + client.get(remoteFile, localTargetDirectory); + } catch (IOException ex) { + Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex); + }finally{ + conn.close(); + } + } + + public void putFile(String localFile, String remoteTargetDirectory) { + putFile(localFile, null, remoteTargetDirectory); + } + + public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) { + putFile(localFile, remoteFileName, remoteTargetDirectory,null); + } + + public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) { + Connection conn = new Connection(ip, port); + try { + conn.connect(); + boolean isAuthenticated = conn.authenticateWithPassword(username, password); + if (!isAuthenticated) { + System.err.println("authentication failed"); + } + SCPClient client = new SCPClient(conn); + if ((mode == null) || (mode.length() == 0)) { + mode = "0600"; + } + if (remoteFileName == null) { + client.put(localFile, remoteTargetDirectory); + } else { + client.put(localFile, remoteFileName, remoteTargetDirectory, mode); + } + } catch (IOException ex) { + Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex); + }finally{ + conn.close(); + } + } + + private String ip; + private int port; + private String username; + private String password; + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/SqlUtils.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/SqlUtils.java new file mode 100644 index 0000000..718f5b2 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/SqlUtils.java @@ -0,0 +1,206 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.util; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.util.StringUtils; +import com.google.common.collect.Lists; +import lombok.extern.slf4j.Slf4j; + +import javax.sql.DataSource; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.sql.*; +import java.util.List; + +/** + * @author / + */ +@Slf4j +public class SqlUtils { + + public static final String COLON = ":"; + + + /** + * 获取数据源 + * + * @param jdbcUrl / + * @param userName / + * @param password / + * @return DataSource + */ + private static DataSource getDataSource(String jdbcUrl, String userName, String password) { + DruidDataSource druidDataSource = new DruidDataSource(); + String className; + try { + className = DriverManager.getDriver(jdbcUrl.trim()).getClass().getName(); + } catch (SQLException e) { + throw new RuntimeException("Get class name error: =" + jdbcUrl); + } + if (StringUtils.isEmpty(className)) { + DataTypeEnum dataTypeEnum = DataTypeEnum.urlOf(jdbcUrl); + if (null == dataTypeEnum) { + throw new RuntimeException("Not supported data type: jdbcUrl=" + jdbcUrl); + } + druidDataSource.setDriverClassName(dataTypeEnum.getDriver()); + } else { + druidDataSource.setDriverClassName(className); + } + + + druidDataSource.setUrl(jdbcUrl); + druidDataSource.setUsername(userName); + druidDataSource.setPassword(password); + // 配置获取连接等待超时的时间 + druidDataSource.setMaxWait(3000); + // 配置初始化大小、最小、最大 + druidDataSource.setInitialSize(1); + druidDataSource.setMinIdle(1); + druidDataSource.setMaxActive(1); + + // 如果链接出现异常则直接判定为失败而不是一直重试 + druidDataSource.setBreakAfterAcquireFailure(true); + try { + druidDataSource.init(); + } catch (SQLException e) { + log.error("Exception during pool initialization", e); + throw new RuntimeException(e.getMessage()); + } + + return druidDataSource; + } + + private static Connection getConnection(String jdbcUrl, String userName, String password) { + DataSource dataSource = getDataSource(jdbcUrl, userName, password); + Connection connection = null; + try { + connection = dataSource.getConnection(); + } catch (Exception ignored) {} + try { + int timeOut = 5; + if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) { + log.info("connection is closed or invalid, retry get connection!"); + connection = dataSource.getConnection(); + } + } catch (Exception e) { + log.error("create connection error, jdbcUrl: {}", jdbcUrl); + throw new RuntimeException("create connection error, jdbcUrl: " + jdbcUrl); + } + return connection; + } + + private static void releaseConnection(Connection connection) { + if (null != connection) { + try { + connection.close(); + } catch (Exception e) { + log.error(e.getMessage(),e); + log.error("connection close error:" + e.getMessage()); + } + } + } + + + public static void closeResult(ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + } + } + + public static boolean testConnection(String jdbcUrl, String userName, String password) { + Connection connection = null; + try { + connection = getConnection(jdbcUrl, userName, password); + if (null != connection) { + return true; + } + } catch (Exception e) { + log.info("Get connection failed:" + e.getMessage()); + } finally { + releaseConnection(connection); + } + return false; + } + + public static String executeFile(String jdbcUrl, String userName, String password, File sqlFile) { + Connection connection = getConnection(jdbcUrl, userName, password); + try { + batchExecute(connection, readSqlList(sqlFile)); + } catch (Exception e) { + log.error("sql脚本执行发生异常:{}",e.getMessage()); + return e.getMessage(); + }finally { + releaseConnection(connection); + } + return "success"; + } + + + /** + * 批量执行sql + * @param connection / + * @param sqlList / + */ + public static void batchExecute(Connection connection, List sqlList) throws SQLException { + Statement st = connection.createStatement(); + for (String sql : sqlList) { + if (sql.endsWith(";")) { + sql = sql.substring(0, sql.length() - 1); + } + st.addBatch(sql); + } + st.executeBatch(); + } + + /** + * 将文件中的sql语句以;为单位读取到列表中 + * @param sqlFile / + * @return / + * @throws Exception e + */ + private static List readSqlList(File sqlFile) throws Exception { + List sqlList = Lists.newArrayList(); + StringBuilder sb = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader( + new FileInputStream(sqlFile), StandardCharsets.UTF_8))) { + String tmp; + while ((tmp = reader.readLine()) != null) { + log.info("line:{}", tmp); + if (tmp.endsWith(";")) { + sb.append(tmp); + sqlList.add(sb.toString()); + sb.delete(0, sb.length()); + } else { + sb.append(tmp); + } + } + if (!"".endsWith(sb.toString().trim())) { + sqlList.add(sb.toString()); + } + } + + return sqlList; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ZipUtils.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ZipUtils.java new file mode 100644 index 0000000..9ef08c7 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/util/ZipUtils.java @@ -0,0 +1,159 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.util; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +/** + * @author: ZhangHouYing + * @date: 2019-08-10 13:34 + */ +public class ZipUtils { + /** + * 解压文件 + * + * @param zipFilePath 解压文件路径 + * @param outputFolder 输出解压文件路径 + */ + public static void unZipIt(String zipFilePath, String outputFolder) { + byte[] buffer = new byte[1024]; + + File folder = new File(outputFolder); + if (!folder.exists()) { + folder.mkdir(); + } + try { + //get the zip file content + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry ze = zis.getNextEntry(); + while (ze != null) { + String fileName = ze.getName(); + File newFile = new File(outputFolder + File.separator + fileName); + System.out.println("file unzip : " + newFile.getAbsoluteFile()); + //大部分网络上的源码,这里没有判断子目录 + if (ze.isDirectory()) { + if (!newFile.mkdirs()) { + System.out.println("was not successful."); + } + } else { + if (!new File(newFile.getParent()).mkdirs()) { + System.out.println("was not successful."); + } + FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) != -1) { + fos.write(buffer, 0, len); + } + fos.close(); + } + ze = zis.getNextEntry(); + } + zis.closeEntry(); + zis.close(); + System.out.println("Done"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void unzip(File source, String out) throws IOException { + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(source))) { + + ZipEntry entry = zis.getNextEntry(); + + while (entry != null) { + + File file = new File(out, entry.getName()); + + if (entry.isDirectory()) { + if (!file.mkdirs()) { + System.out.println("was not successful."); + } + } else { + File parent = file.getParentFile(); + + if (!parent.exists()) { + if (!parent.mkdirs()) { + System.out.println("was not successful."); + } + } + + try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { + + byte[] buffer = new byte[Math.toIntExact(entry.getSize())]; + + int location; + + while ((location = zis.read(buffer)) != -1) { + bos.write(buffer, 0, location); + } + } + } + entry = zis.getNextEntry(); + } + } + } + + /** + * 把所有文件都直接解压到指定目录(忽略子文件夹) + * + * @param zipFile + * @param folderPath + * @throws ZipException + * @throws IOException + */ + public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { + File desDir = new File(folderPath); + if (!desDir.exists()) { + if (!desDir.mkdirs()) { + System.out.println("was not successful."); + } + } + ZipFile zf = new ZipFile(zipFile); + for (Enumeration entries = zf.entries(); entries.hasMoreElements(); ) { + ZipEntry entry = ((ZipEntry) entries.nextElement()); + InputStream in = zf.getInputStream(entry); + String str = folderPath; + File desFile = new File(str, java.net.URLEncoder.encode(entry.getName(), "UTF-8")); + + if (!desFile.exists()) { + File fileParentDir = desFile.getParentFile(); + if (!fileParentDir.exists()) { + if (!fileParentDir.mkdirs()) { + System.out.println("was not successful."); + } + } + } + + OutputStream out = new FileOutputStream(desFile); + byte[] buffer = new byte[1024 * 1024]; + int realLength = in.read(buffer); + while (realLength != -1) { + out.write(buffer, 0, realLength); + realLength = in.read(buffer); + } + + out.close(); + in.close(); + + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/MsgType.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/MsgType.java new file mode 100644 index 0000000..513e8c6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/MsgType.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.websocket; + +/** + * @author ZhangHouYing + * @date 2019-08-10 9:56 + */ +public enum MsgType { + /** 连接 */ + CONNECT, + /** 关闭 */ + CLOSE, + /** 信息 */ + INFO, + /** 错误 */ + ERROR +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/SocketMsg.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/SocketMsg.java new file mode 100644 index 0000000..c9c470e --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/SocketMsg.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.websocket; + +import lombok.Data; + +/** + * @author ZhangHouYing + * @date 2019-08-10 9:55 + */ +@Data +public class SocketMsg { + private Object msg; + private MsgType msgType; + + public SocketMsg(Object msg, MsgType msgType) { + this.msg = msg; + this.msgType = msgType; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/WebSocketServer.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/WebSocketServer.java new file mode 100644 index 0000000..d2c7920 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/mnt/websocket/WebSocketServer.java @@ -0,0 +1,139 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.mnt.websocket; + +import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArraySet; +/** + * @author ZhangHouYing + * @date 2019-08-10 15:46 + */ +@ServerEndpoint("/webSocket/{sid}") +@Slf4j +@Component +public class WebSocketServer { + + /** + * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 + */ + private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet(); + + /** + * 与某个客户端的连接会话,需要通过它来给客户端发送数据 + */ + private Session session; + + /** + * 接收sid + */ + private String sid=""; + /** + * 连接建立成功调用的方法 + * */ + @OnOpen + public void onOpen(Session session,@PathParam("sid") String sid) { + this.session = session; + //如果存在就先删除一个,防止重复推送消息 + for (WebSocketServer webSocket:webSocketSet) { + if (webSocket.sid.equals(sid)) { + webSocketSet.remove(webSocket); + } + } + webSocketSet.add(this); + this.sid=sid; + } + + /** + * 连接关闭调用的方法 + */ + @OnClose + public void onClose() { + webSocketSet.remove(this); + } + + /** + * 收到客户端消息后调用的方法 + * @param message 客户端发送过来的消息*/ + @OnMessage + public void onMessage(String message, Session session) { + log.info("收到来"+sid+"的信息:"+message); + //群发消息 + for (WebSocketServer item : webSocketSet) { + try { + item.sendMessage(message); + } catch (IOException e) { + log.error(e.getMessage(),e); + } + } + } + + @OnError + public void onError(Session session, Throwable error) { + log.error("发生错误"); + error.printStackTrace(); + } + /** + * 实现服务器主动推送 + */ + private void sendMessage(String message) throws IOException { + this.session.getBasicRemote().sendText(message); + } + + + /** + * 群发自定义消息 + * */ + public static void sendInfo(SocketMsg socketMsg, @PathParam("sid") String sid) throws IOException { + String message = JSONObject.toJSONString(socketMsg); + log.info("推送消息到"+sid+",推送内容:"+message); + for (WebSocketServer item : webSocketSet) { + try { + //这里可以设定只推送给这个sid的,为null则全部推送 + if(sid==null) { + item.sendMessage(message); + }else if(item.sid.equals(sid)){ + item.sendMessage(message); + } + } catch (IOException ignored) { } + } + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WebSocketServer that = (WebSocketServer) o; + return Objects.equals(session, that.session) && + Objects.equals(sid, that.sid); + } + + @Override + public int hashCode() { + return Objects.hash(session, sid); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/LoginPropertiesAutoConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/ConfigBeanConfiguration.java similarity index 89% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/LoginPropertiesAutoConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/ConfigBeanConfiguration.java index ec480e8..71493c6 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/LoginPropertiesAutoConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/ConfigBeanConfiguration.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config; +package org.nl.common.security.config; -import org.nl.system.service.secutiry.dto.LoginProperties; +import org.nl.common.security.config.bean.LoginProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,7 +26,7 @@ import org.springframework.context.annotation.Configuration; * @date: 2020/6/10 19:04 */ @Configuration -public class LoginPropertiesAutoConfig { +public class ConfigBeanConfiguration { @Bean @ConfigurationProperties(prefix = "login", ignoreUnknownFields = true) diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCode.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCode.java similarity index 96% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCode.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCode.java index 64de933..489dfb7 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCode.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCode.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.secutiry.dto; +package org.nl.common.security.config.bean; import lombok.Data; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCodeEnum.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCodeEnum.java similarity index 95% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCodeEnum.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCodeEnum.java index e30cde1..29eae65 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginCodeEnum.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginCodeEnum.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.secutiry.dto; +package org.nl.common.security.config.bean; /** * 验证码配置枚举 diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginProperties.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginProperties.java similarity index 97% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginProperties.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginProperties.java index f6beff7..2babbf2 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/secutiry/dto/LoginProperties.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/config/bean/LoginProperties.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.system.service.secutiry.dto; +package org.nl.common.security.config.bean; import cn.hutool.core.util.StrUtil; import com.wf.captcha.*; import com.wf.captcha.base.Captcha; import lombok.Data; -import org.nl.common.aspect.exception.BadConfigurationException; +import org.nl.common.exception.BadConfigurationException; import java.awt.*; import java.util.Objects; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/RedisListenerConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/RedisListenerConfig.java similarity index 94% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/RedisListenerConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/RedisListenerConfig.java index 29f4508..b5b0448 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/RedisListenerConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/RedisListenerConfig.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.common.security.satoken; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaTokenConfigure.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SaTokenConfigure.java similarity index 88% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaTokenConfigure.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SaTokenConfigure.java index 3f01dc4..ab83e17 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaTokenConfigure.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SaTokenConfigure.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.common.security.satoken; import cn.dev33.satoken.interceptor.SaInterceptor; import cn.dev33.satoken.jwt.StpLogicJwtForSimple; @@ -6,6 +6,7 @@ import cn.dev33.satoken.stp.StpLogic; import cn.dev33.satoken.stp.StpUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; @@ -17,12 +18,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @Date: 2022-09-20 */ @Slf4j -@RequiredArgsConstructor @Configuration public class SaTokenConfigure implements WebMvcConfigurer { // 白名单 - private final SecurityProperties securityProperties; + @Autowired + private SecurityProperties securityProperties; // Sa-Token 整合 jwt (Simple 简单模式) @Bean diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SecurityProperties.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SecurityProperties.java similarity index 91% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SecurityProperties.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SecurityProperties.java index 3a39516..443f1c6 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SecurityProperties.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/SecurityProperties.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.common.security.satoken; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/StpInterfaceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/StpInterfaceImpl.java similarity index 95% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/StpInterfaceImpl.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/StpInterfaceImpl.java index b5e99e6..2bfd6aa 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/StpInterfaceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/StpInterfaceImpl.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.common.security.satoken; import cn.dev33.satoken.stp.StpInterface; import org.nl.common.utils.SecurityUtils; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/hint.md b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/hint.md similarity index 100% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/hint.md rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/security/satoken/hint.md diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/service/UserCacheClean.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/service/UserCacheClean.java new file mode 100644 index 0000000..c16eed4 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/security/service/UserCacheClean.java @@ -0,0 +1,49 @@ +package org.nl.common.security.service;///* +// * Copyright 2019-2020 the original author or authors. +// * +// * 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 +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * 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 org.nl.common.security.service; +// +//import cn.hutool.core.util.StrUtil; +//import org.springframework.stereotype.Component; +// +///** +// * @author: liaojinlong +// * @date: 2020/6/11 18:01 +// * @apiNote: 用于清理 用户登录信息缓存,为防止Spring循环依赖与安全考虑 ,单独构成工具类 +// */ +//@Component +//public class UserCacheClean { +// +// /** +// * 清理特定用户缓存信息
+// * 用户信息变更时 +// * +// * @param userName / +// */ +// public void cleanUserCache(String userName) { +// if (StrUtil.isNotEmpty(userName)) { +//// UserDetailsServiceImpl.userDtoCache.remove(userName); +// } +// } +// +// /** +// * 清理所有用户的缓存信息
+// * ,如发生角色授权信息变化,可以简便的全部失效缓存 +// */ +//// public void cleanAll() { +//// UserDetailsServiceImpl.userDtoCache.clear(); +//// } +//} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CacheKey.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CacheKey.java new file mode 100644 index 0000000..ba14cf0 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CacheKey.java @@ -0,0 +1,58 @@ +/* + * Copyright 2019-2020 the original author or authors. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +/** + * @author: liaojinlong + * @date: 2020/6/11 15:49 + * @apiNote: 关于缓存的Key集合 + */ +public interface CacheKey { + + /** + * 用户 + */ + String USER_ID = "user::id:"; + /** + * 数据 + */ + String DATA_USER = "data::user:"; + /** + * 菜单 + */ + String MENU_ID = "menu::id:"; + String MENU_USER = "menu::user:"; + /** + * 角色授权 + */ + String ROLE_AUTH = "role::auth:"; + /** + * 角色信息 + */ + String ROLE_ID = "role::id:"; + /** + * 部门 + */ + String DEPT_ID = "dept::id:"; + /** + * 岗位 + */ + String JOB_ID = "job::id:"; + /** + * 数据字典 + */ + String DICT_NAME = "dict::name:"; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CodeUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CodeUtil.java index 1687091..313ab23 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CodeUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/CodeUtil.java @@ -1,8 +1,9 @@ package org.nl.common.utils; +import org.nl.config.SpringContextHolder; import org.nl.system.service.coderule.ISysCodeRuleService; -import java.util.HashMap; +import java.util.*; public class CodeUtil { diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ColUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ColUtil.java new file mode 100644 index 0000000..ad0aa1d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ColUtil.java @@ -0,0 +1,35 @@ +package org.nl.common.utils; + +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ColUtil { + private static final Logger log = LoggerFactory.getLogger(ColUtil.class); + + /** + * 转换mysql数据类型为java数据类型 + * + * @param type 数据库字段类型 + * @return String + */ + static String cloToJava(String type) { + Configuration config = getConfig(); + assert config != null; + return config.getString(type, "unknowType"); + } + + /** + * 获取配置信息 + */ + public static PropertiesConfiguration getConfig() { + try { + return new PropertiesConfiguration("generator.properties"); + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + } + return null; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/DateUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/DateUtil.java new file mode 100644 index 0000000..a80fd28 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/DateUtil.java @@ -0,0 +1,160 @@ +/* + * Copyright 2019-2020 the original author or authors. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +/** + * @author: liaojinlong + * @date: 2020/6/11 16:28 + * @apiNote: JDK 8 新日期类 格式化与字符串转换 工具类 + */ +public class DateUtil { + + public static final DateTimeFormatter DFY_MD_HMS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + public static final DateTimeFormatter DFY_MD = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + /** + * LocalDateTime 转时间戳 + * + * @param localDateTime / + * @return / + */ + public static Long getDate(LocalDateTime localDateTime) { + return localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond(); + } + + /** + * 时间戳转LocalDateTime + * + * @param Date / + * @return / + */ + public static LocalDateTime fromDate(Long Date) { + return LocalDateTime.ofEpochSecond(Date, 0, OffsetDateTime.now().getOffset()); + } + + /** + * LocalDateTime 转 Date + * Jdk8 后 不推荐使用 {@link Date} Date + * + * @param localDateTime / + * @return / + */ + public static Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + /** + * LocalDate 转 Date + * Jdk8 后 不推荐使用 {@link Date} Date + * + * @param localDate / + * @return / + */ + public static Date toDate(LocalDate localDate) { + return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault()))); + } + + + /** + * Date转 LocalDateTime + * Jdk8 后 不推荐使用 {@link Date} Date + * + * @param date / + * @return / + */ + public static LocalDateTime toLocalDateTime(Date date) { + return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); + } + + /** + * 日期 格式化 + * + * @param localDateTime / + * @param patten / + * @return / + */ + public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) { + DateTimeFormatter df = DateTimeFormatter.ofPattern(patten); + return df.format(localDateTime); + } + + /** + * 日期 格式化 + * + * @param localDateTime / + * @param df / + * @return / + */ + public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) { + return df.format(localDateTime); + } + + /** + * 日期格式化 yyyy-MM-dd HH:mm:ss + * + * @param localDateTime / + * @return / + */ + public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) { + return DFY_MD_HMS.format(localDateTime); + } + + /** + * 日期格式化 yyyy-MM-dd + * + * @param localDateTime / + * @return / + */ + public String localDateTimeFormatyMd(LocalDateTime localDateTime) { + return DFY_MD.format(localDateTime); + } + + /** + * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd + * + * @param localDateTime / + * @return / + */ + public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); + return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); + } + + /** + * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd + * + * @param localDateTime / + * @return / + */ + public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) { + return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); + } + + /** + * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss + * + * @param localDateTime / + * @return / + */ + public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) { + return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime)); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ElAdminConstant.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ElAdminConstant.java new file mode 100644 index 0000000..1a660fa --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ElAdminConstant.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +/** + * 常用静态常量 + * + * @author Zheng Jie + * @date 2018-12-26 + */ +public class ElAdminConstant { + + /** + * 用于IP定位转换 + */ + public static final String REGION = "内网IP|内网IP"; + /** + * win 系统 + */ + public static final String WIN = "win"; + + /** + * mac 系统 + */ + public static final String MAC = "mac"; + + /** + * 常用接口 + */ + public static class Url { + // IP归属地查询 + public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true"; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/FileUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/FileUtil.java index df4bcdb..a3d9b0a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/FileUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/FileUtil.java @@ -21,8 +21,7 @@ import cn.hutool.poi.excel.BigExcelWriter; import cn.hutool.poi.excel.ExcelUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.streaming.SXSSFSheet; - -import org.nl.common.aspect.exception.BadRequestException; +import org.nl.common.exception.BadRequestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/GenUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/GenUtil.java new file mode 100644 index 0000000..21796f2 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/GenUtil.java @@ -0,0 +1,433 @@ +package org.nl.common.utils; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.extra.template.*; +import lombok.extern.slf4j.Slf4j; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.springframework.util.ObjectUtils; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.nl.common.utils.FileUtil.SYS_TEM_DIR; + +/** + * @author: lyd + * @description: 代码生成 + * @Date: 2022/12/2 + */ +@Slf4j +@SuppressWarnings({"unchecked", "all"}) +public class GenUtil { + private static final String TIMESTAMP = "Timestamp"; + + private static final String Date = "Date"; + + private static final String BIGDECIMAL = "BigDecimal"; + + public static final String PK = "PRI"; + + public static final String EXTRA = "auto_increment"; + + /** + * 获取后端代码模板名称 + * + * @return List + */ + private static List getAdminTemplateNames() { + List templateNames = new ArrayList<>(); + templateNames.add("Entity"); + templateNames.add("MySQLMapper"); + templateNames.add("Dto"); + templateNames.add("Mapper"); + templateNames.add("Controller"); + templateNames.add("QueryCriteria"); + templateNames.add("Service"); + templateNames.add("ServiceImpl"); + // templateNames.add("Repository"); + return templateNames; + } + + /** + * 获取前端代码模板名称 + * + * @return List + */ + private static List getFrontTemplateNames() { + List templateNames = new ArrayList<>(); + templateNames.add("index"); + templateNames.add("api"); + return templateNames; + } + + public static List> preview(List columns, CodeGenConfig genConfig) { + Map genMap = getGenMap(columns, genConfig); // 获取参数 + List> genList = new ArrayList<>(); + // 获取后端模版 + List templates = getAdminTemplateNames(); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + for (String templateName : templates) { // 创建模板 + Map map = new HashMap<>(1); + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + map.put("content", template.render(genMap)); + map.put("name", templateName); + genList.add(map); + } + // 获取前端模版 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Map map = new HashMap<>(1); + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + map.put(templateName, template.render(genMap)); + map.put("content", template.render(genMap)); + map.put("name", templateName); + genList.add(map); + } + return genList; + } + + /** + * 定义后端文件路径以及名称 + */ + private static String getAdminFilePath(String templateName, CodeGenConfig genConfig, String className, String rootPath) { + String projectPath = rootPath + File.separator + genConfig.getModule_name() + File.separator; + String packagePath = projectPath + "src" + File.separator + "main" + File.separator + "java" + File.separator; + if (!ObjectUtils.isEmpty(genConfig.getPack())) { + packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; + } + + if ("Entity".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + className + ".java"; + } + + if ("Controller".equals(templateName)) { + return packagePath + "controller" + File.separator + className + "Controller.java"; + } + + if ("Service".equals(templateName)) { + return packagePath + "service" + File.separator + "I" + className + "Service.java"; + } + + if ("ServiceImpl".equals(templateName)) { + return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; + } + + if ("Dto".equals(templateName)) { + return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; + } + + if ("QueryCriteria".equals(templateName)) { + return packagePath + "service" + File.separator + "dto" + File.separator + className + "Query.java"; + } + + if ("Mapper".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + "mapper" + File.separator + className + "Mapper.java"; + } + + if ("MySQLMapper".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; + } + + return null; + } + + /** + * 定义前端文件路径以及名称 + */ + private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { + + if ("api".equals(templateName)) { + return path + File.separator + apiName + ".js"; + } + + if ("index".equals(templateName)) { + return path + File.separator + "index.vue"; + } + + return null; + } + + // 获取模版数据 + private static Map getGenMap(List columnInfos, CodeGenConfig genConfig) { + // 存储模版字段数据 + Map genMap = new HashMap<>(16); + // 接口别名 + genMap.put("apiAlias", genConfig.getApi_alias()); + // 包名称 + genMap.put("package", genConfig.getPack()); + // 模块名称 + genMap.put("moduleName", genConfig.getModule_name()); + // 作者 + genMap.put("author", genConfig.getAuthor()); + // 创建日期 + genMap.put("date", LocalDate.now().toString()); + // 表名 + genMap.put("tableName", genConfig.getTable_name()); + // 大写开头的类名 + String className = StringUtils.toCapitalizeCamelCase(genConfig.getTable_name()); + // 小写开头的类名 + String changeClassName = StringUtils.toCamelCase(genConfig.getTable_name()); + // 判断是否去除表前缀 + if (StrUtil.isNotEmpty(genConfig.getPrefix())) { + className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTable_name(), genConfig.getPrefix())); + changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTable_name(), genConfig.getPrefix())); + } + // 保存类名 + genMap.put("className", className); // 驼峰命名 + // 保存小写开头的类名 + genMap.put("changeClassName", changeClassName); + // 存在 Timestamp 字段 + genMap.put("hasTimestamp", false); + // 查询类中存在 Timestamp 字段 + genMap.put("queryHasTimestamp", false); + // 存在 BigDecimal 字段 + genMap.put("hasBigDecimal", false); + // 查询类中存在 BigDecimal 字段 + genMap.put("queryHasBigDecimal", false); + // 是否需要创建查询 + genMap.put("hasQuery", false); + // 是否有主键 + genMap.put("hasPk", false); + // 自增主键 + genMap.put("auto", false); + genMap.put("hasDate", false); + // 存在字典 + genMap.put("hasDict", false); + // 存在日期注解 + genMap.put("hasDateAnnotation", false); + // 保存字段信息 + List> columns = new ArrayList<>(); + // 保存查询字段的信息 + List> queryColumns = new ArrayList<>(); + // 存储字典信息 + List dicts = new ArrayList<>(); + // 存储 between 信息 + List> betweens = new ArrayList<>(); + // 存储不为空的字段信息 + List> isNotNullColumns = new ArrayList<>(); + + for (CodeColumnConfig column : columnInfos) { // 遍历所有字段 + Map listMap = new HashMap<>(16); + // 字段描述 + listMap.put("remark", column.getRemark()); + // 字段类型 + listMap.put("columnKey", column.getKey_type()); + // 主键类型 + String colType = ColUtil.cloToJava(column.getColumn_type()); + // 小写开头的字段名 - 转驼峰 +// String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); + String changeColumnName = column.getColumn_name(); + // 大写开头的字段名 + String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumn_name()); + if (PK.equals(column.getKey_type())) { // 如果是主键 + genMap.put("hasPk", true); + // 存储主键类型 + genMap.put("pkColumnType", colType); + // 存储小写开头的字段名 + genMap.put("pkChangeColName", changeColumnName); + // 存储大写开头的字段名 + genMap.put("pkCapitalColName", capitalColumnName); + } + // 是否存在 Timestamp 类型的字段 + if (TIMESTAMP.equals(colType)) { + genMap.put("hasTimestamp", true); + } + // 是否存在 BigDecimal 类型的字段 + if (BIGDECIMAL.equals(colType)) { + genMap.put("hasBigDecimal", true); + } + // 主键是否自增 + if (EXTRA.equals(column.getExtra())) { + genMap.put("auto", true); + } + // 主键存在字典 + if (StrUtil.isNotEmpty(column.getDict_name())) { + genMap.put("hasDict", true); + dicts.add(column.getDict_name()); + } + + // 存储字段类型 + listMap.put("columnType", colType); + // 存储字原始段名称 + listMap.put("columnName", column.getColumn_name()); + // 不为空 + listMap.put("istNotNull", column.getNot_null()); + // 字段列表显示 + listMap.put("columnShow", column.getList_show()); + // 表单显示 + listMap.put("formShow", column.getForm_show()); + // 表单组件类型 + listMap.put("formType", StrUtil.isNotEmpty(column.getForm_type()) ? column.getForm_type() : "Input"); + // 小写开头的字段名称 + listMap.put("changeColumnName", changeColumnName); + //大写开头的字段名称 + listMap.put("capitalColumnName", capitalColumnName); + // 字典名称 + listMap.put("dictName", column.getDict_name()); + // 日期注解 + listMap.put("dateAnnotation", column.getDate_annotation()); + if (StrUtil.isNotEmpty(column.getDate_annotation())) { + genMap.put("hasDateAnnotation", true); + } + // 添加非空字段信息 + if (column.getNot_null()) { + isNotNullColumns.add(listMap); + } + // 判断是否有查询,如有则把查询的字段set进columnQuery + if (!StrUtil.isEmpty(column.getQuery_type())) { + // 查询类型 + listMap.put("queryType", column.getQuery_type()); + // 是否存在查询 + genMap.put("hasQuery", true); + if (TIMESTAMP.equals(colType)) { + // 查询中存储 Timestamp 类型 + genMap.put("queryHasTimestamp", true); + } + if (BIGDECIMAL.equals(colType)) { + // 查询中存储 BigDecimal 类型 + genMap.put("queryHasBigDecimal", true); + } + if ("between".equalsIgnoreCase(column.getQuery_type())) { + betweens.add(listMap); + } else { + // 添加到查询列表中 + queryColumns.add(listMap); + } + } + // 添加到字段列表中 + columns.add(listMap); + } + // 保存字段列表 + genMap.put("columns", columns); + // 保存查询列表 + genMap.put("queryColumns", queryColumns); + // 保存字段列表 + genMap.put("dicts", dicts); + // 保存查询列表 + genMap.put("betweens", betweens); + // 保存非空字段信息 + genMap.put("isNotNullColumns", isNotNullColumns); + return genMap; + } + + /** + * 打包下载 + * @param columns + * @param genConfig + * @return + * @throws IOException + */ + public static String download(List columns, CodeGenConfig genConfig) throws IOException { + // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ + // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; + String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTable_name() + File.separator; + Map genMap = getGenMap(columns, genConfig); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + // 生成后端代码 + List templates = getAdminTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); + assert filePath != null; + File file = new File(filePath); + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + // 生成前端代码 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + String path = tempPath + "nladmin-web" + File.separator; + String apiPath = path + "src" + File.separator + "api" + File.separator; + String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; + String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); + assert filePath != null; + File file = new File(filePath); + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + return tempPath; + } + + /** + * 生成文件 + * @param file + * @param template + * @param map + * @throws IOException + */ + private static void genFile(File file, Template template, Map map) throws IOException { + // 生成目标文件 + Writer writer = null; + try { + FileUtil.touch(file); + writer = new FileWriter(file); + template.render(map, writer); + } catch (TemplateException | IOException e) { + throw new RuntimeException(e); + } finally { + assert writer != null; + writer.close(); + } + } + + /** + * 生成代码 + * @param columnInfos + * @param genConfig + * @throws IOException + */ + public static void generatorCode(List columnInfos, CodeGenConfig genConfig) throws IOException { + Map genMap = getGenMap(columnInfos, genConfig); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + // 生成后端代码 + List templates = getAdminTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), System.getProperty("user.dir")); + + assert filePath != null; + File file = new File(filePath); + + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + + // 生成前端代码 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + String filePath = getFrontFilePath(templateName, genConfig.getApi_path(), genConfig.getPath(), genMap.get("changeClassName").toString()); + + assert filePath != null; + File file = new File(filePath); + + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/HttpUtils.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/HttpUtils.java deleted file mode 100755 index c04c689..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/HttpUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.nl.common.utils; - -import io.netty.handler.codec.http.HttpHeaders; - -/** - * - * @author hengyunabc 2021-02-26 - * - */ -public class HttpUtils { - - public static String findClientIP(HttpHeaders headers) { - String hostStr = headers.get("X-Forwarded-For"); - if (hostStr == null) { - return null; - } - int index = hostStr.indexOf(','); - if (index > 0) { - hostStr = hostStr.substring(0, index); - } - return hostStr; - } - - public static Integer findClientPort(HttpHeaders headers) { - String portStr = headers.get("X-Real-Port"); - if (portStr != null) { - return Integer.parseInt(portStr); - } - return null; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RedisUtils.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RedisUtils.java index 1e6e0de..ec2d2bb 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RedisUtils.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RedisUtils.java @@ -19,7 +19,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.Cursor; @@ -39,7 +38,8 @@ import java.util.concurrent.TimeUnit; public class RedisUtils { private static final Logger log = LoggerFactory.getLogger(RedisUtils.class); private RedisTemplate redisTemplate; - private String onlineKey = "online-key"; + /* @Value("${jwt.online-key}")*/ + private String onlineKey; public RedisUtils(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; @@ -697,9 +697,9 @@ public class RedisUtils { */ public void delByKeys(String prefix, Set ids) { Set keys = new HashSet<>(); - for (Long id : ids) { + /* for (String id : ids) { keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString())); - } + }*/ long count = redisTemplate.delete(keys); // 此处提示可自行删除 log.debug("--------------------------------------------"); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RequestHolder.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RequestHolder.java new file mode 100644 index 0000000..27352b9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/RequestHolder.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Objects; + +/** + * 获取 HttpServletRequest + * @author Zheng Jie + * @date 2018-11-24 + */ +public class RequestHolder { + + public static HttpServletRequest getHttpServletRequest() { + return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SecurityUtils.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SecurityUtils.java index ba78697..b434369 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SecurityUtils.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SecurityUtils.java @@ -5,7 +5,7 @@ import cn.hutool.core.util.ObjectUtil; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import lombok.extern.slf4j.Slf4j; -import org.nl.system.service.user.dto.CurrentUser; +import org.nl.common.utils.dto.CurrentUser; import java.util.List; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/InetAddUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/StringUtils.java old mode 100755 new mode 100644 similarity index 75% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/InetAddUtil.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/StringUtils.java index 0e81a45..f3f5e42 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/InetAddUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/StringUtils.java @@ -1,15 +1,30 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; +import lombok.extern.slf4j.Slf4j; import net.dreamlu.mica.ip2region.core.Ip2regionSearcher; import net.dreamlu.mica.ip2region.core.IpInfo; import nl.basjes.parse.useragent.UserAgent; import nl.basjes.parse.useragent.UserAgentAnalyzer; -import org.nl.config.other.ElAdminProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.nl.config.ElAdminProperties; +import org.nl.config.SpringContextHolder; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; @@ -20,75 +35,20 @@ import java.util.Date; import java.util.Enumeration; /** - * - * @author hengyunabc 2020-10-27 - * + * @author Zheng Jie + * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 */ -public class InetAddUtil { - - static { - System.out.println("InetAddressUtil loading"); - } - - /** - * 用于IP定位转换 - */ - public static final String REGION = "内网IP|内网IP"; - /** - * win 系统 - */ - public static final String WIN = "win"; - - /** - * mac 系统 - */ - public static final String MAC = "mac"; - - /** - * 常用接口 - */ - public static class Url { - // IP归属地查询 - public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true"; - } +@Slf4j +public class StringUtils { private static final char SEPARATOR = '_'; private static final String UNKNOWN = "unknown"; - private final static Logger logger = LoggerFactory.getLogger(InetAddUtil.class); /** - * 获得本机IP。 - *

- * 在超过一块网卡时会有问题,因为这里每次都只是取了第一块网卡绑定的IP地址 + * 注入bean */ - public static String getInetAddress() { - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - InetAddress address = null; - while (interfaces.hasMoreElements()) { - NetworkInterface ni = interfaces.nextElement(); - Enumeration addresses = ni.getInetAddresses(); - while (addresses.hasMoreElements()) { - address = addresses.nextElement(); - if (isValidAddress(address)) { - return address.getHostAddress(); - } - } - } - logger.warn("Can not get the server IP address"); - return null; - } catch (Throwable t) { - logger.error("Can not get the server IP address", t); - return null; - } - } + private final static Ip2regionSearcher IP_SEARCHER = SpringContextHolder.getBean(Ip2regionSearcher.class); - public static boolean isValidAddress(InetAddress address) { - return address != null && !address.isLoopbackAddress() // filter 127.x.x.x - && !address.isAnyLocalAddress() // filter 0.0.0.0 - && !address.isLinkLocalAddress() // filter 169.254.0.0/16 - && !address.getHostAddress().contains(":");// filter IPv6 - } private static final UserAgentAnalyzer USER_AGENT_ANALYZER = UserAgentAnalyzer .newBuilder() @@ -211,7 +171,7 @@ public class InetAddUtil { try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { - e.printStackTrace(); + log.error(e.getMessage(), e); } } return ip; @@ -222,11 +182,11 @@ public class InetAddUtil { */ public static String getCityInfo(String ip) { if (ElAdminProperties.ipLocal) { - // return getLocalCityInfo(ip); + // return getLocalCityInfo(ip); return "局域网"; } else { return "局域网"; - // return getHttpCityInfo(ip); + // return getHttpCityInfo(ip); } } @@ -234,7 +194,7 @@ public class InetAddUtil { * 根据ip获取详细地址 */ public static String getHttpCityInfo(String ip) { - String api = String.format(InetAddUtil.Url.IP_URL, ip); + String api = String.format(ElAdminConstant.Url.IP_URL, ip); JSONObject object = JSONUtil.parseObj(HttpUtil.get(api)); return object.get("addr", String.class); } @@ -243,7 +203,7 @@ public class InetAddUtil { * 根据ip获取详细地址 */ public static String getLocalCityInfo(String ip) { - IpInfo ipInfo = SpringContextHolder.getBean(Ip2regionSearcher.class).memorySearch(ip); + IpInfo ipInfo = IP_SEARCHER.memorySearch(ip); if(ipInfo != null){ return ipInfo.getAddress(); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/TranslatorUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/TranslatorUtil.java new file mode 100644 index 0000000..7947e5b --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/TranslatorUtil.java @@ -0,0 +1,67 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +import cn.hutool.json.JSONArray; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; + +/** + * @author Zheng Jie + * 翻译工具类 + */ +public class TranslatorUtil { + + public static String translate(String word){ + try { + String url = "https://translate.googleapis.com/translate_a/single?" + + "client=gtx&" + + "sl=en" + + "&tl=zh-CN" + + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8"); + + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestProperty("User-Agent", "Mozilla/5.0"); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuilder response = new StringBuilder(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + return parseResult(response.toString()); + }catch (Exception e){ + return word; + } + } + + private static String parseResult(String inputJson){ + JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0); + StringBuilder result = new StringBuilder(); + for (Object o : jsonArray2) { + result.append(((JSONArray) o).get(0).toString()); + } + return result.toString(); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ValidationUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ValidationUtil.java new file mode 100644 index 0000000..7b9d80a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/ValidationUtil.java @@ -0,0 +1,45 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.common.utils; + +import cn.hutool.core.util.ObjectUtil; +import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; +import org.nl.common.exception.BadRequestException; + +/** + * 验证工具 + * @author Zheng Jie + * @date 2018-11-23 + */ +public class ValidationUtil{ + + /** + * 验证空 + */ + public static void isNull(Object obj, String entity, String parameter , Object value){ + if(ObjectUtil.isNull(obj)){ + String msg = entity + " 不存在: "+ parameter +" is "+ value; + throw new BadRequestException(msg); + } + } + + /** + * 验证是否为邮箱 + */ + public static boolean isEmail(String email) { + return new EmailValidator().isValid(email, null); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/user/dto/CurrentUser.java b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/dto/CurrentUser.java similarity index 90% rename from nladmin-system/nlsso-server/src/main/java/org/nl/system/service/user/dto/CurrentUser.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/dto/CurrentUser.java index 02d6e5f..440752f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/user/dto/CurrentUser.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/dto/CurrentUser.java @@ -1,4 +1,4 @@ -package org.nl.system.service.user.dto; +package org.nl.common.utils.dto; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; @@ -28,6 +28,4 @@ public class CurrentUser implements Serializable { private SysUser user; private List permissions = new ArrayList<>(); - - private String domain; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/AuditorConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/AuditorConfig.java similarity index 97% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/AuditorConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/AuditorConfig.java index 09450f3..7ce0e4a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/AuditorConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/AuditorConfig.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/CallBack.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/CallBack.java similarity index 95% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/CallBack.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/CallBack.java index 3e14271..c50349f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/domain/CallBack.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/CallBack.java @@ -1,4 +1,4 @@ -/* +package org.nl.config;/* * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +14,11 @@ * limitations under the License. */ -package org.nl.common.domain; - /** * @author: liaojinlong * @date: 2020/6/9 17:02 * @since: 1.0 + * @see {@link SpringContextHolder} * 针对某些初始化方法,在SpringContextHolder 初始化前时,
* 可提交一个 提交回调任务。
* 在SpringContextHolder 初始化后,进行回调使用 diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/DruidFilter.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/DruidFilter.java deleted file mode 100644 index 9e483c8..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/DruidFilter.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.nl.config; - -import com.alibaba.druid.filter.FilterChain; -import com.alibaba.druid.filter.FilterEventAdapter; -import com.alibaba.druid.proxy.jdbc.JdbcParameter; -import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy; -import com.alibaba.druid.proxy.jdbc.ResultSetProxy; -import com.alibaba.druid.proxy.jdbc.StatementProxy; -import com.alibaba.druid.sql.SQLUtils; -import com.alibaba.druid.util.JdbcUtils; -import com.mysql.cj.jdbc.result.ResultSetImpl; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.MDC; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/* - * @author ZZQ - * @Date 2023/2/10 11:27 上午 - */ -@Slf4j -public class DruidFilter extends FilterEventAdapter { - - @Override - public int preparedStatement_executeUpdate(FilterChain chain, PreparedStatementProxy statement) throws SQLException { - - return super.preparedStatement_executeUpdate(chain, statement); - } - - @Override - public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql) throws SQLException { - - return super.statement_executeUpdate(chain, statement, sql); - } - - @Override - protected void statementExecuteAfter(StatementProxy statement, String sql, boolean result) { - String traceId = MDC.get("traceId"); - int size = statement.getParametersSize(); - String executeSql = sql; - int count = 0; - try { - count=statement.getUpdateCount(); - }catch (Exception ex){ } - if (StringUtils.isNotEmpty(traceId) && count>0) { - if (size > 0) { - Collection values = statement.getParameters().values(); - List params = new ArrayList<>(); - for (JdbcParameter value : values) { - params.add(value.getValue()); - } - executeSql = SQLUtils.format(executeSql, JdbcUtils.MYSQL, params); - } - log.info("[----SQL----][update][ SQL: {} ]", executeSql); - } - super.statementExecuteAfter(statement, sql, result); - } - @Override - public ResultSetProxy statement_getResultSet(FilterChain chain, StatementProxy statement) throws SQLException { - ResultSetProxy rs = super.statement_getResultSet(chain, statement); - String executeSql = statement.getLastExecuteSql(); - String traceId = MDC.get("traceId"); - if (StringUtils.isNotEmpty(traceId)){ - int result = 0; - if (rs != null) { - ResultSetImpl rss = rs.getResultSetRaw().unwrap(ResultSetImpl.class); - result = rss.getRows().size(); - } - try { - int size = statement.getParametersSize(); - if (size>0){ - Collection values = statement.getParameters().values(); - List params = new ArrayList<>(); - for (JdbcParameter value : values) { - params.add(value.getValue()); - } - executeSql = SQLUtils.format(executeSql, JdbcUtils.MYSQL, params); - } - }catch (Exception ex){ - log.warn("[-SQL解析异常-][{}]",ex.getMessage()); - } - log.info("[----SQL----][select][执行结果:{}][ SQL: {} ]",result, executeSql); - } - return rs; - } - - - - - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/DtpConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/DtpConfig.java deleted file mode 100644 index d1597e7..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/DtpConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.nl.config; - -import com.dtp.core.support.ThreadPoolBuilder; -import com.dtp.core.support.ThreadPoolCreator; -import com.dtp.core.thread.DtpExecutor; -import org.springframework.boot.web.servlet.server.ServletWebServerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年01月13日 14:30 - * @desc desc - */ -@Configuration -public class DtpConfig { - - /** - * 通过{@link ThreadPoolCreator} 快速创建一些简单配置的动态线程池 - * tips: 建议直接在配置中心配置就行,不用@Bean声明 - * - * @return 线程池实例 - */ - @Bean - public DtpExecutor dtpExecutor1() { - - return ThreadPoolBuilder.newBuilder() - .threadPoolName("dtpExecutor1") - .corePoolSize(1) - .maximumPoolSize(1) - .queueCapacity(1) - .ioIntensive(true) - .buildDynamic(); - } - @Bean - public Object tomcatServletWebServerFactory(ServletWebServerFactory webServerFactory) { - return new Object(); - } - - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElAdminProperties.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/ElAdminProperties.java similarity index 97% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElAdminProperties.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/ElAdminProperties.java index 86db8a6..b407c24 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElAdminProperties.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/ElAdminProperties.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElPermissionConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/ElPermissionConfig.java similarity index 97% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElPermissionConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/ElPermissionConfig.java index 121c389..4abc37f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/ElPermissionConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/ElPermissionConfig.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import org.springframework.stereotype.Service; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/FileProperties.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/FileProperties.java similarity index 87% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/FileProperties.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/FileProperties.java index 5e783a7..0d85a82 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/FileProperties.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/FileProperties.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import lombok.Data; -import org.nl.common.utils.InetAddUtil; +import org.nl.common.utils.ElAdminConstant; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @@ -42,9 +42,9 @@ public class FileProperties { public ElPath getPath(){ String os = System.getProperty("os.name"); - if(os.toLowerCase().startsWith(InetAddUtil.WIN)) { + if(os.toLowerCase().startsWith(ElAdminConstant.WIN)) { return windows; - } else if(os.toLowerCase().startsWith(InetAddUtil.MAC)){ + } else if(os.toLowerCase().startsWith(ElAdminConstant.MAC)){ return mac; } return linux; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/IdUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/IdUtil.java similarity index 89% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/IdUtil.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/IdUtil.java index 41f47c0..5980d3a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/IdUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/IdUtil.java @@ -1,4 +1,4 @@ -package org.nl.common.utils; +package org.nl.config; public class IdUtil { public static Long getLongId() { diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/MapOf.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/MapOf.java similarity index 71% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/MapOf.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/MapOf.java index fc8dc01..7ecd4bf 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/MapOf.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/MapOf.java @@ -1,8 +1,12 @@ -package org.nl.common.utils; +package org.nl.config; +import org.checkerframework.checker.units.qual.K; +import org.springframework.util.CollectionUtils; + import java.io.Serializable; import java.util.HashMap; +import java.util.Iterator; /* * @author ZZQ diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/MultipartConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/MultipartConfig.java index 086a5a6..1afed12 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/MultipartConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/MultipartConfig.java @@ -16,7 +16,7 @@ import java.io.File; public class MultipartConfig { /** - * 文件上传临时路 径 + * 文件上传临时路径 */ @Bean MultipartConfigElement multipartConfigElement() { diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RedisConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java similarity index 99% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RedisConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java index f2b6fad..e0785bb 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RedisConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RedisConfig.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.StrUtil; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RsaProperties.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RsaProperties.java similarity index 97% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RsaProperties.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/RsaProperties.java index 68c1fbc..399a47a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/RsaProperties.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/RsaProperties.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SpringContextHolder.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/SpringContextHolder.java similarity index 98% rename from nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SpringContextHolder.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/SpringContextHolder.java index d449662..3a2ae32 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/common/utils/SpringContextHolder.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/SpringContextHolder.java @@ -1,4 +1,4 @@ -/* +package org.nl.config;/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,16 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.common.utils; import lombok.extern.slf4j.Slf4j; -import org.nl.common.domain.CallBack; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.env.Environment; - import java.util.ArrayList; import java.util.List; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/SwaggerConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/SwaggerConfig.java similarity index 99% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/other/SwaggerConfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/SwaggerConfig.java index f2a83e9..fa7ae74 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/other/SwaggerConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/SwaggerConfig.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.nl.config.other; +package org.nl.config; import com.fasterxml.classmate.TypeResolver; import io.swagger.annotations.ApiModel; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/WebSocketConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/WebSocketConfig.java index ec08886..28a447c 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/WebSocketConfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/WebSocketConfig.java @@ -23,7 +23,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; * @author ZhangHouYing * @date 2019-08-24 15:44 */ -//@Configuration +@Configuration public class WebSocketConfig { @Bean diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/ArthasConstants.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/ArthasConstants.java deleted file mode 100755 index 33dd978..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/ArthasConstants.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.nl.config.arthas; - -/** - * 常量 - */ -public class ArthasConstants { - /** - * local address in VM communication - * - * @see io.netty.channel.local.LocalAddress - * @see io.netty.channel.local.LocalChannel - */ - public static final String NETTY_LOCAL_ADDRESS = "arthas-netty-LocalAddress"; - - public static final int MAX_HTTP_CONTENT_LENGTH = 1024 * 1024 * 8; - - public static final String ARTHAS_OUTPUT = "arthas-output"; - - public static final String APP_NAME = "app-name"; - - public static final String PROJECT_NAME = "project.name"; - public static final String SPRING_APPLICATION_NAME = "spring.application.name"; - - public static final int TELNET_PORT = 3658; - - public static final String DEFAULT_WEBSOCKET_PATH = "/ws"; - public static final int WEBSOCKET_IDLE_SECONDS = 60; - - /** - * HTTP cookie id - */ - public static final String ASESSION_KEY = "asession"; - - public static final String DEFAULT_USERNAME = "arthas"; - public static final String SUBJECT_KEY = "subject"; - public static final String AUTH = "auth"; - public static final String USERNAME_KEY = "username"; - public static final String PASSWORD_KEY = "password"; -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelClusterStoreConfiguration.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelClusterStoreConfiguration.java deleted file mode 100755 index dd26933..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelClusterStoreConfiguration.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.nl.config.arthas; - -import org.nl.monitor.server.arthas.cluster.InMemoryClusterStore; -import org.nl.monitor.server.arthas.cluster.RedisTunnelClusterStore; -import org.nl.monitor.server.arthas.cluster.TunnelClusterStore; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.data.redis.core.StringRedisTemplate; - -/** - * - * @author hengyunabc 2020-10-29 - * - */ -@Configuration -@AutoConfigureAfter(value = { RedisAutoConfiguration.class, CacheAutoConfiguration.class }) -@Import(TunnelClusterStoreConfiguration.RedisTunnelClusterStoreConfiguration.class) -public class TunnelClusterStoreConfiguration { - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty(name = "spring.cache.type", havingValue = "caffeine") - public TunnelClusterStore tunnelClusterStore(@Autowired CacheManager cacheManager) { - Cache inMemoryClusterCache = cacheManager.getCache("inMemoryClusterCache"); - InMemoryClusterStore inMemoryClusterStore = new InMemoryClusterStore(); - inMemoryClusterStore.setCache(inMemoryClusterCache); - return inMemoryClusterStore; - } - static class RedisTunnelClusterStoreConfiguration { - @Bean - // @ConditionalOnBean(StringRedisTemplate.class) - @ConditionalOnClass(StringRedisTemplate.class) - @ConditionalOnProperty("spring.redis.host") - @ConditionalOnMissingBean - public TunnelClusterStore tunnelClusterStore(@Autowired StringRedisTemplate redisTemplate) { - RedisTunnelClusterStore redisTunnelClusterStore = new RedisTunnelClusterStore(); - redisTunnelClusterStore.setRedisTemplate(redisTemplate); - return redisTunnelClusterStore; - } - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelServerConfiguration.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelServerConfiguration.java deleted file mode 100755 index b77e7c3..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/TunnelServerConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.nl.config.arthas; - -import com.alibaba.arthas.spring.ArthasProperties; -import org.nl.common.utils.InetAddUtil; -import org.nl.monitor.server.arthas.TunnelServer; -import org.nl.monitor.server.arthas.cluster.TunnelClusterStore; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * - * @author hengyunabc 2020-10-27 - * - */ -@Configuration -@AutoConfigureAfter(RedisAutoConfiguration.class) -public class TunnelServerConfiguration { - - @Autowired - ArthasProperties arthasProperties; - - @Bean(initMethod = "start", destroyMethod = "stop") - @ConditionalOnMissingBean - public TunnelServer tunnelServer(@Autowired(required = false) TunnelClusterStore tunnelClusterStore) { - TunnelServer tunnelServer = new TunnelServer(); - - tunnelServer.setHost(arthasProperties.getIp()); - tunnelServer.setPort(arthasProperties.getHttpPort()); - tunnelServer.setSsl(false); - tunnelServer.setPath(ArthasConstants.DEFAULT_WEBSOCKET_PATH); - tunnelServer.setClientConnectHost(InetAddUtil.getInetAddress()); - if (tunnelClusterStore != null) { - tunnelServer.setTunnelClusterStore(tunnelClusterStore); - } - return tunnelServer; - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndPointAutoconfiguration.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndPointAutoconfiguration.java deleted file mode 100755 index 5185cb3..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndPointAutoconfiguration.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.nl.config.arthas.endpoint; - -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; - -//@EnableConfigurationProperties(TunnelProperties.class) -//@Configuration -public class ArthasEndPointAutoconfiguration { - - @ConditionalOnMissingBean - @Bean - @ConditionalOnAvailableEndpoint - public ArthasEndpoint arthasEndPoint() { - return new ArthasEndpoint(); - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndpoint.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndpoint.java deleted file mode 100755 index 62d695b..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/endpoint/ArthasEndpoint.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.nl.config.arthas.endpoint; - -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.arthas.spring.ArthasProperties; -import org.nl.monitor.server.arthas.TunnelServer; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - - -//@Endpoint(id = "arthas") -public class ArthasEndpoint { - - @Autowired - ArthasProperties arthasProperties; - @Autowired - TunnelServer tunnelServer; - - @ReadOperation - public Map invoke() { - Map result = new HashMap(); - - result.put("version", this.getClass().getPackage().getImplementationVersion()); - result.put("properties", arthasProperties); - - result.put("agents", tunnelServer.getAgentInfoMap()); - result.put("clientConnections", tunnelServer.getClientConnectionInfoMap()); - - return result; - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/RelayHandler.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/RelayHandler.java deleted file mode 100755 index 29dbcc4..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/RelayHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.nl.config.arthas.netty; - -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.util.ReferenceCountUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class RelayHandler extends ChannelInboundHandlerAdapter { - - private final static Logger logger = LoggerFactory.getLogger(RelayHandler.class); - - private final Channel relayChannel; - - public RelayHandler(Channel relayChannel) { - this.relayChannel = relayChannel; - } - - @Override - public void channelActive(ChannelHandlerContext ctx) { - ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) { - if (relayChannel.isActive()) { - relayChannel.writeAndFlush(msg); - } else { - ReferenceCountUtil.release(msg); - } - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) { - if (relayChannel.isActive()) { - if (relayChannel.isActive()) { - relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); - } - } - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - logger.error("", cause); - ctx.close(); - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketFrameHandler.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketFrameHandler.java deleted file mode 100755 index 6de8bf3..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketFrameHandler.java +++ /dev/null @@ -1,294 +0,0 @@ - -package org.nl.config.arthas.netty; - -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.QueryStringDecoder; -import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete; -import io.netty.util.concurrent.*; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.tomcat.util.codec.binary.Base64; -import org.nl.common.arthas.MethodConstants; -import org.nl.common.arthas.SimpleHttpResponse; -import org.nl.common.arthas.URIConstans; -import org.nl.common.utils.HttpUtils; -import org.nl.monitor.server.arthas.TunnelServer; -import org.nl.monitor.server.arthas.dto.AgentInfo; -import org.nl.monitor.server.arthas.dto.ClientConnectionInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.MultiValueMap; -import org.springframework.web.util.UriComponentsBuilder; - -import java.net.*; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -/** - * - * @author hengyunabc 2019-08-27 - * - */ -public class TunnelSocketFrameHandler extends SimpleChannelInboundHandler { - - private final static Logger logger = LoggerFactory.getLogger(TunnelSocketFrameHandler.class); - - private TunnelServer tunnelServer; - - public TunnelSocketFrameHandler(TunnelServer tunnelServer) { - this.tunnelServer = tunnelServer; - } - - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - if (evt instanceof HandshakeComplete) { - HandshakeComplete handshake = (HandshakeComplete) evt; - // http request uri - String uri = handshake.requestUri(); - logger.info("websocket handshake complete, uri: {}", uri); - - MultiValueMap parameters = UriComponentsBuilder.fromUriString(uri).build().getQueryParams(); - String method = parameters.getFirst(URIConstans.METHOD); - - if (MethodConstants.CONNECT_ARTHAS.equals(method)) { // form browser - connectArthas(ctx, parameters); - } else if (MethodConstants.AGENT_REGISTER.equals(method)) { // form arthas agent, register - agentRegister(ctx, handshake, uri); - } - if (MethodConstants.OPEN_TUNNEL.equals(method)) { // from arthas agent open tunnel - String clientConnectionId = parameters.getFirst(URIConstans.CLIENT_CONNECTION_ID); - openTunnel(ctx, clientConnectionId); - } - } else { - ctx.fireUserEventTriggered(evt); - } - } - - @Override - protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { - System.out.println("接收netty消息"+frame.toString()); - // 只有 arthas agent register建立的 channel 才可能有数据到这里 - if (frame instanceof TextWebSocketFrame) { - TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; - String text = textFrame.text(); - - MultiValueMap parameters = UriComponentsBuilder.fromUriString(text).build() - .getQueryParams(); - - String method = parameters.getFirst(URIConstans.METHOD); - - /** - *
-             * 1. 之前http proxy请求已发送到 tunnel cleint,这里接收到 tunnel client的结果,并解析出SimpleHttpResponse
-             * 2. 需要据 URIConstans.PROXY_REQUEST_ID 取出当时的 Promise,再设置SimpleHttpResponse进去
-             * 
- */ - if (MethodConstants.HTTP_PROXY.equals(method)) { - String requestId = URLDecoder.decode(parameters.getFirst(URIConstans.PROXY_REQUEST_ID), "utf-8"); - - if (requestId == null) { - logger.error("error, need {}, text: {}", URIConstans.PROXY_REQUEST_ID, text); - return; - } - logger.info("received http proxy response, requestId: {}", requestId); - - Promise promise = tunnelServer.findProxyRequestPromise(requestId); - String data = URLDecoder.decode(parameters.getFirst(URIConstans.PROXY_RESPONSE_DATA), "utf-8"); - byte[] bytes = Base64.decodeBase64(data); - SimpleHttpResponse simpleHttpResponse = SimpleHttpResponse.fromBytes(bytes); - promise.setSuccess(simpleHttpResponse); - } - } - } - - private void connectArthas(ChannelHandlerContext tunnelSocketCtx, MultiValueMap parameters) - throws URISyntaxException { - - List agentId = parameters.getOrDefault("id", Collections.emptyList()); - - if (agentId.isEmpty()) { - logger.error("arthas agent id can not be null, parameters: {}", parameters); - throw new IllegalArgumentException("arthas agent id can not be null"); - } - - logger.info("try to connect to arthas agent, id: " + agentId.get(0)); - - Optional findAgent = tunnelServer.findAgent(agentId.get(0)); - - if (findAgent.isPresent()) { - ChannelHandlerContext agentCtx = findAgent.get().getChannelHandlerContext(); - - String clientConnectionId = RandomStringUtils.random(20, true, true).toUpperCase(); - - logger.info("random clientConnectionId: " + clientConnectionId); - // URI uri = new URI("response", null, "/", - // "method=" + MethodConstants.START_TUNNEL + "&id=" + agentId.get(0) + "&clientConnectionId=" + clientConnectionId, null); - URI uri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") - .queryParam(URIConstans.METHOD, MethodConstants.START_TUNNEL).queryParam(URIConstans.ID, agentId) - .queryParam(URIConstans.CLIENT_CONNECTION_ID, clientConnectionId).build().toUri(); - - logger.info("startTunnel response: " + uri); - - ClientConnectionInfo clientConnectionInfo = new ClientConnectionInfo(); - SocketAddress remoteAddress = tunnelSocketCtx.channel().remoteAddress(); - if (remoteAddress instanceof InetSocketAddress) { - InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress; - clientConnectionInfo.setHost(inetSocketAddress.getHostString()); - clientConnectionInfo.setPort(inetSocketAddress.getPort()); - } - clientConnectionInfo.setChannelHandlerContext(tunnelSocketCtx); - - // when the agent open tunnel success, will set result into the promise - Promise promise = GlobalEventExecutor.INSTANCE.newPromise(); - promise.addListener(new FutureListener() { - @Override - public void operationComplete(final Future future) throws Exception { - final Channel outboundChannel = future.getNow(); - if (future.isSuccess()) { - tunnelSocketCtx.pipeline().remove(TunnelSocketFrameHandler.this); - - // outboundChannel is form arthas agent - outboundChannel.pipeline().removeLast(); - - outboundChannel.pipeline().addLast(new RelayHandler(tunnelSocketCtx.channel())); - tunnelSocketCtx.pipeline().addLast(new RelayHandler(outboundChannel)); - } else { - logger.error("wait for agent connect error. agentId: {}, clientConnectionId: {}", agentId, - clientConnectionId); - if (agentCtx.channel().isActive()) { - agentCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); - } - } - } - }); - - clientConnectionInfo.setPromise(promise); - this.tunnelServer.addClientConnectionInfo(clientConnectionId, clientConnectionInfo); - tunnelSocketCtx.channel().closeFuture().addListener(new GenericFutureListener>() { - @Override - public void operationComplete(Future future) throws Exception { - tunnelServer.removeClientConnectionInfo(clientConnectionId); - } - }); - - agentCtx.channel().writeAndFlush(new TextWebSocketFrame(uri.toString())); - - logger.info("browser connect waitting for arthas agent open tunnel"); - boolean watiResult = promise.awaitUninterruptibly(20, TimeUnit.SECONDS); - if (watiResult) { - logger.info( - "browser connect wait for arthas agent open tunnel success, agentId: {}, clientConnectionId: {}", - agentId, clientConnectionId); - } else { - logger.error( - "browser connect wait for arthas agent open tunnel timeout, agentId: {}, clientConnectionId: {}", - agentId, clientConnectionId); - tunnelSocketCtx.close(); - } - } else { - tunnelSocketCtx.channel().writeAndFlush(new CloseWebSocketFrame(2000, "Can not find arthas agent by id: "+ agentId)); - logger.error("Can not find arthas agent by id: {}", agentId); - throw new IllegalArgumentException("Can not find arthas agent by id: " + agentId); - } - } - - private void agentRegister(ChannelHandlerContext ctx, HandshakeComplete handshake, String requestUri) throws URISyntaxException { - QueryStringDecoder queryDecoder = new QueryStringDecoder(requestUri); - Map> parameters = queryDecoder.parameters(); - - String appName = null; - List appNameList = parameters.get(URIConstans.APP_NAME); - if (appNameList != null && !appNameList.isEmpty()) { - appName = appNameList.get(0); - } - - // generate a random agent id - String id = null; - if (appName != null) { - // 如果有传 app name,则生成带 app name前缀的id,方便管理 - id = appName + "_" + RandomStringUtils.random(20, true, true).toUpperCase(); - } else { - id = RandomStringUtils.random(20, true, true).toUpperCase(); - } - // agent传过来,则优先用 agent的 - List idList = parameters.get(URIConstans.ID); - if (idList != null && !idList.isEmpty()) { - id = idList.get(0); - } - - String arthasVersion = null; - List arthasVersionList = parameters.get(URIConstans.ARTHAS_VERSION); - if (arthasVersionList != null && !arthasVersionList.isEmpty()) { - arthasVersion = arthasVersionList.get(0); - } - - final String finalId = id; - - // URI responseUri = new URI("response", null, "/", "method=" + MethodConstants.AGENT_REGISTER + "&id=" + id, null); - URI responseUri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/") - .queryParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER).queryParam(URIConstans.ID, id).build() - .encode().toUri(); - - AgentInfo info = new AgentInfo(); - - // 前面可能有nginx代理 - HttpHeaders headers = handshake.requestHeaders(); - String host = HttpUtils.findClientIP(headers); - - if (host == null) { - SocketAddress remoteAddress = ctx.channel().remoteAddress(); - if (remoteAddress instanceof InetSocketAddress) { - InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress; - info.setHost(inetSocketAddress.getHostString()); - info.setPort(inetSocketAddress.getPort()); - } - } else { - info.setHost(host); - Integer port = HttpUtils.findClientPort(headers); - if (port != null) { - info.setPort(port); - } - } - - info.setChannelHandlerContext(ctx); - if (arthasVersion != null) { - info.setArthasVersion(arthasVersion); - } - - tunnelServer.addAgent(id, info); - ctx.channel().closeFuture().addListener(new GenericFutureListener>() { - @Override - public void operationComplete(Future future) throws Exception { - tunnelServer.removeAgent(finalId); - } - - }); - - ctx.channel().writeAndFlush(new TextWebSocketFrame(responseUri.toString())); - } - - private void openTunnel(ChannelHandlerContext ctx, String clientConnectionId) { - Optional infoOptional = this.tunnelServer.findClientConnection(clientConnectionId); - - if (infoOptional.isPresent()) { - ClientConnectionInfo info = infoOptional.get(); - logger.info("openTunnel clientConnectionId:" + clientConnectionId); - - Promise promise = info.getPromise(); - promise.setSuccess(ctx.channel()); - } else { - logger.error("Can not find client connection by id: {}", clientConnectionId); - } - - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketServerInitializer.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketServerInitializer.java deleted file mode 100755 index c6628d1..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/arthas/netty/TunnelSocketServerInitializer.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.nl.config.arthas.netty; - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; -import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; -import io.netty.handler.ssl.SslContext; -import org.nl.config.arthas.ArthasConstants; -import org.nl.monitor.server.arthas.TunnelServer; - - -/** - * - * @author hengyunabc 2019-08-27 - * - */ -public class TunnelSocketServerInitializer extends ChannelInitializer { - - private final SslContext sslCtx; - - private TunnelServer tunnelServer; - - public TunnelSocketServerInitializer(TunnelServer tunnelServer, SslContext sslCtx) { - this.sslCtx = sslCtx; - this.tunnelServer = tunnelServer; - } - - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - if (sslCtx != null) { - pipeline.addLast(sslCtx.newHandler(ch.alloc())); - } - pipeline.addLast(new HttpServerCodec()); - pipeline.addLast(new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH)); - pipeline.addLast(new WebSocketServerCompressionHandler()); - pipeline.addLast(new WebSocketServerProtocolHandler(tunnelServer.getPath(), null, true, ArthasConstants.MAX_HTTP_CONTENT_LENGTH, false, true, 10000L)); - - pipeline.addLast(new TunnelSocketFrameHandler(tunnelServer)); - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogAppender.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogAppender.java new file mode 100644 index 0000000..000ca5e --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogAppender.java @@ -0,0 +1,49 @@ +package org.nl.config.lucene; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.core.rolling.RollingFileAppender; +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.nio.charset.Charset; + +public class DynamicLogAppender { + /** + * 通过传入的动态名字,动态设置appender + * @param dynamicName + * @return + */ + public RollingFileAppender getAppender(String oldLogPath,String dynamicName) { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + RollingFileAppender appender = new RollingFileAppender(); + //appender的name属性 + appender.setName(dynamicName); + appender.setContext(context); + + //设置文件名 + appender.setFile(new File(oldLogPath, dynamicName + "\\" + DateUtil.format(new DateTime(),"yyyy-MM-dd")+".log").getAbsolutePath()); + //设置日志文件输出格式 + PatternLayoutEncoder encoder = new PatternLayoutEncoder(); + encoder.setContext(context); + encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"); + encoder.setCharset(Charset.forName("UTF-8")); + encoder.start(); + + //设置日志记录器的滚动策略 + TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy(); + policy.setFileNamePattern(oldLogPath+dynamicName+".%d{yyyy-MM-dd}.log"); + policy.setParent(appender); //设置父节点是appender + policy.setContext(context); + policy.start(); + + //加入下面两个节点 + appender.setRollingPolicy(policy); + appender.setEncoder(encoder); + appender.start(); + return appender; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogger.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogger.java new file mode 100644 index 0000000..566a899 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/DynamicLogger.java @@ -0,0 +1,35 @@ +package org.nl.config.lucene; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.core.rolling.RollingFileAppender; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +public class DynamicLogger { + String logPath;//日志存储路径 + public DynamicLogger(String logPath) { + this.logPath = logPath; + } + //对外暴露日志对象:每次拿的对象从内存里拿,没有再构建 + private static Map container = new HashMap<>(); + public Logger getLogger(String dynamicName) { + Logger logger = container.get(dynamicName); + if(logger != null) { + return logger; + } + logger = build(dynamicName); + container.put(dynamicName,logger); + return logger; + } + //构建Logger对象,给Logger指定appender + private Logger build(String dynamicName) { + RollingFileAppender runTaskAppender =new DynamicLogAppender().getAppender(this.logPath,dynamicName); + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + Logger logger = context.getLogger(dynamicName); + logger.addAppender(runTaskAppender); + return logger; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Indexer.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Indexer.java new file mode 100644 index 0000000..fa22002 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Indexer.java @@ -0,0 +1,184 @@ +package org.nl.config.lucene; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.io.FileUtils; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.springframework.beans.factory.annotation.Value; +import org.wltea.analyzer.lucene.IKAnalyzer; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.Set; + +/** + * lucene索引器 + */ +public class Indexer { + /** + * 写索引实例 + */ + private IndexWriter writer; + + public IndexWriter getWriter() { + return writer; + } + + /** + * 构造方法,实例化IndexWriter + * + * @param indexDir + * @throws Exception + */ + public Indexer(String indexDir) throws Exception { + Directory dir = FSDirectory.open(Paths.get(indexDir)); + //标准分词器,会自动去掉空格啊,is a the等单词 +// Analyzer analyzer = new StandardAnalyzer(); + Analyzer analyzer = new IKAnalyzer(); + //将标准分词器配到写索引的配置中 + IndexWriterConfig config = new IndexWriterConfig(analyzer); + //实例化写索引对象 + writer = new IndexWriter(dir, config); + } + + /** + * 索引指定目录下的所有文件 + * + * @param dataDir + * @return + * @throws Exception + */ + public int indexAll(String dataDir) throws Exception { + // 获取该路径下的所有文件 + File[] files = new File(dataDir).listFiles(); + if (null != files) { + for (File file : files) { + //调用下面的indexFile方法,对每个文件进行索引 + indexFile(file); + } + } + //返回索引的文件数 +// return writer.numDocs(); + return writer.numRamDocs(); + } + + /** + * 索引指定的文件 + * + * @param file + * @throws Exception + */ + private void indexFile(File file) throws Exception { + System.out.println("索引文件的路径:" + file.getCanonicalPath()); + //调用下面的getDocument方法,获取该文件的document + Document doc = getDocument(file); + //添加索引文档 + //Document doc = json2Doc(jsonDoc); +// Document doc = new Document(); +// doc.add(new TextField("content", jsonDoc, Field.Store.YES)); + Field fieldContent = new TextField("fieldContent", FileUtils.readFileToString(null, "UTF-8"), Field.Store.YES); + + //将doc添加到索引中 + writer.addDocument(doc); + } + + /** + * 获取文档,文档里再设置每个字段,就类似于数据库中的一行记录 + * + * @param file + * @return + * @throws Exception + */ + private Document getDocument(File file) throws Exception { + Document doc = new Document(); + //开始添加字段 + //添加内容 + doc.add(new TextField("contents", new FileReader(file))); + //添加文件名,并把这个字段存到索引文件里 + doc.add(new TextField("fileName", file.getName(), Field.Store.YES)); + //添加文件路径 + doc.add(new TextField("fullPath", file.getCanonicalPath(), Field.Store.YES)); + return doc; + } + + public Document json2Doc(String strDoc) { + Document doc = new Document(); + JSONObject jsonDoc = JSONObject.parseObject(strDoc); + Set keys = jsonDoc.keySet(); + for (String key : keys) { + doc.add(new TextField(key, jsonDoc.getString(key), Field.Store.YES)); + } + return doc; + } + + public void addLogIndex(String msg) throws IOException { + //步骤一:创建Directory对象,用于指定索引库的位置 RAMDirectory内存 + Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath()); + //步骤二:创建一个IndexWriter对象,用于写索引 +// Analyzer analyzer = new StandardAnalyzer(); + IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(false))); +// indexWriter.deleteAll();//清理所有索引库 +// IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer())); + //记录索引开始时间 + long startTime = System.currentTimeMillis(); + //步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象 + Document document = new Document(); +// document.add(new TextField("fieldContent", device_id, Field.Store.YES)); + document.add(new TextField("fieldContent", msg, Field.Store.YES)); + indexWriter.addDocument(document); + //记录索引结束时间 + long endTime = System.currentTimeMillis(); + System.out.println("建立索引" + "共耗时" + (endTime - startTime) + "毫秒"); + indexWriter.commit(); + //步骤八:关闭资源 + indexWriter.close(); + System.out.println("建立索引成功-----关闭资源"); + } + + //系统的日志文件路径 + @Value("${logging.file.path}") + private String logUrl; + + public static void main(String[] args) throws IOException { + //步骤一:创建Directory对象,用于指定索引库的位置 RAMDirectory内存 + Directory directory = FSDirectory.open(new File("D:\\lucene\\index").toPath()); + //步骤二:创建一个IndexWriter对象,用于写索引 +// Analyzer analyzer = new StandardAnalyzer(); + IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new IKAnalyzer(false))); + + indexWriter.deleteAll();//清理所有索引库 +// indexWriter=new IndexWriter(directory,new IndexWriterConfig(new StandardAnalyzer())); + //记录索引开始时间 + long startTime = System.currentTimeMillis(); + //步骤三:读取磁盘中文件,对应每一个文件创建一个文档对象 + File file = new File("D:\\testlog"); + //步骤四:获取文件列表 + File[] files = file.listFiles(); + for (File item : files) { + BufferedReader bufferedReader = new BufferedReader(new FileReader(item)); + String strLine = null; + while (null != (strLine = bufferedReader.readLine())) { + Document document = new Document(); +// document.add(new Field()); + document.add(new TextField("fieldContent", strLine, Field.Store.YES)); + indexWriter.addDocument(document); + } + } + //记录索引结束时间 + long endTime = System.currentTimeMillis(); + System.out.println("建立索引" + "共耗时" + (endTime - startTime) + "毫秒"); + indexWriter.commit(); + //步骤八:关闭资源 + indexWriter.close(); + System.out.println("建立索引成功-----关闭资源"); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/LuceneIndexWriter.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/LuceneIndexWriter.java new file mode 100644 index 0000000..fb739ce --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/LuceneIndexWriter.java @@ -0,0 +1,60 @@ +package org.nl.config.lucene; + +import cn.hutool.core.date.DateUtil; +import org.apache.lucene.index.CorruptIndexException; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.wltea.analyzer.lucene.IKAnalyzer; + +import java.io.File; +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class LuceneIndexWriter { + private static IndexWriter indexWriter; + + static { + try { + Directory directory = FSDirectory.open(new File(UrlConfig.luceneUrl).toPath()); + IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer()); + indexWriter = new IndexWriter(directory, config); + } catch (Exception e) { + e.printStackTrace(); + } + /**当当前线程结束时,自动关闭IndexWriter,使用Runtime对象*/ + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + closeIndexWriter(); + } catch (Exception e) { + e.printStackTrace(); + } + })); + } + /**在线程结束时,自动关闭IndexWriter*/ + public static IndexWriter getIndexWriter() { + return indexWriter; + } + /**关闭IndexWriter + * @throws IOException + * @throws CorruptIndexException */ + public static void closeIndexWriter() throws Exception { + if(indexWriter != null) { + indexWriter.close(); + } + } + + public static void main(String[] args) throws IOException { + indexWriter.deleteAll(); + } + + public static String getDate(String timeString) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");//时间格式 + Date date = sdf.parse(timeString); + timeString = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");//格式化后的时间 + return timeString; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Searcher.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Searcher.java new file mode 100644 index 0000000..75284ee --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/Searcher.java @@ -0,0 +1,140 @@ +package org.nl.config.lucene; + +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.*; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.apache.lucene.util.BytesRef; + +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +/** + * lucene查询器 + */ +@Slf4j +public class Searcher { + + public static Map search(String indexDir, String ext,Map whereJson) throws Exception { + //获取要查询的路径,也就是索引所在的位置 + Directory dir = FSDirectory.open(Paths.get(indexDir)); + IndexReader reader = DirectoryReader.open(dir); + //构建IndexSearcher + IndexSearcher searcher = new IndexSearcher(reader); + //标准分词器,会自动去掉空格啊,is a the等单词 +// Analyzer analyzer = new StandardAnalyzer(); +// Analyzer analyzer = new IKAnalyzer(false); + //查询解析器 +// QueryParser queryParser = new QueryParser("fieldContent", analyzer); + + //记录索引开始时间 + long startTime = System.currentTimeMillis(); + // 实际上Lucene本身不支持分页。因此我们需要自己进行逻辑分页。我们要准备分页参数: + int pageSize = Integer.parseInt(whereJson.get("size").toString());// 每页条数 + int pageNum = Integer.parseInt(whereJson.get("page").toString());// 当前页码 + int start = pageNum * pageSize;// 当前页的起始条数 + int end = start + pageSize;// 当前页的结束条数(不能包含) + // 创建排序对象,需要排序字段SortField,参数:字段的名称、字段的类型、是否反转如果是false,升序。true降序 + Sort sort = new Sort(new SortField("logTime", SortField.Type.DOC,true)); + + TopDocs docs = null; + BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder(); + //时间范围查询 + String startDate = (String) whereJson.get("begin_time"); + String endDate = (String) whereJson.get("end_time"); + Calendar calendar=Calendar.getInstance(); + calendar.set(1970, 0, 1); + if (startDate == null){ + startDate = DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss.SSS"); + }else{ + startDate = LuceneIndexWriter.getDate(startDate); + } + if (endDate == null){ + endDate = DateUtil.format(new DateTime(),"yyyy-MM-dd HH:mm:ss.SSS"); + } else { + endDate = LuceneIndexWriter.getDate(endDate); + } + TermRangeQuery termRangeQuery = new TermRangeQuery("logTime", new BytesRef(startDate), new BytesRef(endDate), true, true); + booleanQueryBuilder.add(termRangeQuery,BooleanClause.Occur.MUST); + if (whereJson.get("device_code") != null){ + Query termQuery = new TermQuery(new Term("device_code", (String) whereJson.get("device_code"))); + booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST); + } + if (whereJson.get("method") != null){ + Query termQuery = new TermQuery(new Term("method", (String) whereJson.get("method"))); + booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST); + } + if (whereJson.get("status_code") != null){ + Query termQuery = new TermQuery(new Term("status_code", (String) whereJson.get("status_code"))); + booleanQueryBuilder.add(termQuery,BooleanClause.Occur.MUST); + } + if (whereJson.get("requestparam") != null){ + WildcardQuery query = new WildcardQuery(new Term("requestparam", "*"+(String) whereJson.get("requestparam")+"*")); + booleanQueryBuilder.add(query,BooleanClause.Occur.MUST); + } + if (whereJson.get("responseparam") != null){ + WildcardQuery query = new WildcardQuery(new Term("responseparam", "*"+(String) whereJson.get("responseparam")+"*")); + booleanQueryBuilder.add(query,BooleanClause.Occur.MUST); + } + if (whereJson.get("blurry") != null) { + WildcardQuery query = new WildcardQuery(new Term("fieldContent", "*"+(String) whereJson.get("blurry")+"*")); + booleanQueryBuilder.add(query, BooleanClause.Occur.MUST); + } + docs = searcher.search(booleanQueryBuilder.build(), end,sort); + //记录索引时间 + long endTime = System.currentTimeMillis(); + log.info("匹配{}共耗时{}毫秒",booleanQueryBuilder.build(),(endTime-startTime)); + log.info("查询到{}条日志文件", docs.totalHits.value); + List list = new ArrayList<>(); + ScoreDoc[] scoreDocs = docs.scoreDocs; + if (end > docs.totalHits.value) end = (int) docs.totalHits.value; + JSONArray array = new JSONArray(); + + for (int i = start; i < end; i++) { + ScoreDoc scoreDoc = scoreDocs[i]; + Document doc = reader.document(scoreDoc.doc); + JSONObject object = new JSONObject(); + object.put("content",doc.get("fieldContent")); + object.put("device_code",doc.get("device_code")); + object.put("logTime",doc.get("logTime")); + object.put("method",doc.get("method")); + object.put("status_code",doc.get("status_code")); + object.put("requestparam",doc.get("requestparam")); + object.put("responseparam",doc.get("responseparam")); + if(doc.get("fieldContent") != null) { + array.add(object); + } + } + for(Object logDto:array){ + log.info(logDto.toString()); + } + reader.close(); + JSONObject jo = new JSONObject(); + jo.put("content", array); + jo.put("totalElements", docs.totalHits.value); + return jo; + } + + public static void main(String[] args) { + String indexDir = "D:\\lucene\\index"; + //查询这个字符串 + String q = "07.832"; + Map whereJson = null; + try { + search(indexDir, q,whereJson); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/StaticConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/StaticConfig.java new file mode 100644 index 0000000..c7958bb --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/StaticConfig.java @@ -0,0 +1,21 @@ +package org.nl.config.lucene; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @deprecated 设置静态参数初始化 + */ +@Configuration +public class StaticConfig { + //日志索引目录 + @Value("${lucene.index.path}") + private String luceneDir; + + @Bean + public int initStatic() { + UrlConfig.setLuceneUrl(luceneDir); + return 0; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/UrlConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/UrlConfig.java new file mode 100644 index 0000000..dd7ce01 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/lucene/UrlConfig.java @@ -0,0 +1,13 @@ +package org.nl.config.lucene; + +public class UrlConfig { + public static String luceneUrl; + + public static String getLuceneUrl() { + return luceneUrl; + } + + public static void setLuceneUrl(String luceneUrl) { + UrlConfig.luceneUrl = luceneUrl; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CodeGenerator.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CodeGenerator.java index eb1ace8..2e59dc3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CodeGenerator.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CodeGenerator.java @@ -55,10 +55,10 @@ public class CodeGenerator { mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); - dsc.setUrl("jdbc:mysql://192.168.81.252:3306/nl-sso-server?setUnicode=true&characterEncoding=utf8"); + dsc.setUrl("jdbc:mysql://127.0.0.1:3306/stand_lms?setUnicode=true&characterEncoding=utf8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); - dsc.setPassword("Root.123456"); + dsc.setPassword("12356"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CustomIdGenerator.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CustomIdGenerator.java new file mode 100644 index 0000000..bb53c71 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/mybatis/CustomIdGenerator.java @@ -0,0 +1,18 @@ +package org.nl.config.mybatis; + +import cn.hutool.core.util.IdUtil; +import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; +import org.springframework.stereotype.Component; + +/** + * @Author: lyd + * @Description: ID自动生成策略 + * @Date: 2023/5/4 + */ +@Component +public class CustomIdGenerator implements IdentifierGenerator { + @Override + public Number nextId(Object entity) { + return IdUtil.getSnowflake(1,1).nextId(); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/redis/RedisConvert.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/redis/RedisConvert.java new file mode 100644 index 0000000..caea9b9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/redis/RedisConvert.java @@ -0,0 +1,34 @@ +package org.nl.config.redis; + +import cn.hutool.core.util.StrUtil; +import org.mapstruct.Mapper; +import org.mapstruct.factory.Mappers; +import org.nl.system.service.redis.vo.RedisMonitorRespVO; + +import java.util.ArrayList; +import java.util.Properties; + +/** + * @Author: lyd + * @Description: redis---Spring Boot 对象转换 MapStruct + * @Date: 2022-08-04 + */ +@Mapper +public interface RedisConvert { + + RedisConvert INSTANCE = Mappers.getMapper(RedisConvert.class); + + default RedisMonitorRespVO build(Properties info, Long dbSize, Properties commandStats) { + RedisMonitorRespVO respVO = RedisMonitorRespVO.builder().info(info).dbSize(dbSize) + .commandStats(new ArrayList<>(commandStats.size())).build(); + commandStats.forEach((key, value) -> { + respVO.getCommandStats().add(RedisMonitorRespVO.CommandStat.builder() + .command(StrUtil.subAfter((String) key, "cmdstat_", false)) + .calls(Integer.valueOf(StrUtil.subBetween((String) value, "calls=", ","))) + .usec(Long.valueOf(StrUtil.subBetween((String) value, "usec=", ","))) + .build()); + }); + return respVO; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/CorsFilter.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/CorsFilter.java similarity index 98% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/CorsFilter.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/CorsFilter.java index 6ce3cfa..cc2e734 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/CorsFilter.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/CorsFilter.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.config.saconfig; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/LoginUserHandler.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/LoginUserHandler.java similarity index 94% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/LoginUserHandler.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/LoginUserHandler.java index 03d3216..2d259a7 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/LoginUserHandler.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/LoginUserHandler.java @@ -1,4 +1,4 @@ -package org.nl.config.satoken; +package org.nl.config.saconfig; import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.util.SaResult; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaInitCOnfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/SaInitCOnfig.java similarity index 92% rename from nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaInitCOnfig.java rename to nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/SaInitCOnfig.java index 09a3aaa..6a967a9 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/satoken/SaInitCOnfig.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/saconfig/SaInitCOnfig.java @@ -1,8 +1,9 @@ -package org.nl.config.satoken; +package org.nl.config.saconfig; import cn.dev33.satoken.config.SaSsoConfig; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; +import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ModelAndView; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/config/thread/ThreadPoolExecutorUtil.java b/nladmin-system/nlsso-server/src/main/java/org/nl/config/thread/ThreadPoolExecutorUtil.java index 3cb507a..00c1bfe 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/config/thread/ThreadPoolExecutorUtil.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/config/thread/ThreadPoolExecutorUtil.java @@ -16,7 +16,7 @@ package org.nl.config.thread; -import org.nl.common.utils.SpringContextHolder; +import org.nl.config.SpringContextHolder; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/controller/log/LogController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/controller/log/LogController.java deleted file mode 100644 index f8fc6b4..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/controller/log/LogController.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.nl.monitor.controller.log; - -import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.monitor.server.LogService; -import org.nl.monitor.server.log.dto.LogQuery; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年01月29日 18:55 - * @desc desc - */ - -@RestController -@RequiredArgsConstructor -@RequestMapping("/api/esLog") -public class LogController { - private final LogService esLogService; - - - @GetMapping("/labels/{type}") - @ApiOperation("获取标签") - public ResponseEntity labelsValues(@PathVariable String type) { - return new ResponseEntity<>(esLogService.getLabelsValues(type), HttpStatus.OK); - } - - @PostMapping("/query") - @ApiOperation("日志查询") - public ResponseEntity queryAll(@RequestBody LogQuery query) { - return new ResponseEntity<>(esLogService.query(query), HttpStatus.OK); - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/LogService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/LogService.java deleted file mode 100644 index 5147a08..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/LogService.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.nl.monitor.server; - -import com.alibaba.fastjson.JSONArray; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import org.nl.monitor.server.log.dto.LogQuery; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年02月07日 14:34 - * @desc desc - */ -public interface LogService { - /** - * 获取labels和values树 - * @return - */ - JSONArray getLabelsValues(String type); - - /** - * 日志查询 - * @param logQuery - * @return - */ - Page query(LogQuery logQuery); -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/TunnelServer.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/TunnelServer.java deleted file mode 100755 index 6120f2c..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/TunnelServer.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.nl.monitor.server.arthas; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.Channel; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.logging.LogLevel; -import io.netty.handler.logging.LoggingHandler; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslContextBuilder; -import io.netty.handler.ssl.util.SelfSignedCertificate; -import io.netty.util.concurrent.DefaultThreadFactory; -import io.netty.util.concurrent.Promise; -import lombok.Data; -import org.apache.commons.lang3.StringUtils; -import org.nl.common.arthas.SimpleHttpResponse; -import org.nl.config.arthas.ArthasConstants; -import org.nl.config.arthas.netty.TunnelSocketServerInitializer; -import org.nl.monitor.server.arthas.cluster.TunnelClusterStore; -import org.nl.monitor.server.arthas.dto.AgentClusterInfo; -import org.nl.monitor.server.arthas.dto.AgentInfo; -import org.nl.monitor.server.arthas.dto.ClientConnectionInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -/** - * 控制台与arthas service通过netty连接 - * arthas启动时会启动ChannelFuture channelFuture = tunnelClient.start(); - * queryEncoder.addParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER); - */ -@Data -public class TunnelServer { - private final static Logger logger = LoggerFactory.getLogger(TunnelServer.class); - - private boolean ssl; - private String host; - private int port; - private String path = ArthasConstants.DEFAULT_WEBSOCKET_PATH; - - private Map agentInfoMap = new ConcurrentHashMap(); - - private Map clientConnectionInfoMap = new ConcurrentHashMap(); - - /** - * 记录 proxy request - */ - private Map> proxyRequestPromiseMap = new ConcurrentHashMap>(); - - private EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("arthas-TunnelServer-boss", true)); - private EventLoopGroup workerGroup = new NioEventLoopGroup(new DefaultThreadFactory("arthas-TunnelServer-worker", true)); - - private Channel channel; - - /** - * 在集群部署时,保存agentId和host关系 - */ - private TunnelClusterStore tunnelClusterStore; - - /** - * 集群部署时外部连接的host - */ - private String clientConnectHost; - - /** - * 核心方法 - * @throws Exception - */ - public void start() throws Exception { - { - System.out.println("Tunnel server 启动....."); - } - // Configure SSL. - final SslContext sslCtx; - if (ssl) { - SelfSignedCertificate ssc = new SelfSignedCertificate(); - sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); - } else { - sslCtx = null; - } - ServerBootstrap b = new ServerBootstrap(); - //指定解析器 - b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) - .childHandler(new TunnelSocketServerInitializer(this, sslCtx)); - - if (StringUtils.isBlank(host)) { - channel = b.bind(port).sync().channel(); - } else { - channel = b.bind(host, port).sync().channel(); - } - logger.info("Tunnel server listen at {}:{}", host, port); - workerGroup.scheduleWithFixedDelay(() -> { - agentInfoMap.entrySet().removeIf(e -> !e.getValue().getChannelHandlerContext().channel().isActive()); - clientConnectionInfoMap.entrySet() - .removeIf(e -> !e.getValue().getChannelHandlerContext().channel().isActive()); - - // 更新集群key信息 - if (tunnelClusterStore != null && clientConnectHost != null) { - try { - for (Entry entry : agentInfoMap.entrySet()) { - tunnelClusterStore.addAgent(entry.getKey(), new AgentClusterInfo(entry.getValue(), clientConnectHost), 60 * 60, TimeUnit.SECONDS); - } - } catch (Throwable t) { - logger.error("update tunnel info error", t); - } - } - }, 60, 60, TimeUnit.SECONDS); - } - - public void stop() { - if (channel != null) { - channel.close(); - } - bossGroup.shutdownGracefully(); - workerGroup.shutdownGracefully(); - } - - public Optional findAgent(String id) { - return Optional.ofNullable(this.agentInfoMap.get(id)); - } - - public void addAgent(String id, AgentInfo agentInfo) { - agentInfoMap.put(id, agentInfo); - if (this.tunnelClusterStore != null) { - this.tunnelClusterStore.addAgent(id, new AgentClusterInfo(agentInfo, clientConnectHost), 60 * 60, TimeUnit.SECONDS); - } - } - - public AgentInfo removeAgent(String id) { - AgentInfo agentInfo = agentInfoMap.remove(id); - if (this.tunnelClusterStore != null) { - this.tunnelClusterStore.removeAgent(id); - } - return agentInfo; - } - public Optional findClientConnection(String id) { - return Optional.ofNullable(this.clientConnectionInfoMap.get(id)); - } - public void addClientConnectionInfo(String id, ClientConnectionInfo clientConnectionInfo) { - clientConnectionInfoMap.put(id, clientConnectionInfo); - } - - public ClientConnectionInfo removeClientConnectionInfo(String id) { - return this.clientConnectionInfoMap.remove(id); - } - - public void addProxyRequestPromise(String requestId, Promise promise) { - this.proxyRequestPromiseMap.put(requestId, promise); - // 把过期的proxy 请求删掉 - workerGroup.schedule(new Runnable() { - - @Override - public void run() { - removeProxyRequestPromise(requestId); - } - - }, 60, TimeUnit.SECONDS); - } - - public void removeProxyRequestPromise(String requestId) { - this.proxyRequestPromiseMap.remove(requestId); - } - - public Promise findProxyRequestPromise(String requestId) { - return this.proxyRequestPromiseMap.get(requestId); - } - - - public void setPath(String path) { - path = path.trim(); - if (!path.startsWith("/")) { - logger.warn("tunnel server path should start with / ! path: {}, try to auto add / .", path); - path = "/" + path; - } - this.path = path; - } -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/InMemoryClusterStore.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/InMemoryClusterStore.java deleted file mode 100755 index 10e90e3..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/InMemoryClusterStore.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.nl.monitor.server.arthas.cluster; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import org.nl.monitor.server.arthas.dto.AgentClusterInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cache.Cache; -import org.springframework.cache.Cache.ValueWrapper; -import org.springframework.cache.caffeine.CaffeineCache; - - -/** - * - * @author hengyunabc 2020-12-02 - * - */ -public class InMemoryClusterStore implements TunnelClusterStore { - private final static Logger logger = LoggerFactory.getLogger(InMemoryClusterStore.class); - - private Cache cache; - - @Override - public AgentClusterInfo findAgent(String agentId) { - - ValueWrapper valueWrapper = cache.get(agentId); - if (valueWrapper == null) { - return null; - } - - AgentClusterInfo info = (AgentClusterInfo) valueWrapper.get(); - return info; - } - - @Override - public void removeAgent(String agentId) { - cache.evict(agentId); - } - - @Override - public void addAgent(String agentId, AgentClusterInfo info, long timeout, TimeUnit timeUnit) { - cache.put(agentId, info); - } - - @Override - public Collection allAgentIds() { - CaffeineCache caffeineCache = (CaffeineCache) cache; - com.github.benmanes.caffeine.cache.Cache nativeCache = caffeineCache.getNativeCache(); - return (Collection) (Collection) nativeCache.asMap().keySet(); - } - - @Override - public Map agentInfo(String appName) { - CaffeineCache caffeineCache = (CaffeineCache) cache; - com.github.benmanes.caffeine.cache.Cache nativeCache = caffeineCache.getNativeCache(); - - ConcurrentMap map = (ConcurrentMap) (ConcurrentMap) nativeCache - .asMap(); - - Map result = new HashMap(); - - String prefix = appName + "_"; - for (Entry entry : map.entrySet()) { - String agentId = entry.getKey(); - if (agentId.startsWith(prefix)) { - result.put(agentId, entry.getValue()); - } - } - - return result; - - } - - public Cache getCache() { - return cache; - } - - public void setCache(Cache cache) { - this.cache = cache; - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/RedisTunnelClusterStore.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/RedisTunnelClusterStore.java deleted file mode 100755 index 1484ec1..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/RedisTunnelClusterStore.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.nl.monitor.server.arthas.cluster; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.nl.monitor.server.arthas.dto.AgentClusterInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.ValueOperations; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * - * @author hengyunabc 2020-10-27 - * - */ -public class RedisTunnelClusterStore implements TunnelClusterStore { - private final static Logger logger = LoggerFactory.getLogger(RedisTunnelClusterStore.class); - // 定义jackson对象 - private static final ObjectMapper MAPPER = new ObjectMapper(); - - private String prefix = "arthas-tunnel-agent-"; - - private StringRedisTemplate redisTemplate; - - @Override - public AgentClusterInfo findAgent(String agentId) { - try { - ValueOperations opsForValue = redisTemplate.opsForValue(); - String infoStr = opsForValue.get(prefix + agentId); - AgentClusterInfo info = MAPPER.readValue(infoStr, AgentClusterInfo.class); - return info; - } catch (Throwable e) { - logger.error("try to read agentInfo error. agentId:{}", agentId, e); - throw new RuntimeException(e); - } - } - - @Override - public void removeAgent(String agentId) { - ValueOperations opsForValue = redisTemplate.opsForValue(); - opsForValue.getOperations().delete(prefix + agentId); - } - - @Override - public void addAgent(String agentId, AgentClusterInfo info, long timeout, TimeUnit timeUnit) { - try { - ValueOperations opsForValue = redisTemplate.opsForValue(); - String infoStr = MAPPER.writeValueAsString(info); - opsForValue.set(prefix + agentId, infoStr, timeout, timeUnit); - } catch (Throwable e) { - logger.error("try to add agentInfo error. agentId:{}", agentId, e); - throw new RuntimeException(e); - } - } - - public StringRedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public void setRedisTemplate(StringRedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - @Override - public Collection allAgentIds() { - ValueOperations opsForValue = redisTemplate.opsForValue(); - - Set result = new HashSet(); - - int length = prefix.length(); - for (String value : opsForValue.getOperations().keys(prefix + "*")) { - result.add(value.substring(length)); - - } - return result; - } - - @Override - public Map agentInfo(String appName) { - try { - - ValueOperations opsForValue = redisTemplate.opsForValue(); - - Set keys = new HashSet(); - - String prefixWithAppName = prefix + appName + "_"; - - for (String value : opsForValue.getOperations().keys(prefixWithAppName + "*")) { - keys.add(value); - - } - - List values = opsForValue.getOperations().opsForValue().multiGet(keys); - - Map result = new HashMap<>(); - - Iterator iterator = values.iterator(); - - for (String key : keys) { - String infoStr = iterator.next(); - AgentClusterInfo info = MAPPER.readValue(infoStr, AgentClusterInfo.class); - String agentId = key.substring(prefix.length()); - result.put(agentId, info); - } - - return result; - } catch (Throwable e) { - logger.error("try to query agentInfo error. appName:{}", appName, e); - throw new RuntimeException(e); - } - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/TunnelClusterStore.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/TunnelClusterStore.java deleted file mode 100755 index 3f3003c..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/cluster/TunnelClusterStore.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.nl.monitor.server.arthas.cluster; - -import org.nl.monitor.server.arthas.dto.AgentClusterInfo; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.TimeUnit; - - -/** - * 保存agentId连接到哪个具体的 tunnel server,集群部署时使用 - * - * @author hengyunabc 2020-10-27 - * - */ -public interface TunnelClusterStore { - public void addAgent(String agentId, AgentClusterInfo info, long expire, TimeUnit timeUnit); - - public AgentClusterInfo findAgent(String agentId); - - public void removeAgent(String agentId); - - public Collection allAgentIds(); - - public Map agentInfo(String appName); -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentClusterInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentClusterInfo.java deleted file mode 100755 index c644541..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentClusterInfo.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.nl.monitor.server.arthas.dto; - -/** - * @author hengyunabc 2020-10-30 - * - */ -public class AgentClusterInfo { - /** - * agent本身以哪个ip连接到 tunnel server - */ - private String host; - private int port; - private String arthasVersion; - - /** - * agent 连接到的 tunnel server 的ip - */ - private String clientConnectHost; - - public AgentClusterInfo() { - - } - - public AgentClusterInfo(AgentInfo agentInfo, String clientConnectHost) { - this.host = agentInfo.getHost(); - this.port = agentInfo.getPort(); - this.arthasVersion = agentInfo.getArthasVersion(); - this.clientConnectHost = clientConnectHost; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getArthasVersion() { - return arthasVersion; - } - - public void setArthasVersion(String arthasVersion) { - this.arthasVersion = arthasVersion; - } - - public String getClientConnectHost() { - return clientConnectHost; - } - - public void setClientConnectHost(String clientConnectHost) { - this.clientConnectHost = clientConnectHost; - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentInfo.java deleted file mode 100755 index 7fe143a..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/AgentInfo.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.nl.monitor.server.arthas.dto; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.netty.channel.ChannelHandlerContext; -import lombok.Data; - -/** - *监听对象相关信息:redis会存储一份 - */ -@Data -public class AgentInfo { - - @JsonIgnore - private ChannelHandlerContext channelHandlerContext; - /** - * ip - */ - private String host; - /** - * 端口号 - */ - private int port; - /** - * 版本号 - */ - private String arthasVersion; - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/ClientConnectionInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/ClientConnectionInfo.java deleted file mode 100755 index 7ff32c7..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/arthas/dto/ClientConnectionInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.nl.monitor.server.arthas.dto; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.netty.channel.Channel; -import io.netty.channel.ChannelHandlerContext; -import io.netty.util.concurrent.Promise; -import lombok.Data; - -/** - *arthas主启动启动时Client创建socket信息 - */ -@Data -public class ClientConnectionInfo { - - @JsonIgnore - private ChannelHandlerContext channelHandlerContext; - private String host; - private int port; - - /** - * wait for agent connect - */ - @JsonIgnore - private Promise promise; - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogQuery.java deleted file mode 100644 index 96b479e..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogQuery.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.nl.monitor.server.log.dto; - -import lombok.Data; - -import java.util.Date; - -/* - * @author ZZQ - * @Date 2023/2/8 5:18 下午 - */ -@Data -public class LogQuery { - /** - * 创建时间范围查询 - */ - private Date startTime; - private Date endTime; - /** - * 追踪id - */ - private String traceId; - /** - * 日志内容模糊匹配 - */ - private String message; - /** - * 日志级别 - */ - private String logLevel; - /** - * 系统标签 - */ - private String system; - /** - * 是否只查询Http相关请求 - */ - private Boolean isRequest = Boolean.TRUE; - /** - * 是否过滤wql日志 - */ - private Boolean filterSql = Boolean.TRUE; - - private Integer size = 20; - - private Integer page = 1; -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogRepositoryDTO.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogRepositoryDTO.java deleted file mode 100644 index 6f56781..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/dto/LogRepositoryDTO.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.nl.monitor.server.log.dto; - -import lombok.Data; -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/* - * @author ZZQ - * @Date 2023/2/8 4:06 下午 - */ -@Document(indexName = "lms_log", type = "lms_log") -@Data -public class LogRepositoryDTO { - - private String message; - private String host; - private String logLevel; - private String logger; - private String requestTime; - private String requestIp; - @Id - private String id; - private String traceId; - private String requestMethod; - private String thread; - private String system; - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/impl/LogServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/impl/LogServiceImpl.java deleted file mode 100644 index a6b5eb8..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/impl/LogServiceImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.nl.monitor.server.log.impl; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ss.formula.functions.T; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.script.Script; -import org.elasticsearch.search.aggregations.AggregationBuilders; -import org.elasticsearch.search.aggregations.Aggregations; -import org.elasticsearch.search.aggregations.bucket.terms.Terms; -import org.nl.monitor.server.LogService; -import org.nl.monitor.server.log.dto.LogQuery; -import org.nl.monitor.server.log.dto.LogRepositoryDTO; -import org.nl.monitor.server.log.repository.LogRepository; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; -import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl; -import org.springframework.data.elasticsearch.core.query.FetchSourceFilter; -import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.util.List; - -/** - * @author ldjun - * @version 1.0 - * @date 2023年02月07日 14:35 - * @desc desc - */ -@Service -@RequiredArgsConstructor -public class LogServiceImpl implements LogService { - - private final LogRepository esLogRepository; - - private final ElasticsearchRestTemplate elasticsearchRestTemplate; - - @Override - public Page query(LogQuery logQuery){ - Page page = new Page<>(); - if (logQuery != null){ - BoolQueryBuilder query = QueryBuilders.boolQuery(); //requestMethod - extractedParam(logQuery, query); - Iterable all = esLogRepository.search(query, PageRequest.of(logQuery.getPage()-1,logQuery.getSize(), Sort.by("@timestamp").descending())); - page.setRecords(((AggregatedPageImpl) all).getContent()); - page.setTotal(((AggregatedPageImpl) all).getTotalElements()); - page.setPages(logQuery.getPage()); - page.setSize(logQuery.getSize()); - } - return page; - } - - - private void extractedParam(LogQuery logQuery, BoolQueryBuilder query) { - if (StringUtils.isNotEmpty(logQuery.getLogLevel())){ - query.must().add(QueryBuilders.matchQuery("logLevel", logQuery.getLogLevel())); - } - if (StringUtils.isNotEmpty(logQuery.getSystem())){ - query.must().add(QueryBuilders.matchQuery("system", logQuery.getSystem())); - } - if (logQuery.getIsRequest()){ - query.must().add(QueryBuilders.existsQuery("requestMethod")); - } - if (logQuery.getFilterSql()){ - query.mustNot().add(QueryBuilders.wildcardQuery("logger","org.nl.modules.wql.core.engine.*")); - } - query.mustNot().add(QueryBuilders.matchPhraseQuery("logger","org.elasticsearch.client.RestClient")); - if (StringUtils.isNotEmpty(logQuery.getTraceId())){ - query.must().add(QueryBuilders.matchQuery("traceId", logQuery.getTraceId())); - } - if (StringUtils.isNotEmpty(logQuery.getMessage())){ - query.must().add(QueryBuilders.matchQuery("message", logQuery.getMessage()).minimumShouldMatch("80%")); - } - if (logQuery.getEndTime()!=null ){ - String script = "doc['@timestamp'].value.millis < " + logQuery.getEndTime().getTime() + "L"; - query.must().add(QueryBuilders.scriptQuery(new Script(script))); - } - if (logQuery.getStartTime()!=null){ - String script = "doc['@timestamp'].value.millis > " + logQuery.getStartTime().getTime() + "L"; - query.must().add(QueryBuilders.scriptQuery(new Script(script))); - } - } - - - - @Override - public JSONArray getLabelsValues(String type) { - JSONArray result = new JSONArray(); - FetchSourceFilter fetchSourceFilter = new FetchSourceFilter(new String[]{type}, null); - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); - queryBuilder.withCollapseField(type+".keyword"); - queryBuilder.withSourceFilter(fetchSourceFilter); - queryBuilder.addAggregation(AggregationBuilders.terms(type).field(type+".keyword").size(100)); - Aggregations agg = elasticsearchRestTemplate.query(queryBuilder.build(), SearchResponse::getAggregations); - Terms terms = agg.get(type); - List buckets = terms.getBuckets(); - if (!CollectionUtils.isEmpty(buckets)){ - buckets.stream().map(Terms.Bucket::getKeyAsString).forEach(v-> { - JSONObject item = new JSONObject(); - item.put("label", v); - item.put("value", v); - result.add(item); - }); - } - return result; - } - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/repository/LogRepository.java b/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/repository/LogRepository.java deleted file mode 100644 index dbed650..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/monitor/server/log/repository/LogRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.nl.monitor.server.log.repository; - -import org.nl.monitor.server.log.dto.LogRepositoryDTO; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -import org.springframework.stereotype.Repository; - -/* - * @author ZZQ - * @Date 2023/2/8 4:11 下午 - */ -@Repository -public interface LogRepository extends ElasticsearchRepository { - -} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleController.java index e145871..bdfe2db 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleController.java @@ -4,13 +4,12 @@ package org.nl.system.controller.coderule; import cn.dev33.satoken.annotation.SaCheckPermission; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.coderule.ISysCodeRuleService; import org.nl.system.service.coderule.dao.SysCodeRule; -import org.nl.system.service.coderule.dto.CodeRuleQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -30,15 +29,15 @@ import java.util.Set; */ @RestController @Api(tags = "系统:编码生成") -@RequiredArgsConstructor @RequestMapping("/api/genCode") public class SysCodeRuleController { - private final ISysCodeRuleService codeRuleService; + @Autowired + private ISysCodeRuleService codeRuleService; @ApiOperation("查询编码") @GetMapping @SaCheckPermission("genCode:list") - public ResponseEntity queryAll(CodeRuleQuery form, PageQuery pageable) { + public ResponseEntity queryAll(@RequestParam Map form, PageQuery pageable) { return new ResponseEntity<>(TableDataInfo.build(codeRuleService.queryAll(form, pageable)), HttpStatus.OK); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleDetailController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleDetailController.java index 2009590..c0268dc 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleDetailController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/coderule/SysCodeRuleDetailController.java @@ -4,14 +4,13 @@ package org.nl.system.controller.coderule; import cn.dev33.satoken.annotation.SaCheckPermission; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.logging.annotation.Log; import org.nl.system.service.coderule.ISysCodeRuleDetailService; import org.nl.system.service.coderule.dao.SysCodeRuleDetail; import org.nl.system.service.coderule.dto.CodeRuleDetailQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -26,10 +25,11 @@ import org.springframework.web.bind.annotation.*; */ @Api(tags = "系统:编码详情管理") @RestController -@RequiredArgsConstructor @RequestMapping("/api/codeDetail") public class SysCodeRuleDetailController { - private final ISysCodeRuleDetailService codeDetailService; + + @Autowired + private ISysCodeRuleDetailService codeDetailService; @ApiOperation("查询编码明细") @GetMapping diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/DeptController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/DeptController.java index 9b95351..a576223 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/DeptController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/DeptController.java @@ -20,17 +20,15 @@ import cn.dev33.satoken.annotation.SaMode; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.aspect.exception.BadRequestException; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - - +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.PageUtil; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.dept.ISysDeptService; import org.nl.system.service.dept.dao.SysDept; import org.nl.system.service.dept.dto.DeptQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; @@ -45,12 +43,12 @@ import java.util.Set; * @date 2019-03-25 */ @RestController -@RequiredArgsConstructor @Api(tags = "系统:部门管理") @RequestMapping("/api/dept") public class DeptController { - private final ISysDeptService deptService; + @Autowired + private ISysDeptService deptService; @ApiOperation("查询部门") @GetMapping @@ -82,7 +80,7 @@ public class DeptController { } return new ResponseEntity<>(deptService.getSuperior(ids),HttpStatus.OK); } -// + @Log("新增部门") @ApiOperation("新增部门") @PostMapping @@ -91,19 +89,19 @@ public class DeptController { deptService.createDept(resources); return new ResponseEntity<>(HttpStatus.CREATED); } -// + @Log("修改部门") @ApiOperation("修改部门") @PutMapping // @SaCheckPermission("dept:edit") public ResponseEntity update(@Validated @RequestBody SysDept dept){ - if (dept.getPid() != null && dept.getDeptId().equals(dept.getPid())) { + if (dept.getPid() != null && dept.getDept_id().equals(dept.getPid())) { throw new BadRequestException("上级不能为自己"); } deptService.updateDept(dept); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } -// + @Log("删除部门") @ApiOperation("删除部门") @DeleteMapping diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/SysUserDeptController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/SysUserDeptController.java deleted file mode 100644 index 626ab54..0000000 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dept/SysUserDeptController.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.nl.system.controller.dept; - - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - *

- * 部门表 前端控制器 - *

- * - * @author generator - * @since 2022-12-15 - */ -@RestController -@RequestMapping("/sysUserDept") -public class SysUserDeptController { - -} - diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dict/SysDictController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dict/SysDictController.java index e3efc82..66b7adb 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dict/SysDictController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/dict/SysDictController.java @@ -1,16 +1,14 @@ package org.nl.system.controller.dict; - import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.logging.annotation.Log; import org.nl.system.service.dict.ISysDictService; import org.nl.system.service.dict.dao.Dict; import org.nl.system.service.dict.dto.DictQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -30,11 +28,11 @@ import java.util.Set; * @since 2022-12-14 */ @RestController -@RequiredArgsConstructor @RequestMapping("/api/dict") public class SysDictController { - private final ISysDictService dictService; + @Autowired + private ISysDictService dictService; @Log("查询字典") @GetMapping @@ -44,6 +42,13 @@ public class SysDictController { return new ResponseEntity<>(TableDataInfo.build(dictService.queryAll(whereJson,pageable)), HttpStatus.OK); } + @ApiOperation("查询所有字典信息") + @GetMapping(value = "/all") +// @SaCheckPermission("dict:list") + public ResponseEntity queryAll(){ + return new ResponseEntity<>(dictService.queryAll(),HttpStatus.OK); + } + @Log("新增字典") @PostMapping @ApiOperation("新增字典") diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java new file mode 100644 index 0000000..81d06da --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java @@ -0,0 +1,45 @@ +package org.nl.system.controller.generator; + + +import cn.dev33.satoken.annotation.SaIgnore; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + *

+ * 代码生成配置表 前端控制器 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@SaIgnore +@RestController +@Api(tags = "系统:代码生成管理") +@RequestMapping("api/genConfig") +public class CodeGenConfigController { + + @Autowired + private ICodeGenConfigService genConfigService; + + @ApiOperation("查询表数据") + @GetMapping(value = "/{tableName}") + public ResponseEntity query(@PathVariable String tableName){ + return new ResponseEntity<>(genConfigService.findByTableName(tableName), HttpStatus.OK); + } + + @ApiOperation("修改") + @PutMapping + public ResponseEntity update(@Validated @RequestBody CodeGenConfig genConfig){ + return new ResponseEntity<>(genConfigService.update(genConfig.getTable_name(), genConfig),HttpStatus.OK); + } +} + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java new file mode 100644 index 0000000..cc48b9d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java @@ -0,0 +1,91 @@ +package org.nl.system.controller.generator; + +import cn.dev33.satoken.annotation.SaIgnore; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.ICodeGeneratorService; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + *

+ * 列的数据信息表 前端控制器 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@SaIgnore +@RestController +@RequestMapping("/api/generator") +@Api(tags = "系统:代码生成管理") +public class CodeGeneratorController { + @Autowired + private ICodeGeneratorService generatorService; + @Autowired + private ICodeGenConfigService genConfigService; + + @Value("${generator.enabled}") + private Boolean generatorEnabled; + + @ApiOperation("查询数据库数据") + @GetMapping(value = "/tables") + public ResponseEntity queryTables(@RequestParam(defaultValue = "") String name, PageQuery pageable){ + return new ResponseEntity<>(TableDataInfo.build(generatorService.getTables(name, pageable)), HttpStatus.OK); + } + + @ApiOperation("查询字段数据") + @GetMapping(value = "/columns") + public ResponseEntity queryColumns(@RequestParam String tableName){ + return new ResponseEntity<>(TableDataInfo.build(generatorService.getColumns(tableName)), HttpStatus.OK); + } + + @ApiOperation("批量修改字段数据") + @PutMapping + public ResponseEntity save(@RequestBody List columnInfos){ + generatorService.updateBatchById(columnInfos); + return new ResponseEntity<>(HttpStatus.OK); + } + + @ApiOperation("同步字段数据") + @PostMapping(value = "sync") + public ResponseEntity sync(@RequestBody List tables){ + for (String table : tables) { + generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); + } + return new ResponseEntity<>(HttpStatus.OK); + } + + @ApiOperation("生成代码") + @PostMapping(value = "/{tableName}/{type}") + public ResponseEntity generator(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){ + if(!generatorEnabled && type == 0){ + throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); + } + switch (type){ + // 生成代码 + case 0: generatorService.generator(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName)); + break; + // 预览 + case 1: return generatorService.preview(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName)); + // 打包 + case 2: generatorService.download(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName), request, response); + break; + default: throw new BadRequestException("没有这个选项"); + } + return new ResponseEntity<>(HttpStatus.OK); + } +} + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logging/SysLogController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logging/SysLogController.java new file mode 100644 index 0000000..5323312 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logging/SysLogController.java @@ -0,0 +1,81 @@ +package org.nl.system.controller.logging; + + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; +import org.nl.common.utils.SecurityUtils; +import org.nl.system.service.logging.ISysLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + *

+ * 系统日志 前端控制器 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@RestController +@RequestMapping("/api/logs") +@Api(tags = "系统:日志管理") +public class SysLogController { + @Autowired + private ISysLogService logService; + @GetMapping + @ApiOperation("日志查询") + //@SaCheckPermission("@el.check()") + public ResponseEntity query(@RequestParam Map criteria, PageQuery pageable){ + criteria.put("log_type","INFO"); + return new ResponseEntity<>(TableDataInfo.build(logService.queryAll(criteria,pageable)), HttpStatus.OK); + } + + @GetMapping(value = "/user") + // @ApiOperation("用户日志查询") + public ResponseEntity queryUserLog(@RequestParam Map criteria, PageQuery pageable){ + criteria.put("log_type","INFO"); + criteria.put("username", SecurityUtils.getCurrentUsername()); + return new ResponseEntity<>(TableDataInfo.build(logService.queryAll(criteria,pageable)), HttpStatus.OK); + } + + @GetMapping(value = "/error") + @ApiOperation("错误日志查询") + // @SaCheckPermission("@el.check()") + public ResponseEntity queryErrorLog(@RequestParam Map criteria, PageQuery pageable){ + criteria.put("log_type","ERROR"); + return new ResponseEntity<>(TableDataInfo.build(logService.queryAll(criteria,pageable)), HttpStatus.OK); + } + + @GetMapping(value = "/error/{id}") + @ApiOperation("日志异常详情查询") + // @SaCheckPermission("@el.check()") + public ResponseEntity queryErrorLogs(@PathVariable String id){ + return new ResponseEntity<>(logService.findByErrDetail(id), HttpStatus.OK); + } + + @DeleteMapping(value = "/del/error") + @Log("删除所有ERROR日志") + @ApiOperation("删除所有ERROR日志") + // @SaCheckPermission("@el.check()") + public ResponseEntity delAllErrorLog(){ + logService.delAllByError(); + return new ResponseEntity<>(HttpStatus.OK); + } + + @DeleteMapping(value = "/del/info") + @Log("删除所有INFO日志") + @ApiOperation("删除所有INFO日志") + // @SaCheckPermission("@el.check()") + public ResponseEntity delAllInfoLog(){ + logService.delAllByInfo(); + return new ResponseEntity<>(HttpStatus.OK); + } +} + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageController.java new file mode 100644 index 0000000..65e23de --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageController.java @@ -0,0 +1,99 @@ +package org.nl.system.controller.logicflow; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; +import org.nl.system.service.logicflow.IStageService; +import org.nl.system.service.logicflow.dao.Stage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; +import java.util.Set; + +/** + *

+ * 舞台主表 前端控制器 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Slf4j +@RestController +@Api(tags = "舞台管理") +@RequestMapping("/api/stage") +public class StageController { + + @Autowired + private IStageService stageService; + + @GetMapping + @Log("查询舞台") + @ApiOperation("查询舞台") + //@SaCheckPermission("stage:list") + public ResponseEntity query(@RequestParam Map whereJson, PageQuery page) { + return new ResponseEntity<>(TableDataInfo.build(stageService.queryAll(whereJson, page)), HttpStatus.OK); + } + + @PostMapping + @Log("新增舞台") + @ApiOperation("新增舞台") + //@SaCheckPermission("stage:add") + public ResponseEntity create(@Validated @RequestBody Stage dto) { + stageService.create(dto); + return new ResponseEntity<>(HttpStatus.CREATED); + } + + @PutMapping + @Log("修改舞台") + @ApiOperation("修改舞台") + //@SaCheckPermission("stage:edit") + public ResponseEntity update(@Validated @RequestBody Stage dto) { + stageService.update(dto); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Log("删除舞台") + @ApiOperation("删除舞台") + //@SaCheckPermission("stage:del") + @DeleteMapping + public ResponseEntity delete(@RequestBody Set ids) { + stageService.deleteAll(ids); + return new ResponseEntity<>(HttpStatus.OK); + } + + @GetMapping("/selectList") + @Log("下拉选舞台") + @ApiOperation("下拉选舞台") + //@SaCheckPermission("routePlan:list") + public ResponseEntity selectList() { + return new ResponseEntity<>(stageService.selectList(), HttpStatus.OK); + } + + @PostMapping("/addNewStage") + @Log("保存舞台数据") + @ApiOperation("保存舞台数据") + public ResponseEntity addNewStage(@Validated @RequestBody Stage dto) { + log.info("dto{}",dto); + stageService.addNewStage(dto); + return new ResponseEntity<>(HttpStatus.CREATED); + } + + @PostMapping("/getNewStageDataByCode") + @Log("根据stage_code获取舞台数据") + @ApiOperation("根据stage_code获取舞台数据") + public ResponseEntity getNewStageDataByCode(@RequestBody String code) { + Stage one = stageService.getOne(new LambdaQueryWrapper().eq(Stage::getStage_code, code)); + return new ResponseEntity<>(one, HttpStatus.CREATED); + } + +} + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageImageController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageImageController.java new file mode 100644 index 0000000..c8e5f2d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/logicflow/StageImageController.java @@ -0,0 +1,80 @@ +package org.nl.system.controller.logicflow; + + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; +import org.nl.system.service.logicflow.IStageImageService; +import org.nl.system.service.logicflow.dao.StageImage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; +import java.util.Set; + + +/** + * @Author: lyd + * @Description: 舞台图标控制层 + * @Date: 2022-07-29 + */ +@RestController +@RequiredArgsConstructor +@Api(tags = "舞台管理") +@RequestMapping("/api/stageImage") +@Slf4j +public class StageImageController { + + @Autowired + private IStageImageService stageImageService; + @GetMapping + @Log("查询舞台") + @ApiOperation("查询舞台") + //@SaCheckPermission("stageImage:list") + public ResponseEntity query(@RequestParam Map whereJson, PageQuery page) { + return new ResponseEntity<>(TableDataInfo.build(stageImageService.queryAll(whereJson, page)), HttpStatus.OK); + } + + @PostMapping + @Log("新增舞台图片") + @ApiOperation("新增舞台图片") + //@SaCheckPermission("stageImage:add") + public ResponseEntity create(@Validated @RequestBody StageImage entity) { + stageImageService.create(entity); + return new ResponseEntity<>(HttpStatus.CREATED); + } + + @PutMapping + @Log("修改舞台") + @ApiOperation("修改舞台") + //@SaCheckPermission("stageImage:edit") + public ResponseEntity update(@Validated @RequestBody StageImage entity) { + stageImageService.update(entity); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Log("删除舞台") + @ApiOperation("删除舞台") + //@SaCheckPermission("stageImage:del") + @DeleteMapping + public ResponseEntity delete(@RequestBody Set ids) { + stageImageService.deleteAll(ids); + return new ResponseEntity<>(HttpStatus.OK); + } + + @GetMapping("/selectList") + @Log("下拉选设备图标") + @ApiOperation("下拉选设备图标") + //@SaCheckPermission("routePlan:list") + public ResponseEntity selectList() { + return new ResponseEntity<>(stageImageService.selectList(), HttpStatus.OK); + } +} + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/lucence/LuceneController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/lucence/LuceneController.java new file mode 100644 index 0000000..1ee76d9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/lucence/LuceneController.java @@ -0,0 +1,35 @@ +package org.nl.system.controller.lucence; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.logging.annotation.Log; +import org.nl.system.service.lucene.LuceneService; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@Api(tags = "日志检索") +@RequestMapping("/api/lucene") +@Slf4j +public class LuceneController { + + private final LuceneService luceneService; + + @GetMapping("/getAll") + @Log("日志检索") + @ApiOperation("日志检索") + //@PreAuthorize("@el.check('task:list')") + public ResponseEntity get(@RequestParam Map whereJson, Pageable page) { + return new ResponseEntity<>(luceneService.getAll(whereJson, page), HttpStatus.OK); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/menu/SysMenuController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/menu/SysMenuController.java index c6c8def..71e5679 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/menu/SysMenuController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/menu/SysMenuController.java @@ -5,16 +5,16 @@ import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaMode; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONObject; -import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; -import org.nl.common.domain.query.PageQuery; +import io.swagger.annotations.ApiOperation; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.menu.ISysMenuService; import org.nl.system.service.menu.dao.SysMenu; import org.nl.system.service.menu.dto.MenuDto; import org.nl.system.service.menu.dto.MenuQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -33,9 +33,9 @@ import java.util.stream.Collectors; */ @RestController @RequestMapping("api/sysMenu") -@RequiredArgsConstructor public class SysMenuController { - private final ISysMenuService iSysMenuService; + @Autowired + private ISysMenuService iSysMenuService; @GetMapping(value = "/build") @ApiOperation("根据用户获取菜单") @@ -68,7 +68,7 @@ public class SysMenuController { List menuList = iSysMenuService.getMenus(id); menuSet.add(iSysMenuService.findById(id)); menuSet = iSysMenuService.getChildMenus(menuList, menuSet); - Set ids = menuSet.stream().map(SysMenu::getMenuId).collect(Collectors.toSet()); + Set ids = menuSet.stream().map(SysMenu::getMenu_id).collect(Collectors.toSet()); return new ResponseEntity<>(ids, HttpStatus.OK); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/monitor/MonitorController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/monitor/MonitorController.java new file mode 100644 index 0000000..092e749 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/monitor/MonitorController.java @@ -0,0 +1,47 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.system.controller.monitor; + +import cn.dev33.satoken.annotation.SaCheckPermission; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.nl.system.service.monitor.MonitorService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Zheng Jie + * @date 2020-05-02 + */ +@RestController +@RequiredArgsConstructor +@Api(tags = "系统-服务监控管理") +@RequestMapping("/api/monitor") +public class MonitorController { + + private final MonitorService serverService; + + @GetMapping + @ApiOperation("查询服务监控") + @SaCheckPermission("monitor:list") + public ResponseEntity query() { + return new ResponseEntity<>(serverService.getServers(),HttpStatus.OK); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/notice/SysNoticeController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/notice/SysNoticeController.java new file mode 100644 index 0000000..5d63042 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/notice/SysNoticeController.java @@ -0,0 +1,107 @@ +package org.nl.system.controller.notice; + +import com.alibaba.fastjson.JSONObject; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; +import org.nl.system.service.notice.ISysNoticeService; +import org.nl.system.service.notice.dao.SysNotice; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; +import java.util.Set; +/** +* @author lyd +* @date 2023-05-09 +**/ +@Slf4j +@RestController +@Api(tags = "消息通知管理") +@RequestMapping("/api/notice") +public class SysNoticeController { + + @Autowired + private ISysNoticeService noticeService; + + @GetMapping + @Log("查询消息通知") + @ApiOperation("查询消息通知") + //@SaCheckPermission("@el.check('sysNotice:list')") + public ResponseEntity query(@RequestParam Map whereJson, PageQuery page){ + return new ResponseEntity<>(TableDataInfo.build(noticeService.queryAll(whereJson,page)),HttpStatus.OK); + } + + @PostMapping + @Log("新增消息通知") + @ApiOperation("新增消息通知") + //@SaCheckPermission("@el.check('sysNotice:add')") + public ResponseEntity create(@Validated @RequestBody SysNotice entity){ + noticeService.create(entity); + return new ResponseEntity<>(HttpStatus.CREATED); + } + + @PutMapping + @Log("修改消息通知") + @ApiOperation("修改消息通知") + //@SaCheckPermission("@el.check('sysNotice:edit')") + public ResponseEntity update(@Validated @RequestBody SysNotice entity){ + noticeService.update(entity); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Log("删除消息通知") + @ApiOperation("删除消息通知") + //@SaCheckPermission("@el.check('sysNotice:del')") + @DeleteMapping + public ResponseEntity delete(@RequestBody Set ids) { + noticeService.deleteAll(ids); + return new ResponseEntity<>(HttpStatus.OK); + } + + @Log("获取未读的接收消息条数") + @GetMapping("/countByReceiveNotRead") + public ResponseEntity countByReceiveNotRead(){ + return new ResponseEntity<>(noticeService.countByReceiveNotRead(), HttpStatus.OK); + } + + @Log("接收消息分页") + @GetMapping("/pageByReceive") + public ResponseEntity pageByReceive(){ + return new ResponseEntity<>(noticeService.pageByReceive(), HttpStatus.OK); + } + + @Log("标为已读") + @PostMapping("/read") + public ResponseEntity read(@RequestBody String id){ + noticeService.read(id); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Log("消息详情") + @PostMapping("/findById") + public ResponseEntity findById(@RequestBody String id){ + return new ResponseEntity<>(noticeService.getById(id), HttpStatus.OK); + } + + @Log("修改已处理") + @PostMapping("/deal") + public ResponseEntity deal(@RequestBody String id){ + noticeService.deal(id); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Log("批量已读") + @PostMapping("/changeRead") + @ApiOperation("批量已读") + public ResponseEntity changeRead(@RequestBody JSONObject jsonObject) { + noticeService.changeRead(jsonObject); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/param/SysParamController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/param/SysParamController.java index c6902ac..b78ffb0 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/param/SysParamController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/param/SysParamController.java @@ -3,14 +3,13 @@ package org.nl.system.controller.param; import cn.dev33.satoken.annotation.SaIgnore; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.logging.annotation.Log; import org.nl.system.service.param.ISysParamService; import org.nl.system.service.param.dao.Param; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -32,10 +31,10 @@ import java.util.Map; @Slf4j @RestController @RequestMapping("/api/param") -@RequiredArgsConstructor class SysParamController { - private final ISysParamService paramService; + @Autowired + private ISysParamService paramService; @GetMapping @Log("查询系统参数") @ApiOperation("查询系统参数") diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/permission/SysDataPermissionController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/permission/SysDataPermissionController.java index 73135bb..4a94366 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/permission/SysDataPermissionController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/permission/SysDataPermissionController.java @@ -4,15 +4,14 @@ package org.nl.system.controller.permission; import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.logging.annotation.Log; import org.nl.system.service.permission.ISysDataPermissionService; import org.nl.system.service.permission.dao.SysDataPermission; import org.nl.system.service.permission.dto.SysDataPermissionQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -30,12 +29,12 @@ import java.util.Set; */ @Slf4j @RestController -@RequiredArgsConstructor @Api(tags = "数据管理") @RequestMapping("/api/dataPermission") public class SysDataPermissionController { - private final ISysDataPermissionService dataPermissionService; + @Autowired + private ISysDataPermissionService dataPermissionService; @GetMapping @Log("查询数据权限") diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/quartz/SysQuartzJobController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/quartz/SysQuartzJobController.java index ccf957f..1b6bdf2 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/quartz/SysQuartzJobController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/quartz/SysQuartzJobController.java @@ -4,16 +4,15 @@ package org.nl.system.controller.quartz; import cn.dev33.satoken.annotation.SaCheckPermission; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.common.annotation.Log; -import org.nl.common.aspect.exception.BadRequestException; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.exception.BadRequestException; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.quartz.ISysQuartzJobService; import org.nl.system.service.quartz.dao.SysQuartzJob; import org.nl.system.service.quartz.dto.JobQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -31,13 +30,13 @@ import java.util.Set; */ @Slf4j @RestController -@RequiredArgsConstructor @RequestMapping("/api/jobs") @Api(tags = "系统:定时任务管理") public class SysQuartzJobController { private static final String ENTITY_NAME = "quartzJob"; - private final ISysQuartzJobService quartzJobService; + @Autowired + private ISysQuartzJobService quartzJobService; @ApiOperation("查询定时任务") @GetMapping @@ -58,7 +57,7 @@ public class SysQuartzJobController { @PostMapping @SaCheckPermission("timing:add") public ResponseEntity create(@Validated @RequestBody SysQuartzJob resources) { - if (resources.getJobId() != null) { + if (resources.getJob_id() != null) { throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID"); } quartzJobService.createJob(resources); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/redis/RedisController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/redis/RedisController.java new file mode 100644 index 0000000..ec89c86 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/redis/RedisController.java @@ -0,0 +1,57 @@ +package org.nl.system.controller.redis; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.logging.annotation.Log; +import org.nl.system.service.redis.RedisService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +/** + * @Author: lyd + * @Description: Redis监控管理 + * @Date: 2022-08-04 + */ +@RestController +@RequiredArgsConstructor +@Api(tags = "系统表格管理") +@RequestMapping("/api/redis") +@Slf4j +public class RedisController { + + private final RedisService redisService; + + @GetMapping("/get-monitor-info") + @Log("查询redis的信息") + @ApiOperation("查询redis的信息") + public ResponseEntity getRedisMonitorInfo() { + return new ResponseEntity<>(redisService.getRedisMonitorInfo(),HttpStatus.OK); + } + + @GetMapping("/get-key-define-list") + @Log("获得 Redis Key 模板列表") + @ApiOperation("获得 Redis Key 模板列表") + public ResponseEntity getKeyDefineList() { + return new ResponseEntity<>(redisService.getKeyDefineList(),HttpStatus.OK); + } + + @GetMapping("/get-key-value-list") + @Log("获得 Redis Key Value列表") + @ApiOperation("获得 Redis Key Value列表") + public ResponseEntity getKeyValueList() { + return new ResponseEntity<>( redisService.getKeyValueList(),HttpStatus.OK); + } + + @Log("根据key删除Redis数据") + @ApiOperation("根据key删除Redis数据") + @DeleteMapping + public ResponseEntity deleteByKey(@RequestBody String[] ids) { + redisService.deleteByKey(ids); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/role/SysRoleController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/role/SysRoleController.java index 29b9311..2eacfa3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/role/SysRoleController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/role/SysRoleController.java @@ -3,12 +3,11 @@ package org.nl.system.controller.role; import cn.dev33.satoken.annotation.SaCheckPermission; import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.logging.annotation.Log; import org.nl.system.service.role.ISysRoleService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -26,10 +25,10 @@ import java.util.Set; */ @RestController @RequestMapping("/api/sysRole") -@RequiredArgsConstructor public class SysRoleController { - private final ISysRoleService roleService; + @Autowired + private ISysRoleService roleService; @ApiOperation("分页查询角色") @GetMapping diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/secutiry/AuthorizationController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/secutiry/AuthorizationController.java index eddafce..321bfa3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/secutiry/AuthorizationController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/secutiry/AuthorizationController.java @@ -1,18 +1,4 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * 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 org.nl.system.controller.secutiry; @@ -23,24 +9,22 @@ import com.alibaba.fastjson.JSONObject; import com.wf.captcha.base.Captcha; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.nl.common.utils.RedisUtils; import org.nl.common.utils.SecurityUtils; -import org.nl.system.service.dept.ISysDeptService; -import org.nl.system.service.dept.dao.SysDept; -import org.nl.system.service.secutiry.dto.LoginCodeEnum; -import org.nl.system.service.secutiry.dto.LoginProperties; +import org.nl.common.utils.dto.CurrentUser; +import org.nl.common.security.config.bean.LoginCodeEnum; +import org.nl.common.security.config.bean.LoginProperties; import org.nl.system.service.secutiry.impl.OnlineUserService; -import org.nl.system.service.user.dto.CurrentUser; +import org.nl.system.service.user.ISysUserService; +import org.nl.system.service.user.dao.SysUser; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -52,21 +36,22 @@ import java.util.concurrent.TimeUnit; @Slf4j @RestController @RequestMapping("/auth") -@RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { - private final RedisUtils redisUtils; - private final OnlineUserService onlineUserService; - private final ISysDeptService deptService; - - @Resource + @Autowired + private RedisUtils redisUtils; + @Autowired + private OnlineUserService onlineUserService; + @Autowired + private ISysUserService userService; + @Autowired private LoginProperties loginProperties; @ApiOperation("登录授权") @PostMapping(value = "/login") public ResponseEntity login(@RequestBody Map authMap) throws Exception { if (ObjectUtil.isEmpty(authMap)){ - return ResponseEntity.noContent().build(); + return ResponseEntity.noContent().build(); } return ResponseEntity.ok(onlineUserService.login(authMap)); } @@ -79,10 +64,6 @@ public class AuthorizationController { JSONObject jsonObject = new JSONObject(); jsonObject.put("roles", SecurityUtils.getCurrentUserPermissions()); jsonObject.put("user", currentUser.getUser()); - //TODO:添加部门 - List depts = deptService.getUserDeptRelation(currentUser.getId()); - jsonObject.put("depts",depts); - return ResponseEntity.ok(jsonObject); } @@ -90,9 +71,8 @@ public class AuthorizationController { @GetMapping(value = "/userInfo") public ResponseEntity getUserInfo(Long loginId) { if (loginId != null){ -// WQLObject userTab = WQLObject.getWQLObject("sys_user"); -// JSONObject user = userTab.query("user_id = '" + loginId + "'").uniqueResult(0); - return ResponseEntity.ok(null); + SysUser user = userService.getById(loginId); + return ResponseEntity.ok(user); } return ResponseEntity.noContent().build(); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/tools/ToolLocalStorageController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/tools/ToolLocalStorageController.java index 8f9bf37..e042e03 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/tools/ToolLocalStorageController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/tools/ToolLocalStorageController.java @@ -5,16 +5,15 @@ import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaIgnore; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.aspect.exception.BadRequestException; -import org.nl.common.domain.TableDataInfo; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; - +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.FileUtil; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.tools.IToolLocalStorageService; import org.nl.system.service.tools.dao.ToolLocalStorage; import org.nl.system.service.tools.dto.ToolLocalStorageQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -32,11 +31,11 @@ import java.util.Set; * @since 2022-12-20 */ @RestController -@RequiredArgsConstructor @Api(tags = "工具:本地存储管理") @RequestMapping("/api/localStorage") public class ToolLocalStorageController { - private final IToolLocalStorageService localStorageService; + @Autowired + private IToolLocalStorageService localStorageService; @ApiOperation("查询文件") @GetMapping diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/OnlineController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/OnlineController.java index e043d2c..567898e 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/OnlineController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/OnlineController.java @@ -17,9 +17,9 @@ package org.nl.system.controller.user; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; import org.nl.common.utils.EncryptUtils; import org.nl.system.service.secutiry.impl.OnlineUserService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -33,12 +33,12 @@ import java.util.Set; * @author Zheng Jie */ @RestController -@RequiredArgsConstructor @RequestMapping("/auth/online") @Api(tags = "系统:在线用户管理") public class OnlineController { - private final OnlineUserService onlineUserService; + @Autowired + private OnlineUserService onlineUserService; @ApiOperation("查询在线用户") @GetMapping diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/UserController.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/UserController.java index 1398405..c9204a5 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/UserController.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/controller/user/UserController.java @@ -18,18 +18,19 @@ package org.nl.system.controller.user; import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.StpUtil; import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; -import org.nl.common.annotation.Log; -import org.nl.common.aspect.exception.BadRequestException; +import org.nl.common.base.TableDataInfo; import org.nl.common.domain.query.PageQuery; +import org.nl.config.RsaProperties; +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.RsaUtils; import org.nl.common.utils.SecurityUtils; - -import org.nl.config.other.RsaProperties; +import org.nl.common.logging.annotation.Log; import org.nl.system.service.user.ISysUserService; import org.nl.system.service.user.dao.SysUser; import org.nl.system.service.user.dto.UserQuery; @@ -53,13 +54,13 @@ import java.util.Set; public class UserController { @Autowired - ISysUserService userService; + private ISysUserService userService; @ApiOperation("查询用户") @GetMapping public ResponseEntity query(UserQuery query, PageQuery page){ - return new ResponseEntity(userService.getUserDetail(query, page),HttpStatus.OK); + return new ResponseEntity(TableDataInfo.build(userService.getUserDetail(query, page)),HttpStatus.OK); } @Log("新增用户") @@ -84,7 +85,7 @@ public class UserController { @ApiOperation("修改用户:个人中心") // @PutMapping(value = "center") public ResponseEntity center(@RequestBody SysUser resources){ - if(!resources.getUserId().equals(StpUtil.getLoginIdAsLong())){ + if(!resources.getUser_id().equals(StpUtil.getLoginIdAsLong())){ throw new BadRequestException("不能修改他人资料"); } userService.saveOrUpdate(resources); @@ -103,7 +104,18 @@ public class UserController { @ApiOperation("修改密码") @PostMapping(value = "/updatePass") public ResponseEntity updatePass(@RequestBody JSONObject passVo) throws Exception { - userService.updatePass(passVo); + // 解密,得到字符密码 + String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getString("oldPass")); + String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getString("newPass")); + SysUser user = userService.getOne(new LambdaQueryWrapper().eq(SysUser::getUsername, SecurityUtils.getCurrentUsername())); + if (!SaSecureUtil.md5BySalt(user.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(oldPass, "salt"))) { + throw new BadRequestException("修改失败,旧密码错误"); + } + if (!SaSecureUtil.md5BySalt(user.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(newPass, "salt"))) { + throw new BadRequestException("新密码不能与旧密码相同"); + } + user.setPassword(SaSecureUtil.md5BySalt(newPass, "salt")); + userService.updateById(user); return new ResponseEntity<>(HttpStatus.OK); } @@ -118,7 +130,7 @@ public class UserController { @PostMapping(value = "/updateEmail/{code}") public ResponseEntity updateEmail(@PathVariable String code,@RequestBody SysUser user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword()); - SysUser userInfo = userService.getOne(new QueryWrapper().eq("username", SecurityUtils.getCurrentUsername())); + SysUser userInfo = userService.getOne(new QueryWrapper().eq("username",SecurityUtils.getCurrentUsername())); if(!SaSecureUtil.md5BySalt(userInfo.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(password, "salt"))){ throw new BadRequestException("密码错误"); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/ISysCodeRuleService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/ISysCodeRuleService.java index 4f227a2..49d63fb 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/ISysCodeRuleService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/ISysCodeRuleService.java @@ -25,7 +25,7 @@ public interface ISysCodeRuleService extends IService { * @param pageable * @return */ - IPage queryAll(CodeRuleQuery form, PageQuery pageable); + IPage queryAll(Map form, PageQuery pageable); /** * 创建编码 diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRule.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRule.java index 809302f..8563b74 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRule.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRule.java @@ -41,7 +41,7 @@ public class SysCodeRule implements Serializable { /** * 当前值 */ - private String currentValue; + private String current_value; /** * 备注 @@ -51,42 +51,42 @@ public class SysCodeRule implements Serializable { /** * 是否启用 */ - private String isActive; + private String is_active; /** * 是否删除 */ - private String isDelete; + private String is_delete; /** * 创建id */ - private String createId; + private String create_id; /** * 创建者 */ - private String createName; + private String create_name; /** * 创建时间 */ - private String createTime; + private String create_time; /** * 修改id */ - private String updateId; + private String update_id; /** * 修改者 */ - private String updateName; + private String update_name; /** * 修改时间 */ - private String updateTime; + private String update_time; @TableField(exist = false) private String demo; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRuleDetail.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRuleDetail.java index 7016de0..b85d88a 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRuleDetail.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/dao/SysCodeRuleDetail.java @@ -38,17 +38,17 @@ public class SysCodeRuleDetail implements Serializable { /** * 初始值 */ - private String initValue; + private String init_value; /** * 当前值 */ - private String currentValue; + private String current_value; /** * 允许最大值 */ - private String maxValue; + private String max_value; /** * 步长 @@ -73,7 +73,7 @@ public class SysCodeRuleDetail implements Serializable { /** * 排序号 */ - private BigDecimal sortNum; + private BigDecimal sort_num; /** * 备注 @@ -83,50 +83,50 @@ public class SysCodeRuleDetail implements Serializable { /** * 编码规则标识 */ - private String codeRuleId; + private String code_rule_id; /** * 是否启用 */ - private String isActive; + private String is_active; /** * 是否删除 */ - private String isDelete; + private String is_delete; /** * 创建id */ - private String createId; + private String create_id; /** * 创建者 */ - private String createName; + private String create_name; /** * 创建时间 */ - private String createTime; + private String create_time; /** * 修改id */ - private String updateId; + private String update_id; /** * 修改者 */ - private String updateName; + private String update_name; /** * 修改时间 */ - private String updateTime; + private String update_time; @TableField(exist = false) - private String dictName; + private String dict_name; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/impl/SysCodeRuleDetailServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/impl/SysCodeRuleDetailServiceImpl.java index 18c6d02..778f3f4 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/impl/SysCodeRuleDetailServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/coderule/impl/SysCodeRuleDetailServiceImpl.java @@ -5,21 +5,19 @@ import cn.hutool.core.util.IdUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import lombok.RequiredArgsConstructor; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.nl.common.domain.query.PageQuery; import org.nl.common.utils.SecurityUtils; +import org.nl.system.service.coderule.ISysCodeRuleDetailService; import org.nl.system.service.coderule.dao.SysCodeRuleDetail; import org.nl.system.service.coderule.dao.mapper.SysCodeRuleDetailMapper; -import org.nl.system.service.coderule.ISysCodeRuleDetailService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.nl.system.service.coderule.dto.CodeRuleDetailQuery; import org.nl.system.service.coderule.utils.CodeRuleTypeEnum; -import org.springframework.data.domain.Pageable; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; -import java.util.Map; /** *

@@ -30,15 +28,14 @@ import java.util.Map; * @since 2022-12-20 */ @Service -@RequiredArgsConstructor public class SysCodeRuleDetailServiceImpl extends ServiceImpl implements ISysCodeRuleDetailService { - - private final SysCodeRuleDetailMapper codeRuleDetailMapper; + @Autowired + private SysCodeRuleDetailMapper codeRuleDetailMapper; @Override public IPage queryAll(CodeRuleDetailQuery form, PageQuery page) { LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); - lam.eq(SysCodeRuleDetail::getCodeRuleId, form.getId()) - .orderByAsc(SysCodeRuleDetail::getSortNum); + lam.eq(SysCodeRuleDetail::getCode_rule_id, form.getId()) + .orderByAsc(SysCodeRuleDetail::getSort_num); IPage pages = new Page<>(page.getPage() + 1, page.getSize()); codeRuleDetailMapper.selectPage(pages, lam); return pages; @@ -51,19 +48,19 @@ public class SysCodeRuleDetailServiceImpl extends ServiceImpl @@ -38,15 +36,21 @@ import java.util.function.Consumer; * @since 2022-12-19 */ @Service -@RequiredArgsConstructor public class SysCodeRuleServiceImpl extends ServiceImpl implements ISysCodeRuleService { - - private final SysCodeRuleMapper codeRuleMapper; - private final SysCodeRuleDetailMapper codeRuleDetailMapper; + @Autowired + private SysCodeRuleMapper codeRuleMapper; + @Autowired + private SysCodeRuleDetailMapper codeRuleDetailMapper; @Override - public IPage queryAll(CodeRuleQuery form, PageQuery pageable) { - IPage page = this.page(pageable.build(SysCodeRule.class), form.build()); + public IPage queryAll(Map form, PageQuery pageable) { + String blurry = ObjectUtil.isNotEmpty(form.get("blurry"))?form.get("blurry").toString():null; + LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); + lam.like(ObjectUtil.isNotEmpty(blurry), SysCodeRule::getCode, blurry) + .or(ObjectUtil.isNotEmpty(blurry)) + .like(ObjectUtil.isNotEmpty(blurry), SysCodeRule::getName, blurry); + IPage page = new Page<>(pageable.getPage() + 1, pageable.getSize()); + codeRuleMapper.selectPage(page, lam); page.getRecords().forEach(sysCodeRule -> sysCodeRule.setDemo(codeDemo(MapOf.of("flag", "0", "code", sysCodeRule.getCode())))); return page; } @@ -57,7 +61,7 @@ public class SysCodeRuleServiceImpl extends ServiceImpl().eq(SysCodeRule::getCode, code)).getId(); // 如果flag = 1就执行更新数据库的操作 String flag = (String) form.get("flag"); - List ruleDetails = codeRuleDetailMapper.selectList(new LambdaQueryWrapper().eq(SysCodeRuleDetail::getCodeRuleId, id)); + List ruleDetails = codeRuleDetailMapper.selectList(new LambdaQueryWrapper().eq(SysCodeRuleDetail::getCode_rule_id, id)); String demo = ""; boolean isSame = true; for(SysCodeRuleDetail detail : ruleDetails) { @@ -65,11 +69,11 @@ public class SysCodeRuleServiceImpl extends ServiceImpl maxValue) { - numValue = detail.getInitValue(); + Long maxValue = Long.valueOf(detail.getMax_value()); + if (!isSame && (Long.valueOf(detail.getCurrent_value()) + step) > maxValue) { + numValue = detail.getInit_value(); } else { - numValue = Integer.parseInt(detail.getCurrentValue()) + step + ""; + numValue = Integer.parseInt(detail.getCurrent_value()) + step + ""; } int size = numValue.length(); int length = detail.getLength(); @@ -101,18 +105,18 @@ public class SysCodeRuleServiceImpl extends ServiceImpl= maxValue) { - numCurr = Integer.parseInt(detail.getInitValue()); - detail.setCurrentValue(String.valueOf(numCurr)); + numCurr = Integer.parseInt(detail.getInit_value()); + detail.setCurrent_value(String.valueOf(numCurr)); }else{ - detail.setCurrentValue(String.valueOf(numCurr + step)); + detail.setCurrent_value(String.valueOf(numCurr + step)); } } } @@ -134,12 +138,12 @@ public class SysCodeRuleServiceImpl extends ServiceImpl sysCodeRules = codeRuleMapper.selectList(new LambdaQueryWrapper().eq(SysCodeRule::getCode, codeRule.getCode())); if (ObjectUtil.isNotEmpty(sysCodeRules)) throw new BadRequestException("编号[" + sysCodeRules.get(0).getCode() + "]已存在"); codeRule.setId(IdUtil.getSnowflake(1,1).nextIdStr()); - codeRule.setCreateId(currentUserId); - codeRule.setCreateName(currentUsername); - codeRule.setCreateTime(now); - codeRule.setUpdateId(currentUserId); - codeRule.setUpdateName(currentUsername); - codeRule.setUpdateTime(now); + codeRule.setCreate_id(currentUserId); + codeRule.setCreate_name(currentUsername); + codeRule.setCreate_time(now); + codeRule.setUpdate_id(currentUserId); + codeRule.setUpdate_name(currentUsername); + codeRule.setUpdate_time(now); codeRuleMapper.insert(codeRule); } @@ -148,7 +152,7 @@ public class SysCodeRuleServiceImpl extends ServiceImpl ids) { ids.forEach(id -> { codeRuleMapper.deleteById(id); - codeRuleDetailMapper.delete(new LambdaQueryWrapper().eq(SysCodeRuleDetail::getCodeRuleId, id)); + codeRuleDetailMapper.delete(new LambdaQueryWrapper().eq(SysCodeRuleDetail::getCode_rule_id, id)); }); } @@ -161,9 +165,9 @@ public class SysCodeRuleServiceImpl extends ServiceImpl { * @param deptIds */ void saveUserDeptRelation(String UserId, Collection deptIds); - - List getUserDeptRelation(String UserId); - void delUserDeptRelation(String user); /** diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysDept.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysDept.java index e3c4b02..b865cf3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysDept.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysDept.java @@ -29,7 +29,7 @@ public class SysDept implements Serializable { * ID */ @TableId(value = "dept_id", type = IdType.NONE) - private String deptId; + private String dept_id; /** * 上级部门 @@ -39,7 +39,7 @@ public class SysDept implements Serializable { /** * 子部门数目 */ - private Integer subCount; + private Integer sub_count; /** * 名称 @@ -49,45 +49,45 @@ public class SysDept implements Serializable { /** * 排序 */ - private Integer deptSort; + private Integer dept_sort; /** * 状态 */ - private Boolean isUsed; + private Boolean is_used; - private String createId; + private String create_id; /** * 创建者 */ - private String createName; + private String create_name; - private String updateId; + private String update_id; /** * 更新者 */ - private String updateName; + private String update_name; /** * 创建日期 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; + private Date create_time; /** * 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date updateTime; + private Date update_time; /** * 部门编号 */ private String code; - private String extId; + private String ext_id; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysUserDept.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysUserDept.java index 48b97d8..fb29ffa 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysUserDept.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/SysUserDept.java @@ -1,7 +1,5 @@ package org.nl.system.service.dept.dao; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; @@ -26,13 +24,12 @@ public class SysUserDept implements Serializable { /** * 用户标识 */ - @TableId(value = "user_id", type = IdType.NONE) - private Long userId; + private Long user_id; /** * 部门标识 */ - private Long deptId; + private Long dept_id; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/mapper/SysDeptMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/mapper/SysDeptMapper.java index bfdc607..97d0e9b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/mapper/SysDeptMapper.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dao/mapper/SysDeptMapper.java @@ -2,7 +2,6 @@ package org.nl.system.service.dept.dao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; import org.nl.system.service.dept.dao.SysDept; import java.util.Collection; @@ -29,10 +28,6 @@ public interface SysDeptMapper extends BaseMapper { List getDeptRelation(@Param("deptIds") Collection deptIds); - - @Select("select sys_dept.* from sys_dept inner join sys_user_dept on sys_dept.dept_id = sys_user_dept.dept_id where sys_user_dept.user_id = #{user}") - List getDeptRelationByUser(@Param("user") String user); - /** * 跟新sub_count字段 * @param deptId diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptQuery.java index 6861e2f..51854f0 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptQuery.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptQuery.java @@ -23,11 +23,11 @@ public class DeptQuery extends BaseQuery { private Long pid; - private Boolean pidIsNull; + private Boolean pid_is_null; @Override public void paramMapping() { - super.doP.put("pidIsNull", QParam.builder().k(new String[]{"pid"}).type(QueryTEnum.NO).build()); - super.doP.put("deptIds", QParam.builder().k(new String[]{"deptId"}).type(QueryTEnum.IN).build()); + super.doP.put("pid_is_null", QParam.builder().k(new String[]{"pid"}).type(QueryTEnum.NO).build()); + super.doP.put("deptIds", QParam.builder().k(new String[]{"dept_id"}).type(QueryTEnum.IN).build()); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptTree.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptTree.java index 61c0323..0aaf8b8 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptTree.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/dto/DeptTree.java @@ -30,7 +30,7 @@ import java.util.List; @Setter public class DeptTree implements Serializable { - private String deptId; + private String dept_id; private String pid; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysDeptServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysDeptServiceImpl.java index 5101e5e..93ea266 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysDeptServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysDeptServiceImpl.java @@ -5,18 +5,18 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.commons.lang3.StringUtils; -import org.nl.common.aspect.exception.BadRequestException; import org.nl.common.domain.query.PageQuery; -import org.nl.common.utils.CopyUtil; -import org.nl.common.utils.IdUtil; +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.SecurityUtils; +import org.nl.common.utils.dto.CurrentUser; +import org.nl.common.domain.vo.DeptVo; +import org.nl.system.service.dept.dto.DeptTree; +import org.nl.common.utils.CopyUtil; +import org.nl.config.IdUtil; import org.nl.system.service.dept.ISysDeptService; import org.nl.system.service.dept.dao.SysDept; import org.nl.system.service.dept.dao.mapper.SysDeptMapper; import org.nl.system.service.dept.dto.DeptQuery; -import org.nl.system.service.dept.dto.DeptTree; -import org.nl.system.service.dept.dto.DeptVo; -import org.nl.system.service.user.dto.CurrentUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -34,7 +34,6 @@ import java.util.stream.Collectors; * @since 2022-12-15 */ @Service -@Transactional public class SysDeptServiceImpl extends ServiceImpl implements ISysDeptService { @Autowired @@ -63,7 +62,7 @@ public class SysDeptServiceImpl extends ServiceImpl impl trees.add(deptDTO); } for (DeptTree it : deptDtos) { - if (it.getPid() != null && deptDTO.getDeptId().equals(it.getPid())) { + if (it.getPid() != null && deptDTO.getDept_id().equals(it.getPid())) { isChild = true; if (deptDTO.getChildren() == null) { deptDTO.setChildren(new ArrayList<>()); @@ -85,18 +84,18 @@ public class SysDeptServiceImpl extends ServiceImpl impl @Override public Page queryVo(DeptQuery query, PageQuery pageQuery) { - if (query.getPidIsNull() == null){ + if (query.getPid_is_null() == null){ if (query.getPid() == null){ - query.setPidIsNull(true); + query.setPid_is_null(true); } - if (StringUtils.isNotEmpty(query.getName()) || query.getIsUsed()!=null){ - query.setPidIsNull(null); + if (StringUtils.isNotEmpty(query.getName()) || query.getIs_used()!=null){ + query.setPid_is_null(null); } } Page page = this.page(pageQuery.build(SysDept.class), query.build()); page.setRecords(CopyUtil.copyList(page.getRecords(), DeptVo.class)); - if (StringUtils.isNotEmpty(query.getName()) || query.getIsUsed()!=null){ - page.getRecords().forEach(a->((DeptVo)a).setHasChildren(false) ); + if (StringUtils.isNotEmpty(query.getName()) || query.getIs_used()!=null){ + page.getRecords().forEach(a->((DeptVo)a).setHas_children(false) ); } return page; } @@ -110,11 +109,6 @@ public class SysDeptServiceImpl extends ServiceImpl impl sysDeptMapper.saveDeptRelation(userId,deptIds); } - @Override - public List getUserDeptRelation(String user) { - return sysDeptMapper.getDeptRelationByUser(user); - } - @Override public void delUserDeptRelation(String user) { sysDeptMapper.delDeptRelation(user); @@ -123,12 +117,12 @@ public class SysDeptServiceImpl extends ServiceImpl impl @Override @Transactional(rollbackFor = Exception.class) public void updateDept(SysDept dept) { - if (dept == null ||StringUtils.isEmpty(dept.getDeptId())){ + if (dept == null ||StringUtils.isEmpty(dept.getDept_id())){ return; } this.updateById(dept); //删除节点信息 - sysDeptMapper.updateSubCount(dept.getDeptId()); + sysDeptMapper.updateSubCount(dept.getDept_id()); if (StringUtils.isNotEmpty(dept.getPid())){ sysDeptMapper.updateSubCount(dept.getPid()); } @@ -171,12 +165,11 @@ public class SysDeptServiceImpl extends ServiceImpl impl @Override @Transactional(rollbackFor = Exception.class) public void createDept(SysDept dept) { - dept.setDeptId(IdUtil.getStringId()); + dept.setDept_id(IdUtil.getStringId()); CurrentUser user = SecurityUtils.getCurrentUser(); - dept.setCreateId(user.getId()); - dept.setCreateName(user.getPresonName()); - dept.setCreateTime(new Date()); - dept.setCode(UUID.randomUUID().toString()); + dept.setCreate_id(user.getId()); + dept.setCreate_name(user.getPresonName()); + dept.setCreate_time(new Date()); this.save(dept); // 清理缓存 if (StringUtils.isNotEmpty(dept.getPid())){ diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysUserDeptServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysUserDeptServiceImpl.java index ac45fc9..e9a9774 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysUserDeptServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dept/impl/SysUserDeptServiceImpl.java @@ -5,7 +5,6 @@ import org.nl.system.service.dept.ISysUserDeptService; import org.nl.system.service.dept.dao.SysUserDept; import org.nl.system.service.dept.dao.mapper.SysUserDeptMapper; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; /** *

@@ -16,7 +15,6 @@ import org.springframework.transaction.annotation.Transactional; * @since 2022-12-15 */ @Service -@Transactional public class SysUserDeptServiceImpl extends ServiceImpl implements ISysUserDeptService { } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/ISysDictService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/ISysDictService.java index 00afc03..f56a0ba 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/ISysDictService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/ISysDictService.java @@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.service.IService; import org.nl.common.domain.query.PageQuery; import org.nl.system.service.dict.dao.Dict; import org.nl.system.service.dict.dto.DictQuery; +import org.springframework.data.domain.Pageable; import java.util.List; import java.util.Map; @@ -78,4 +79,10 @@ public interface ISysDictService extends IService { * @param id */ void deleteDetail(String id); + + /** + * 查询所有字典信息 + * @return + */ + List queryAll(); } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/Dict.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/Dict.java index 518b5bc..2010f30 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/Dict.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/Dict.java @@ -1,13 +1,13 @@ package org.nl.system.service.dict.dao; +import java.math.BigDecimal; + import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; -import java.io.Serializable; -import java.math.BigDecimal; - /** *

* 字典表 @@ -27,7 +27,7 @@ public class Dict implements Serializable { * 字典标识 */ @TableId(value = "dict_id") - private String dictId; + private String dict_id; /** * 编码 @@ -52,12 +52,12 @@ public class Dict implements Serializable { /** * 排序号 */ - private BigDecimal dictSort; + private BigDecimal dict_sort; /** * 字典类型 */ - private String dictType; + private String dict_type; /** * 参数1 @@ -77,31 +77,31 @@ public class Dict implements Serializable { /** * 创建人 */ - private String createId; + private String create_id; /** * 创建人 */ - private String createName; + private String create_name; /** * 创建时间 */ - private String createTime; + private String create_time; /** * 修改人 */ - private String updateId; + private String update_id; /** * 修改人 */ - private String updateName; + private String update_name; /** * 修改时间 */ - private String updateTime; + private String update_time; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/mapper/SysDictMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/mapper/SysDictMapper.java index 5bffec6..d83ff61 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/mapper/SysDictMapper.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dao/mapper/SysDictMapper.java @@ -1,7 +1,7 @@ package org.nl.system.service.dict.dao.mapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.nl.system.service.dict.dao.Dict; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** *

diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dto/DictQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dto/DictQuery.java index 3802779..c446f91 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dto/DictQuery.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/dto/DictQuery.java @@ -13,6 +13,6 @@ import org.nl.system.service.dict.dao.Dict; public class DictQuery extends BaseQuery { private String code; - private String dictName; - private String dictId; + private String dict_name; + private String dict_id; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/impl/SysDictServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/impl/SysDictServiceImpl.java index b89f027..ae50dfb 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/impl/SysDictServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/dict/impl/SysDictServiceImpl.java @@ -8,14 +8,14 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import lombok.RequiredArgsConstructor; -import org.nl.common.aspect.exception.BadRequestException; import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.SecurityUtils; - import org.nl.system.service.dict.ISysDictService; +import org.nl.system.service.dict.ISysDictService; import org.nl.system.service.dict.dao.Dict; import org.nl.system.service.dict.dao.mapper.SysDictMapper; import org.nl.system.service.dict.dto.DictQuery; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -32,26 +32,22 @@ import java.util.Set; * @since 2022-12-14 */ @Service -@RequiredArgsConstructor -@Transactional public class SysDictServiceImpl extends ServiceImpl implements ISysDictService { - - private final SysDictMapper sysDictMapper; + @Autowired + private SysDictMapper sysDictMapper; @Override public IPage queryAll(Map whereJson, PageQuery page) { String blurry = null; if (ObjectUtil.isNotEmpty(whereJson.get("blurry"))) blurry = whereJson.get("blurry").toString(); - IPage pages = new Page<>(page.getPage() + 1, page.getSize()); - QueryWrapper lam = new QueryWrapper<>(); - lam.select("MAX(dict_id) AS dictId, code, name") + IPage pages = this.page(new Page<>(page.getPage() + 1, page.getSize()), new QueryWrapper() + .select("MAX(dict_id) AS dict_id, code, name") .lambda() .like(ObjectUtil.isNotEmpty(blurry), Dict::getCode, blurry) .or(ObjectUtil.isNotEmpty(blurry)) .like(ObjectUtil.isNotEmpty(blurry), Dict::getName, blurry) - .orderBy(true, true, Dict::getCode) - .groupBy(Dict::getCode, Dict::getName); - sysDictMapper.selectPage(pages, lam); + .orderBy(true, true, Dict::getCode) + .groupBy(Dict::getCode, Dict::getName)); return pages; } @@ -64,20 +60,23 @@ public class SysDictServiceImpl extends ServiceImpl impleme List oldDict = sysDictMapper.selectList(new LambdaQueryWrapper() .eq(ObjectUtil.isNotEmpty(dict.getCode()), Dict::getCode, dict.getCode())); if (ObjectUtil.isNotEmpty(oldDict)) throw new BadRequestException("字典[" + dict.getCode() + "]已存在"); - dict.setDictId(IdUtil.getSnowflake(1, 1).nextIdStr()); - dict.setCreateId(currentUserId); - dict.setCreateName(nickName); - dict.setCreateTime(date); - dict.setUpdateId(currentUserId); - dict.setUpdateName(nickName); - dict.setUpdateTime(date); + dict.setDict_id(IdUtil.getSnowflake(1, 1).nextIdStr()); + dict.setCreate_id(currentUserId); + dict.setCreate_name(nickName); + dict.setCreate_time(date); + dict.setUpdate_id(currentUserId); + dict.setUpdate_name(nickName); + dict.setUpdate_time(date); sysDictMapper.insert(dict); } @Override @Transactional(rollbackFor = Exception.class) public void updateDict(Dict dto) { - Dict dict = sysDictMapper.selectById(dto.getDictId()); + Dict dict = sysDictMapper.selectById(dto.getDict_id()); + if (ObjectUtil.isEmpty(dict)) { + throw new BadRequestException("字典不存在"); + } List dictList = sysDictMapper.selectList(new LambdaQueryWrapper().eq(Dict::getCode, dto.getCode())); if (ObjectUtil.isNotEmpty(dictList) && !dto.getCode().equals(dict.getCode())) throw new BadRequestException("字典[" + dto.getCode() + "]已存在"); @@ -88,9 +87,9 @@ public class SysDictServiceImpl extends ServiceImpl impleme dicts.forEach(di -> { di.setCode(dto.getCode()); di.setName(dto.getName()); - di.setUpdateId(currentUserId); - di.setUpdateName(currentNickName); - di.setUpdateTime(DateUtil.now()); + di.setUpdate_id(currentUserId); + di.setUpdate_name(currentNickName); + di.setUpdate_time(DateUtil.now()); sysDictMapper.updateById(di); }); } @@ -111,7 +110,7 @@ public class SysDictServiceImpl extends ServiceImpl impleme lam.eq(Dict::getCode, criteria.getCode()) .isNotNull(Dict::getLabel) .ne(Dict::getLabel, "") - .orderBy(true, true, Dict::getDictSort); + .orderBy(true, true, Dict::getDict_sort); IPage pages = new Page<>(page.getPage() + 1, page.getSize()); sysDictMapper.selectPage(pages, lam); return pages; @@ -140,8 +139,8 @@ public class SysDictServiceImpl extends ServiceImpl impleme dic.setCode(dict.getCode()); dic.setLabel(dict.getLabel()); dic.setValue(dict.getValue()); - dic.setDictSort(dict.getDictSort()); - dic.setDictType(dict.getDictType()); + dic.setDict_sort(dict.getDict_sort()); + dic.setDict_type(dict.getDict_type()); dic.setPara1(dict.getPara1()); dic.setPara2(dict.getPara2()); dic.setPara3(dict.getPara3()); @@ -149,30 +148,34 @@ public class SysDictServiceImpl extends ServiceImpl impleme return; } // 插入新的数据 - dict.setDictId(IdUtil.getSnowflake(1, 1).nextIdStr()); + dict.setDict_id(IdUtil.getSnowflake(1, 1).nextIdStr()); dict.setCode(dic.getCode()); dict.setName(dic.getName()); - dict.setCreateId(SecurityUtils.getCurrentUserId()); - dict.setCreateName(SecurityUtils.getCurrentNickName()); - dict.setCreateTime(DateUtil.now()); - dict.setUpdateId(SecurityUtils.getCurrentUserId()); - dict.setUpdateName(SecurityUtils.getCurrentNickName()); - dict.setUpdateTime(DateUtil.now()); + dict.setCreate_id(SecurityUtils.getCurrentUserId()); + dict.setCreate_name(SecurityUtils.getCurrentNickName()); + dict.setCreate_time(DateUtil.now()); + dict.setUpdate_id(SecurityUtils.getCurrentUserId()); + dict.setUpdate_name(SecurityUtils.getCurrentNickName()); + dict.setUpdate_time(DateUtil.now()); sysDictMapper.insert(dict); } @Override @Transactional(rollbackFor = Exception.class) public void updateDetail(Dict resources) { - Dict dict = sysDictMapper.selectById(resources.getDictId()); - if (ObjectUtil.isEmpty(dict)) throw new BadRequestException("被删除或无权限,操作失败!"); + Dict dict = sysDictMapper.selectById(resources.getDict_id()); + if (ObjectUtil.isEmpty(dict)) { + throw new BadRequestException("被删除或无权限,操作失败!"); + } // 校验是否已经有标签 List dictList = sysDictMapper.selectList(new LambdaQueryWrapper().eq(Dict::getLabel, resources.getLabel()) .eq(Dict::getCode, resources.getCode())); - if (ObjectUtil.isNotEmpty(dictList) && !resources.getLabel().equals(dict.getLabel())) throw new BadRequestException("标签[" + dict.getLabel() + "]已存在"); - resources.setUpdateId(SecurityUtils.getCurrentUserId()); - resources.setUpdateName(SecurityUtils.getCurrentNickName()); - resources.setUpdateTime(DateUtil.now()); + if (ObjectUtil.isNotEmpty(dictList) && !resources.getLabel().equals(dict.getLabel())) { + throw new BadRequestException("标签[" + resources.getLabel() + "]已存在"); + } + resources.setUpdate_id(SecurityUtils.getCurrentUserId()); + resources.setUpdate_name(SecurityUtils.getCurrentNickName()); + resources.setUpdate_time(DateUtil.now()); sysDictMapper.updateById(resources); } @@ -182,4 +185,12 @@ public class SysDictServiceImpl extends ServiceImpl impleme sysDictMapper.deleteById(id); } + @Override + public List queryAll() { + return sysDictMapper.selectList(new QueryWrapper() + .select("MAX(dict_id) AS dictId, code, name") + .lambda() + .groupBy(Dict::getCode, Dict::getName)); + } + } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java new file mode 100644 index 0000000..1ae10b9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java @@ -0,0 +1,30 @@ +package org.nl.system.service.generator; + +import org.nl.system.service.generator.dao.CodeGenConfig; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + *

+ * 代码生成配置表 服务类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface ICodeGenConfigService extends IService { + + /** + * 根据表名查找 + * @param tableName + * @return + */ + CodeGenConfig findByTableName(String tableName); + + /** + * 根据表名更新 + * @param tableName + * @param genConfig + * @return + */ + CodeGenConfig update(String tableName, CodeGenConfig genConfig); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java new file mode 100644 index 0000000..ee1fd9f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java @@ -0,0 +1,72 @@ +package org.nl.system.service.generator; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import com.baomidou.mybatisplus.extension.service.IService; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dto.TablesInfo; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Async; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + *

+ * 列的数据信息表 服务类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface ICodeGeneratorService extends IService { + + /** + * 获得所有的表格信息 + * @return + */ + IPage getTables(String name, PageQuery pageQuery); + + /** + * 得到数据表的元数据 + * @param tableName 表名 + * @return / + */ + IPage getColumns(String tableName); + + /** + * 根据表名查询表字段 + * @param tableName + * @return + */ + List query(String tableName); + + /** + * 同步表数据 + * @param columnInfos / + * @param columnInfoList / + */ + @Async + void sync(IPage columnInfos, List columnInfoList); + + ResponseEntity preview(CodeGenConfig byTableName, IPage columns); + + /** + * 打包下载 + * @param genConfig 配置信息 + * @param columnsPage 字段信息分页数据 + * @param request / + * @param response / + */ + void download(CodeGenConfig genConfig, IPage columnsPage, HttpServletRequest request, HttpServletResponse response); + + /** + * 代码生成 + * @param genConfig 配置信息 + * @param columnsPage 字段信息分页数据 + */ + void generator(CodeGenConfig genConfig, IPage columnsPage); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java new file mode 100644 index 0000000..f5427fc --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java @@ -0,0 +1,73 @@ +package org.nl.system.service.generator.dao; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 列的数据信息表 + *

+ * + * @author generator + * @since 2023-05-03 + */ +@Data +@Builder +@EqualsAndHashCode(callSuper = false) +@TableName("code_column_config") +public class CodeColumnConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 标识 + */ + @TableId(value = "column_id", type = IdType.ASSIGN_ID) + private String column_id; + + @ApiModelProperty(value = "表名") + private String table_name; + + @ApiModelProperty(value = "数据库字段名称") + private String column_name; + + @ApiModelProperty(value = "数据库字段类型") + private String column_type; + + @ApiModelProperty(value = "数据库字段键类型") + private String key_type; + + @ApiModelProperty(value = "字段额外的参数") + private String extra; + + @ApiModelProperty(value = "数据库字段描述") + private String remark; + + @ApiModelProperty(value = "是否必填") + private Boolean not_null; + + @ApiModelProperty(value = "是否在列表显示") + private Boolean list_show; + + @ApiModelProperty(value = "是否表单显示") + private Boolean form_show; + + @ApiModelProperty(value = "表单类型") + private String form_type; + + @ApiModelProperty(value = "查询 1:模糊 2:精确") + private String query_type; + + @ApiModelProperty(value = "字典名称") + private String dict_name; + + @ApiModelProperty(value = "日期注解") + private String date_annotation; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java new file mode 100644 index 0000000..3d438c1 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java @@ -0,0 +1,82 @@ +package org.nl.system.service.generator.dao; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +/** + *

+ * 代码生成配置表 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = false) +@TableName("code_gen_config") +public class CodeGenConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + public CodeGenConfig(String table_name) { + this.table_name = table_name; + } + + /** + * ID + */ + @TableId(value = "config_id") + private String config_id; + + /** + * 表名 + */ + private String table_name; + + /** + * 作者 + */ + private String author; + + /** + * 是否覆盖 + */ + private Boolean cover; + + /** + * 模块名称 + */ + private String module_name; + + /** + * 包名 + */ + private String pack; + + /** + * 路径 + */ + private String path; + + /** + * api路径 + */ + private String api_path; + + /** + * 表前缀 + */ + private String prefix; + + /** + * 接口名称 + */ + private String api_alias; + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java new file mode 100644 index 0000000..c1306b6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java @@ -0,0 +1,35 @@ +package org.nl.system.service.generator.dao.mapper; + +import org.nl.system.service.generator.dao.CodeColumnConfig; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.nl.system.service.generator.dto.ColumnInfo; +import org.nl.system.service.generator.dto.TablesInfo; + +import java.util.List; + +/** + *

+ * 列的数据信息表 Mapper 接口 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface CodeColumnConfigMapper extends BaseMapper { + + /** + * 分页查找 + * @param name + * @return + */ + List getTables(String name, int pageSize, int offset); + + /** + * 分页查询的总数 + * @param name + * @return + */ + long getTablesTotal(String name); + + List getTablesByTableName(String tableName); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml new file mode 100644 index 0000000..e35f1b8 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml @@ -0,0 +1,46 @@ + + + + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java new file mode 100644 index 0000000..1fb385f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java @@ -0,0 +1,16 @@ +package org.nl.system.service.generator.dao.mapper; + +import org.nl.system.service.generator.dao.CodeGenConfig; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + *

+ * 代码生成配置表 Mapper 接口 + *

+ * + * @author generator + * @since 2023-05-03 + */ +public interface CodeGenConfigMapper extends BaseMapper { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml new file mode 100644 index 0000000..72ca44c --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java new file mode 100644 index 0000000..79e389f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java @@ -0,0 +1,48 @@ +package org.nl.system.service.generator.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @Author: lyd + * @Description: 字段信息 + * @Date: 2023/5/3 + */ +@Data +public class ColumnInfo { + @ApiModelProperty(value = "数据库字段名称") + private String column_name; + + @ApiModelProperty(value = "数据库字段类型") + private String column_type; + + @ApiModelProperty(value = "数据库字段键类型") + private String key_type; + + @ApiModelProperty(value = "字段额外的参数") + private String extra; + + @ApiModelProperty(value = "数据库字段描述") + private String remark; + + @ApiModelProperty(value = "是否必填") + private Boolean not_null; + + @ApiModelProperty(value = "是否在列表显示") + private Boolean list_show; + + @ApiModelProperty(value = "是否表单显示") + private Boolean form_show; + + @ApiModelProperty(value = "表单类型") + private String form_type; + + @ApiModelProperty(value = "查询 1:模糊 2:精确") + private String query_type; + + @ApiModelProperty(value = "字典名称") + private String dict_name; + + @ApiModelProperty(value = "日期注解") + private String date_annotation; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java new file mode 100644 index 0000000..9dce5d9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java @@ -0,0 +1,40 @@ +package org.nl.system.service.generator.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @Author: lyd + * @Description: 表的数据信息 + * @Date: 2023/5/3 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class TablesInfo { + /** + * 表名 + */ + private String table_name; + + /** + * 创建时间 + */ + private String create_time; + + /** + * 引擎 + */ + private String ENGINE; + + /** + * 字符序 + */ + private String coding; + + /** + * 注释 + */ + private String remark; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java new file mode 100644 index 0000000..7d0f5af --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java @@ -0,0 +1,71 @@ +package org.nl.system.service.generator.impl; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dao.mapper.CodeGenConfigMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.io.File; + +/** + *

+ * 代码生成配置表 服务实现类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Service +public class CodeGenConfigServiceImpl extends ServiceImpl implements ICodeGenConfigService { + + @Autowired + private CodeGenConfigMapper codeGenConfigMapper; + + @Override + public CodeGenConfig findByTableName(String tableName) { + CodeGenConfig codeGenConfig = codeGenConfigMapper.selectOne(new LambdaQueryWrapper() + .eq(CodeGenConfig::getTable_name, tableName)); + if (ObjectUtil.isEmpty(codeGenConfig)) { + return new CodeGenConfig(tableName); + } + return codeGenConfig; + } + + @Override + public CodeGenConfig update(String tableName, CodeGenConfig genConfig) { + // 如果 api 路径为空,则自动生成路径 + if(StrUtil.isEmpty(genConfig.getApi_path())){ + String separator = File.separator; + String[] paths; + String symbol = "\\"; + if (symbol.equals(separator)) { + paths = genConfig.getPath().split("\\\\"); + } else { + paths = genConfig.getPath().split(File.separator); + } + StringBuilder api = new StringBuilder(); + for (String path : paths) { + api.append(path); + api.append(separator); + if ("src".equals(path)) { + api.append("api"); + break; + } + } + genConfig.setApi_path(api.toString()); + } + if (ObjectUtil.isNotEmpty(genConfig.getConfig_id())) { + codeGenConfigMapper.updateById(genConfig); + } else { + genConfig.setConfig_id(IdUtil.getSnowflake(1,1).nextIdStr()); + codeGenConfigMapper.insert(genConfig); + } + return genConfig; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java new file mode 100644 index 0000000..d3c7ced --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java @@ -0,0 +1,179 @@ +package org.nl.system.service.generator.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.ZipUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; +import org.nl.common.utils.FileUtil; +import org.nl.common.utils.GenUtil; +import org.nl.system.service.generator.ICodeGeneratorService; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dao.mapper.CodeColumnConfigMapper; +import org.nl.system.service.generator.dto.ColumnInfo; +import org.nl.system.service.generator.dto.TablesInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + *

+ * 列的数据信息表 服务实现类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Service +public class CodeGeneratorServiceImpl extends ServiceImpl implements ICodeGeneratorService { + + @Autowired + private CodeColumnConfigMapper columnConfigMapper; + + @Override + public IPage getTables(String name, PageQuery pageQuery) { + IPage pages = new Page<>(); + int page = pageQuery.getPage(); + int pageSize = pageQuery.getSize(); + int offset = page * pageSize; + List tableInfos = columnConfigMapper.getTables(name, pageSize, offset); + long num = columnConfigMapper.getTablesTotal(name); + pages.setRecords(tableInfos); + pages.setCurrent(page + 1); + pages.setSize(pageSize); + pages.setTotal(num); + return pages; + } + + @Override + public IPage getColumns(String tableName) { + IPage pages = new Page<>(); + // 查找行列数据表 + List codeColumnConfigs = columnConfigMapper + .selectList(new LambdaQueryWrapper() + .eq(CodeColumnConfig::getTable_name, tableName)); + if (ObjectUtil.isEmpty(codeColumnConfigs)) { + // 为空查找全新的数据 + codeColumnConfigs = query(tableName); + // 保存 + this.saveBatch(codeColumnConfigs); + } + pages.setRecords(codeColumnConfigs); + return pages; + } + + @Override + public List query(String tableName) { + List columnConfigList = columnConfigMapper.getTablesByTableName(tableName); + // 设置默认值 + List columnInfos = columnConfigList.stream() + .map(config -> CodeColumnConfig + .builder() + .column_id(IdUtil.getSnowflake(1,1).nextIdStr()) + .table_name(tableName) + .column_name(config.getColumn_name()) + .column_type(config.getColumn_type()) + .key_type(config.getKey_type()) + .extra(config.getExtra()) + .not_null((ObjectUtil.isNotEmpty(config.getKey_type()) + &&ObjectUtil.isNotEmpty(config.getExtra()) + &&GenUtil.PK.equalsIgnoreCase(config.getKey_type()) + &&GenUtil.EXTRA.equalsIgnoreCase(config.getExtra())) + ?false:ObjectUtil.isNotEmpty(config.getNot_null())?config.getNot_null():false) + .remark(ObjectUtil.isNotEmpty(config.getRemark())?config.getRemark():null) + .list_show(true) + .form_show(true) + .build()) + .collect(Collectors.toList()); + return columnInfos; + } + + @Override + public void sync(IPage columnInfos, List columnInfoList) { + List records = columnInfos.getRecords(); + // 第一种情况,数据库类字段改变或者新增字段 + for (CodeColumnConfig columnInfo : columnInfoList) { + // 根据字段名称查找 + List columns = records.stream().filter(c -> c.getColumn_name().equals(columnInfo.getColumn_name())).collect(Collectors.toList()); + // 如果能找到,就修改部分可能被字段 + if (CollectionUtil.isNotEmpty(columns)) { + CodeColumnConfig column = columns.get(0); + column.setColumn_type(columnInfo.getColumn_type()); + column.setExtra(columnInfo.getExtra()); + column.setKey_type(columnInfo.getKey_type()); + if (StrUtil.isEmpty(column.getRemark())) { + column.setRemark(columnInfo.getRemark()); + } + columnConfigMapper.updateById(column); + } else { + // 如果找不到,则保存新字段信息 + columnConfigMapper.insert(columnInfo); + } + } + // 第二种情况,数据库字段删除了 + for (CodeColumnConfig columnInfo : records) { + // 根据字段名称查找 + List columns = columnInfoList.stream().filter(c -> c.getColumn_name().equals(columnInfo.getColumn_name())).collect(Collectors.toList()); + // 如果找不到,就代表字段被删除了,则需要删除该字段 + if (CollectionUtil.isEmpty(columns)) { + columnConfigMapper.deleteById(columnInfo.getColumn_id()); + } + } + } + + @Override + public ResponseEntity preview(CodeGenConfig genConfig, IPage columns) { + List columnsRecords = columns.getRecords(); + if (genConfig.getConfig_id() == null) { + throw new BadRequestException("请先配置生成器"); + } + List> genList = GenUtil.preview(columnsRecords, genConfig); + return new ResponseEntity<>(genList, HttpStatus.OK); + } + + @Override + public void download(CodeGenConfig genConfig, IPage columnsPage, HttpServletRequest request, HttpServletResponse response) { + List columns = columnsPage.getRecords(); + if (genConfig.getConfig_id() == null) { + throw new BadRequestException("请先配置生成器"); + } + try { + File file = new File(GenUtil.download(columns, genConfig)); + String zipPath = file.getPath() + ".zip"; + ZipUtil.zip(file.getPath(), zipPath); + FileUtil.downloadFile(request, response, new File(zipPath), true); + } catch (IOException e) { + throw new BadRequestException("打包失败"); + } + } + + @Override + public void generator(CodeGenConfig genConfig, IPage columnsPage) { + List columns = columnsPage.getRecords(); + if (genConfig.getConfig_id() == null) { + throw new BadRequestException("请先配置生成器"); + } + try { + GenUtil.generatorCode(columns, genConfig); + } catch (IOException e) { + log.error(e.getMessage(), e); + throw new BadRequestException("生成失败,请手动处理已生成的文件"); + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/ISysLogService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/ISysLogService.java new file mode 100644 index 0000000..5ae003c --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/ISysLogService.java @@ -0,0 +1,44 @@ +package org.nl.system.service.logging; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.logging.dao.SysLog; + +import java.util.Map; + +/** + *

+ * 系统日志 服务类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface ISysLogService extends IService { + + /** + * 分页查询日志 + * @param criteria + * @param pageable + * @return + */ + IPage queryAll(Map criteria, PageQuery pageable); + + /** + * 查询异常详情 + * @param id 日志ID + * @return Object + */ + Object findByErrDetail(String id); + + /** + * 删除所有异常日志 + */ + void delAllByError(); + + /** + * 删除所有操作日志 + */ + void delAllByInfo(); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/SysLog.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/SysLog.java new file mode 100644 index 0000000..6067341 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/SysLog.java @@ -0,0 +1,55 @@ +package org.nl.system.service.logging.dao; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.time.LocalDateTime; +import java.io.Serializable; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 系统日志 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_log") +public class SysLog implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * ID + */ + @TableId(value = "log_id") + private String log_id; + + private String description; + + private String log_type; + + private String method; + + private String params; + + private String request_ip; + + private Long time; + + private String username; + + private String address; + + private String browser; + + /** 异常详细 */ + private byte[] exception_detail; + + private String create_time; + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.java new file mode 100644 index 0000000..3205364 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.java @@ -0,0 +1,16 @@ +package org.nl.system.service.logging.dao.mapper; + +import org.nl.system.service.logging.dao.SysLog; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + *

+ * 系统日志 Mapper 接口 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface SysLogMapper extends BaseMapper { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.xml new file mode 100644 index 0000000..38be495 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dao/mapper/SysLogMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dto/SysLogQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dto/SysLogQuery.java new file mode 100644 index 0000000..2fbf523 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/dto/SysLogQuery.java @@ -0,0 +1,12 @@ +package org.nl.system.service.logging.dto; + +import org.nl.common.domain.query.BaseQuery; +import org.nl.system.service.logging.dao.SysLog; + +/** + * @Author: lyd + * @Description: + * @Date: 2023/5/8 + */ +public class SysLogQuery extends BaseQuery { +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/impl/SysLogServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/impl/SysLogServiceImpl.java new file mode 100644 index 0000000..9042e2f --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logging/impl/SysLogServiceImpl.java @@ -0,0 +1,74 @@ +package org.nl.system.service.logging.impl; + +import cn.hutool.core.lang.Dict; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.utils.ValidationUtil; +import org.nl.system.service.logging.ISysLogService; +import org.nl.system.service.logging.dao.SysLog; +import org.nl.system.service.logging.dao.mapper.SysLogMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + *

+ * 系统日志 服务实现类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Slf4j +@Service +public class SysLogServiceImpl extends ServiceImpl implements ISysLogService { + + @Autowired + private SysLogMapper logMapper; + + @Override + public IPage queryAll(Map whereJson, PageQuery pageable) { + String blurry = ObjectUtil.isNotEmpty(whereJson.get("blurry"))?whereJson.get("blurry").toString():null; + String log_type = ObjectUtil.isNotEmpty(whereJson.get("log_type"))?whereJson.get("log_type").toString():null; + String username = ObjectUtil.isNotEmpty(whereJson.get("username"))?whereJson.get("username").toString():null; + String begin_time = ObjectUtil.isNotEmpty(whereJson.get("begin_time"))?whereJson.get("begin_time").toString():null; + String end_time = ObjectUtil.isNotEmpty(whereJson.get("end_time"))?whereJson.get("end_time").toString():null; + LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); + lam.eq(ObjectUtil.isNotEmpty(log_type), SysLog::getLog_type, log_type) + .eq(ObjectUtil.isNotEmpty(username), SysLog::getUsername, username) + .like(ObjectUtil.isNotEmpty(blurry), SysLog::getDescription, blurry) + .le(ObjectUtil.isNotEmpty(end_time), SysLog::getCreate_time, end_time) + .ge(ObjectUtil.isNotEmpty(begin_time), SysLog::getCreate_time, begin_time) + .orderByDesc(SysLog::getCreate_time); + IPage page = new Page<>(pageable.getPage()+1, pageable.getSize()); + logMapper.selectPage(page, lam); + return page; + } + + @Override + public Object findByErrDetail(String id) { + SysLog sysLog = logMapper.selectById(id); + if (ObjectUtil.isEmpty(sysLog)) { + sysLog = new SysLog(); + } + ValidationUtil.isNull(sysLog.getLog_id(), "SysLog", "log_id", id); + byte[] details = sysLog.getException_detail(); + return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes())); + } + + @Override + public void delAllByError() { + logMapper.delete(new LambdaQueryWrapper().eq(SysLog::getLog_type, "ERROR")); + } + + @Override + public void delAllByInfo() { + logMapper.delete(new LambdaQueryWrapper().eq(SysLog::getLog_type, "INFO")); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageImageService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageImageService.java new file mode 100644 index 0000000..037907a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageImageService.java @@ -0,0 +1,56 @@ +package org.nl.system.service.logicflow; + +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.logicflow.dao.StageImage; +import com.baomidou.mybatisplus.extension.service.IService; +import org.springframework.data.domain.Pageable; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * 设备舞台图标表 服务类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface IStageImageService extends IService { + + /** + * 分页 + * @param whereJson + * @param page + * @return + */ + IPage queryAll(Map whereJson, PageQuery page); + + /** + * 创建 + * @param entity + */ + void create(StageImage entity); + + /** + * 更新 + * @param entity + */ + void update(StageImage entity); + + /** + * 删除 + * @param ids + */ + void deleteAll(Set ids); + + /** + * 前端舞台编辑选择设备图标下拉选列表 + * + * @return + */ + List selectList(); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageService.java new file mode 100644 index 0000000..3e54179 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/IStageService.java @@ -0,0 +1,62 @@ +package org.nl.system.service.logicflow; + +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.logicflow.dao.Stage; +import com.baomidou.mybatisplus.extension.service.IService; +import org.springframework.data.domain.Pageable; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * 舞台主表 服务类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface IStageService extends IService { + + /** + * 分页查询 + * @param whereJson + * @param page + * @return + */ + IPage queryAll(Map whereJson, PageQuery page); + + /** + * 新增 + * @param dto + */ + void create(Stage dto); + + /** + * 修改 + * @param dto + */ + void update(Stage dto); + + /** + * 删除 + * @param ids + */ + void deleteAll(Set ids); + + /** + * 前端舞台下拉选列表 + * + * @return + */ + List selectList(); + + /** + * 添加舞台数据 + * @param dto + */ + void addNewStage(Stage dto); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/Stage.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/Stage.java new file mode 100644 index 0000000..33f9a3e --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/Stage.java @@ -0,0 +1,78 @@ +package org.nl.system.service.logicflow.dao; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 舞台主表 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("stage") +public class Stage implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 舞台标识 + */ + @TableId + private String stage_uuid; + + /** + * 舞台编码 + */ + private String stage_code; + + /** + * 舞台名字 + */ + private String stage_name; + + /** + * 舞台数据 + */ + private String stage_data; + + /** + * 是否启用 + */ + private String is_active; + + /** + * 是否删除 + */ + private String is_delete; + + /** + * 创建者 + */ + private String create_id; + private String create_name; + + /** + * 创建时间 + */ + private String create_time; + + /** + * 修改者 + */ + private String update_id; + private String update_name; + + /** + * 修改时间 + */ + private String update_time; + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/StageImage.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/StageImage.java new file mode 100644 index 0000000..a96dd0d --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/StageImage.java @@ -0,0 +1,83 @@ +package org.nl.system.service.logicflow.dao; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 设备舞台图标表 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("stage_image") +public class StageImage implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 图标标识 + */ + @TableId + private String image_uuid; + + /** + * 图标编码 + */ + private String image_code; + + /** + * 图标名字 + */ + private String image_name; + + /** + * 适用驱动 + */ + private String driver_code_json; + + /** + * 备注 + */ + private String remark; + + /** + * 是否启用 + */ + private String is_active; + + /** + * 是否删除 + */ + private String is_delete; + + /** + * 创建者 + */ + private String create_id; + private String create_name; + + /** + * 创建时间 + */ + private String create_time; + + /** + * 修改者 + */ + private String update_id; + private String update_name; + + /** + * 修改时间 + */ + private String update_time; + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.java new file mode 100644 index 0000000..9d6eeb8 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.java @@ -0,0 +1,16 @@ +package org.nl.system.service.logicflow.dao.mapper; + +import org.nl.system.service.logicflow.dao.StageImage; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + *

+ * 设备舞台图标表 Mapper 接口 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface StageImageMapper extends BaseMapper { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.xml new file mode 100644 index 0000000..93e3cac --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageImageMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.java new file mode 100644 index 0000000..abf68d1 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.java @@ -0,0 +1,16 @@ +package org.nl.system.service.logicflow.dao.mapper; + +import org.nl.system.service.logicflow.dao.Stage; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + *

+ * 舞台主表 Mapper 接口 + *

+ * + * @author generator + * @since 2023-05-08 + */ +public interface StageMapper extends BaseMapper { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.xml new file mode 100644 index 0000000..10c03e4 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/dao/mapper/StageMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageImageServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageImageServiceImpl.java new file mode 100644 index 0000000..14b40a6 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageImageServiceImpl.java @@ -0,0 +1,89 @@ +package org.nl.system.service.logicflow.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; +import org.nl.common.utils.SecurityUtils; +import org.nl.system.service.logicflow.IStageImageService; +import org.nl.system.service.logicflow.dao.StageImage; +import org.nl.system.service.logicflow.dao.mapper.StageImageMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * 设备舞台图标表 服务实现类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Service +public class StageImageServiceImpl extends ServiceImpl implements IStageImageService { + + @Autowired + private StageImageMapper stageImageMapper; + + @Override + public IPage queryAll(Map whereJson, PageQuery page) { + LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); + IPage pages = new Page<>(page.getPage() + 1, page.getSize()); + stageImageMapper.selectPage(pages, lam); + return pages; + } + + @Override + public void create(StageImage entity) { + String currentUserId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + + entity.setImage_uuid(IdUtil.simpleUUID()); + entity.setCreate_id(currentUserId); + entity.setCreate_name(nickName); + entity.setCreate_time(now); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); + stageImageMapper.insert(entity); + } + + @Override + public void update(StageImage entity) { + StageImage dto = stageImageMapper.selectOne(new LambdaQueryWrapper() + .eq(StageImage::getImage_uuid, entity.getImage_uuid())); + if (dto == null) throw new BadRequestException("被删除或无权限,操作失败!"); + + String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUserId = SecurityUtils.getCurrentUserId(); + String now = DateUtil.now(); + entity.setUpdate_time(now); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(currentUsername); + stageImageMapper.updateById(entity); + } + + @Override + public void deleteAll(Set ids) { + stageImageMapper.deleteBatchIds(ids); + } + + @Override + public List selectList() { + List stageImages = stageImageMapper.selectList(new LambdaQueryWrapper() + .eq(StageImage::getIs_delete, "0") + .eq(StageImage::getIs_active, "1") + .orderByDesc(StageImage::getUpdate_time)); + stageImages.forEach(stageImage -> stageImage.setImage_name(stageImage.getImage_code().split("-")[0])); + return stageImages; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageServiceImpl.java new file mode 100644 index 0000000..0f3b62b --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/logicflow/impl/StageServiceImpl.java @@ -0,0 +1,109 @@ +package org.nl.system.service.logicflow.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; +import org.nl.common.utils.SecurityUtils; +import org.nl.system.service.logicflow.IStageService; +import org.nl.system.service.logicflow.dao.Stage; +import org.nl.system.service.logicflow.dao.mapper.StageMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * 舞台主表 服务实现类 + *

+ * + * @author generator + * @since 2023-05-08 + */ +@Service +public class StageServiceImpl extends ServiceImpl implements IStageService { + + @Autowired + private StageMapper stageMapper; + + @Override + public IPage queryAll(Map whereJson, PageQuery page) { + LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); + IPage pages = new Page<>(page.getPage() + 1, page.getSize()); + stageMapper.selectPage(pages, lam); + return pages; + } + + @Override + public void create(Stage entity) { + Stage stage = stageMapper.selectOne(new LambdaQueryWrapper().eq(Stage::getStage_code, entity.getStage_code())); + if (ObjectUtil.isNotEmpty(stage)) { + throw new BadRequestException("舞台编码[" + entity.getStage_code() + "]已存在"); + } + String currentUserId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + + entity.setStage_uuid(IdUtil.simpleUUID()); + entity.setCreate_id(currentUserId); + entity.setCreate_name(nickName); + entity.setCreate_time(now); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); + stageMapper.insert(entity); + } + + @Override + public void update(Stage dto) { + Stage entity = stageMapper.selectOne(new LambdaQueryWrapper().eq(Stage::getStage_uuid, dto.getStage_uuid())); + if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); + + String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUserId = SecurityUtils.getCurrentUserId(); + String now = DateUtil.now(); + dto.setUpdate_time(now); + dto.setUpdate_id(currentUserId); + dto.setUpdate_name(currentUsername); + stageMapper.updateById(dto); + } + + @Override + public void deleteAll(Set ids) { + stageMapper.deleteBatchIds(ids); + } + + @Override + public List selectList() { + List stages = stageMapper.selectList(new LambdaQueryWrapper() + .eq(Stage::getIs_delete, "0") + .eq(Stage::getIs_active, "1")); + return stages; + } + + @Override + public void addNewStage(Stage dto) { + Stage stage = stageMapper.selectOne(new LambdaQueryWrapper().eq(Stage::getStage_code, dto.getStage_code())); + if (ObjectUtil.isEmpty(stage)) { + throw new BadRequestException("舞台不存在"); + } + // 设置内容 + stage.setStage_data(dto.getStage_data()); + // 获取当前用户与时间 + String currentUsername = SecurityUtils.getCurrentUsername(); + String currentUserId = SecurityUtils.getCurrentUserId(); + String now = DateUtil.now(); + stage.setUpdate_time(now); + stage.setUpdate_name(currentUsername); + stage.setUpdate_id(currentUserId); + stageMapper.updateById(stage); + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneExecuteLogService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneExecuteLogService.java new file mode 100644 index 0000000..cd2f571 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneExecuteLogService.java @@ -0,0 +1,40 @@ +package org.nl.system.service.lucene; + +import org.nl.system.service.lucene.dto.LuceneLogDto; + +import java.io.IOException; + +public interface LuceneExecuteLogService { + /** + * 设备光电变化实时光电信号 + * + * @param device_code 设备编号 + * @param key plc信号 + * @param value plc信号值 + */ + void deviceItemValue(String device_code, String key, String value); + + /** + * 设备执行日志,会保留历史记录 + * + * @param luceneLogDto 日志结果对象 + */ + void deviceExecuteLog(LuceneLogDto luceneLogDto); + + /** + * 接口日志,会保留历史记录 + * + * @param luceneLogDto 日志结果对象 + */ + void interfaceExecuteLog(LuceneLogDto luceneLogDto) throws IOException; + + /** + * 设备执行日志,会保留历史记录 + * + * @param name 日志名称 + * @param message 日志信息 + */ + void extLog(String name, String message); + + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneService.java new file mode 100644 index 0000000..96560e8 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/LuceneService.java @@ -0,0 +1,19 @@ +package org.nl.system.service.lucene; + +import com.alibaba.fastjson.JSONArray; +import org.springframework.data.domain.Pageable; + +import java.util.Map; + + +public interface LuceneService { + + /** + * 获取数据分页 + * + * @param whereJson 条件 + * @param page 分页参数 + * @return Map + */ + Map getAll(Map whereJson, Pageable page); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/dto/LuceneLogDto.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/dto/LuceneLogDto.java new file mode 100644 index 0000000..7cda043 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/dto/LuceneLogDto.java @@ -0,0 +1,86 @@ +package org.nl.system.service.lucene.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class LuceneLogDto { + + /* 日志标识 */ + private String log_uuid; + /*日志类型*/ + private String logType; + /*设备编号*/ + private String device_code; + /*内容详情*/ + private String content; + + /* 任务编码 */ + private String task_code; + + /* 指令编码 */ + private String instruct_code; + + /* 任务标识 */ + private String task_id; + + /* 载具号 */ + private String vehicle_code; + + /* 备注 */ + private String remark; + + /* 日志类型 */ + private String log_type; + + /* 方法 */ + private String method; + + /* 请求参数 */ + private String requestparam; + + /* 响应参数 */ + private String responseparam; + + /* 请求地址 */ + private String requesturl; + + /* 状态码 */ + private String status_code; + + /* 是否删除 1:是;0:否 */ + private String is_delete; + + /* 创建者 */ + private String create_by; + + /* 创建时间 YYYY-MM-DD hh:mm:ss */ + private String create_time; + + /* 修改者 */ + private String update_by; + + /* 修改时间 */ + private String update_time; + + + + public LuceneLogDto (final String opc_server_code,final String opc_plc_code, + final String device_code,final String to_home,final int last_home, + final int home) { + super (); + this.device_code = device_code; + this.content = "信号" + + opc_server_code + "." + + opc_plc_code + "." + + device_code + "." + + to_home + "变更从" + + last_home + "->" + + home; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneExecuteLogServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneExecuteLogServiceImpl.java new file mode 100644 index 0000000..0f5deac --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneExecuteLogServiceImpl.java @@ -0,0 +1,111 @@ +package org.nl.system.service.lucene.impl; + +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.StringField; +import org.apache.lucene.index.IndexWriter; +import org.nl.common.enums.LogTypeEnum; +import org.nl.config.lucene.DynamicLogger; +import org.nl.config.lucene.LuceneIndexWriter; +import org.nl.system.service.lucene.LuceneExecuteLogService; +import org.nl.system.service.lucene.dto.LuceneLogDto; +import org.slf4j.Logger; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; + +/** + * @author jlm + * @description 服务实现 + * @date 2023-04-11 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class LuceneExecuteLogServiceImpl implements LuceneExecuteLogService { + + //日志目录 + @Value("${logging.file.path}") + private String logPath; + + @Override + public void deviceItemValue(String device_code, String key, String value) { + String now = DateUtil.now(); + } + + @SneakyThrows + @Override + public void deviceExecuteLog(LuceneLogDto luceneLogDto) { + luceneLogDto.setLogType(LogTypeEnum.DEVICE_LOG.getDesc()); + addIndex(luceneLogDto); + } + + @Override + public void interfaceExecuteLog(LuceneLogDto luceneLogDto) throws IOException { + luceneLogDto.setLogType(LogTypeEnum.INTERFACE_LOG.getDesc()); + addIndex(luceneLogDto); + } + + private void addIndex(LuceneLogDto luceneLogDto) throws IOException { + IndexWriter indexWriter = LuceneIndexWriter.getIndexWriter(); + //创建一个Document对象 + Document document = new Document(); + try { + //记录索引开始时间 + long startTime = System.currentTimeMillis(); + //向document对象中添加域。 + if (ObjectUtil.isNotEmpty(luceneLogDto.getDevice_code())) { + document.add(new StringField("device_code", luceneLogDto.getDevice_code(), Field.Store.YES)); +// document.add(new TextField("device_code", luceneLogDto.getDevice_code(), Field.Store.YES)); + } + if (ObjectUtil.isNotEmpty(luceneLogDto.getContent())) { + document.add(new StringField("fieldContent", luceneLogDto.getContent(), Field.Store.YES)); + } + if (ObjectUtil.isNotEmpty(luceneLogDto.getMethod())) { + document.add(new StringField("method", luceneLogDto.getMethod(), Field.Store.YES)); + } + if (ObjectUtil.isNotEmpty(luceneLogDto.getStatus_code())) { + document.add(new StringField("status_code", luceneLogDto.getStatus_code(), Field.Store.YES)); + } + if (ObjectUtil.isNotEmpty(luceneLogDto.getRequestparam())) { + document.add(new StringField("requestparam", luceneLogDto.getRequestparam(), Field.Store.YES)); + } + if (ObjectUtil.isNotEmpty(luceneLogDto.getResponseparam())) { + document.add(new StringField("responseparam", luceneLogDto.getResponseparam(), Field.Store.YES)); + } + document.add(new StringField("logType", luceneLogDto.getLogType(), Field.Store.YES)); + document.add(new StringField("logTime", DateUtil.format(new DateTime(), "yyyy-MM-dd HH:mm:ss.SSS"), Field.Store.YES)); + indexWriter.addDocument(document); + //记录索引结束时间 + long endTime = System.currentTimeMillis(); + indexWriter.commit(); + //实现日志文件按业务独立生成日志文件到指定路径 + DynamicLogger loggerBuilder =new DynamicLogger(logPath+"\\"+luceneLogDto.getLogType()+"\\"); + Logger logger = loggerBuilder.getLogger(luceneLogDto.getDevice_code()); +// logger.info("设备{}建立索引共耗时{}毫秒",luceneLogDto.getDevice_code(),endTime-startTime); + logger.info("{}",luceneLogDto.toString()); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } + + @Override + public void extLog(String name, String message) { + try { + MDC.put(name, name); + log.info("{}", message); + } catch (Exception e) { + e.printStackTrace(); + } finally { + MDC.remove(name); + } + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneServiceImpl.java new file mode 100644 index 0000000..f7cc829 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/lucene/impl/LuceneServiceImpl.java @@ -0,0 +1,44 @@ +package org.nl.system.service.lucene.impl; + +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.config.lucene.Searcher; +import org.nl.system.service.lucene.LuceneService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Map; + + +@Service +@RequiredArgsConstructor +@Slf4j +public class LuceneServiceImpl implements LuceneService { + + //日志索引目录 + @Value("${lucene.index.path}") + private String luceneUrl; + + @Override + public Map getAll(Map whereJson, Pageable page) { + JSONObject jo = new JSONObject(); + try { + JSONObject jsonObject = (JSONObject) Searcher.search(luceneUrl, "", whereJson); + JSONArray array = jsonObject.getJSONArray("content"); + int totalElements = Integer.parseInt(jsonObject.get("totalElements").toString()); + jo.put("content", array); + jo.put("totalElements", totalElements); + } catch (Exception e) { + log.error("索引查询为空", e); + throw new NullPointerException("索引查询为空"); + } + + return jo; + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/ISysMenuService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/ISysMenuService.java index 5403902..b672ea4 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/ISysMenuService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/ISysMenuService.java @@ -2,10 +2,10 @@ package org.nl.system.service.menu; import com.baomidou.mybatisplus.extension.service.IService; import org.nl.common.domain.query.PageQuery; +import org.nl.common.domain.vo.MenuVo; import org.nl.system.service.menu.dao.SysMenu; import org.nl.system.service.menu.dto.MenuDto; import org.nl.system.service.menu.dto.MenuQuery; -import org.nl.system.service.menu.dto.MenuVo; import java.util.List; import java.util.Map; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dao/SysMenu.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dao/SysMenu.java index 401fdc2..33d4d78 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dao/SysMenu.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dao/SysMenu.java @@ -27,7 +27,7 @@ public class SysMenu implements Serializable { * 菜单标识 */ @TableId(value = "menu_id", type = IdType.NONE) - private String menuId; + private String menu_id; /** * 上级菜单ID @@ -38,7 +38,7 @@ public class SysMenu implements Serializable { /** * 子菜单数目 */ - private Integer subCount; + private Integer sub_count; /** * 菜单类型 @@ -48,7 +48,7 @@ public class SysMenu implements Serializable { /** * 所属系统 */ - private String systemType; + private String system_type; /** * 菜单分类 @@ -63,7 +63,7 @@ public class SysMenu implements Serializable { /** * 组件名称 */ - private String componentName; + private String component_name; /** * 组件 @@ -73,7 +73,7 @@ public class SysMenu implements Serializable { /** * 排序 */ - private Integer menuSort; + private Integer menu_sort; /** * 图标 @@ -108,34 +108,34 @@ public class SysMenu implements Serializable { /** * 创建人标识 */ - private String createId; + private String create_id; /** * 创建人 */ - private String createName; + private String create_name; /** * 创建时间 */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date createTime; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date create_time; /** * 修改人标识 */ - private String updateId; + private String update_id; /** * 修改人 */ - private String updateName; + private String update_name; /** * 修改时间 */ - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private Date updateTime; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date update_time; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuDto.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuDto.java index 0bc7309..4484d60 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuDto.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuDto.java @@ -16,7 +16,7 @@ package org.nl.system.service.menu.dto; import lombok.Data; -import org.nl.common.domain.BaseDTO; +import org.nl.common.base.BaseDTO; import java.io.Serializable; import java.util.List; @@ -25,7 +25,7 @@ import java.util.Objects; @Data public class MenuDto extends BaseDTO implements Serializable { - private String menuId; + private String menu_id; private List children; @@ -35,7 +35,7 @@ public class MenuDto extends BaseDTO implements Serializable { private String title; - private Integer menuSort; + private Integer menu_sort; private String path; private String name; @@ -44,30 +44,30 @@ public class MenuDto extends BaseDTO implements Serializable { private String pid; - private Integer subCount; + private Integer sub_count; private Boolean iframe; - private String systemType; + private String system_type; private Boolean cache; private Boolean hidden; - private String componentName; + private String component_name; private String icon; - private boolean hasChildren; + private boolean has_children; private boolean leaf; - public Boolean getHasChildren() { - return subCount > 0; + public Boolean getHas_children() { + return sub_count > 0; } public Boolean getLeaf() { - return subCount <= 0; + return sub_count <= 0; } public String getLabel() { @@ -83,11 +83,11 @@ public class MenuDto extends BaseDTO implements Serializable { return false; } MenuDto menuDto = (MenuDto) o; - return Objects.equals(menuId, menuDto.menuId); + return Objects.equals(menu_id, menuDto.menu_id); } @Override public int hashCode() { - return Objects.hash(menuId); + return Objects.hash(menu_id); } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuQuery.java index 6202256..01fcf9c 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuQuery.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/dto/MenuQuery.java @@ -14,7 +14,7 @@ import org.nl.system.service.menu.dao.SysMenu; @Data public class MenuQuery extends BaseQuery { private String pid = ""; - private String systemType; + private String system_type; @Override public void paramMapping() { this.doP.put("pid", QParam.builder().k(new String[]{"pid"}).type(QueryTEnum.OREQ).build()); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/impl/SysMenuServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/impl/SysMenuServiceImpl.java index f2e8b18..d29e0d6 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/impl/SysMenuServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/menu/impl/SysMenuServiceImpl.java @@ -8,24 +8,25 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.collect.Lists; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.nl.common.aspect.exception.BadRequestException; import org.nl.common.domain.constant.DictConstantPool; import org.nl.common.domain.query.PageQuery; -import org.nl.common.utils.CopyUtil; -import org.nl.common.utils.IdUtil; +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.SecurityUtils; - import org.nl.system.service.dict.ISysDictService; +import org.nl.common.domain.vo.MenuMetaVo; +import org.nl.common.domain.vo.MenuVo; +import org.nl.common.utils.CopyUtil; +import org.nl.config.IdUtil; import org.nl.system.service.dict.dao.Dict; +import org.nl.system.service.dict.dao.mapper.SysDictMapper; +import org.nl.system.service.lucene.LuceneExecuteLogService; +import org.nl.system.service.menu.dto.MenuDto; import org.nl.system.service.menu.ISysMenuService; import org.nl.system.service.menu.dao.SysMenu; import org.nl.system.service.menu.dao.mapper.SysMenuMapper; -import org.nl.system.service.menu.dto.MenuDto; -import org.nl.system.service.menu.dto.MenuMetaVo; import org.nl.system.service.menu.dto.MenuQuery; -import org.nl.system.service.menu.dto.MenuVo; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; @@ -42,13 +43,17 @@ import java.util.stream.Collectors; * @since 2022-12-15 */ @Service -@RequiredArgsConstructor @Slf4j -@Transactional public class SysMenuServiceImpl extends ServiceImpl implements ISysMenuService { - private final SysMenuMapper baseMapper; - private final ISysDictService sysDictMapper; + @Autowired + private SysMenuMapper baseMapper; + + @Autowired + private SysDictMapper sysDictMapper; + + @Autowired + private LuceneExecuteLogService luceneExecuteLogService; @Override public List queryAll(Map param) { @@ -63,8 +68,8 @@ public class SysMenuServiceImpl extends ServiceImpl impl if (StringUtils.isNotEmpty(query.getBlurry())){ query.setPid(null); } - Page menuPage = this.page(page.build(SysMenu.class), query.build()); - List collect = menuPage.getRecords().stream().map(menu -> this.doToDto(menu)).sorted(Comparator.comparingInt(MenuDto::getMenuSort)).collect(Collectors.toList()); + Page menuPage = this.page(page.build(), query.build()); + List collect = menuPage.getRecords().stream().map(menu -> this.doToDto(menu)).collect(Collectors.toList()); return collect; } @@ -98,7 +103,7 @@ public class SysMenuServiceImpl extends ServiceImpl impl public Set getChildMenus(List menuList, Set menuSet) { for (SysMenu menu : menuList) { menuSet.add(menu); - List menus = this.findByPid(menu.getMenuId()); + List menus = this.findByPid(menu.getMenu_id()); if (menus != null && menus.size() != 0) { getChildMenus(menus, menuSet); } @@ -116,7 +121,7 @@ public class SysMenuServiceImpl extends ServiceImpl impl throw new BadRequestException("外链必须以http://或者https://开头"); } } - resources.setMenuId(IdUtil.getStringId()); + resources.setMenu_id(IdUtil.getStringId()); if (resources.getPid().equals("0")) { resources.setPid(null); addSystemTypeDict(resources); @@ -124,32 +129,32 @@ public class SysMenuServiceImpl extends ServiceImpl impl baseMapper.insert(resources); // 计算子节点数目 - resources.setSubCount(0); + resources.setSub_count(0); // 更新父节点菜单数目 updateSubCnt(resources.getPid()); updateRootSystemType(resources); } private void addSystemTypeDict(SysMenu resources) { - Dict dict = sysDictMapper.getOne(new QueryWrapper().eq("code", DictConstantPool.DICT_SYS_CODE).orderByDesc("value").last("limit 1")); + Dict dict = sysDictMapper.selectOne(new QueryWrapper().eq("code", DictConstantPool.DICT_SYS_CODE).orderByDesc("value").last("limit 1")); Integer currentType = dict!=null?Integer.valueOf(dict.getValue())+1:1; Dict currentSysType = new Dict(); - currentSysType.setDictId(IdUtil.getStringId()); + currentSysType.setDict_id(IdUtil.getStringId()); currentSysType.setCode(DictConstantPool.DICT_SYS_CODE); currentSysType.setName(DictConstantPool.DICT_SYS_NAME); currentSysType.setLabel(resources.getTitle()); currentSysType.setValue(String.valueOf(currentType)); - currentSysType.setPara1(resources.getMenuId()); - sysDictMapper.save(currentSysType); - resources.setSystemType(String.valueOf(currentType)); + currentSysType.setPara1(resources.getMenu_id()); + sysDictMapper.insert(currentSysType); + resources.setSystem_type(String.valueOf(currentType)); } private void updateRootSystemType(SysMenu sysMenu) { - String rootMenuId = this.findRootMenuId(sysMenu.getMenuId()); - if (sysMenu.getMenuId().equals(rootMenuId)){ + String rootMenuId = this.findRootMenuId(sysMenu.getMenu_id()); + if (sysMenu.getMenu_id().equals(rootMenuId)){ return; } SysMenu rootMenu = this.findById(rootMenuId); - sysMenu.setSystemType(rootMenu.getSystemType()); + sysMenu.setSystem_type(rootMenu.getSystem_type()); this.updateById(sysMenu); } private String findRootMenuId(String menuId) { @@ -167,32 +172,27 @@ public class SysMenuServiceImpl extends ServiceImpl impl List pids = Lists.newArrayList(); for (SysMenu menu : menuSet) { //解绑菜单 - baseMapper.untiedMenu(menu.getMenuId()); - baseMapper.deleteById(menu.getMenuId()); + baseMapper.untiedMenu(menu.getMenu_id()); + baseMapper.deleteById(menu.getMenu_id()); String pid = menu.getPid(); if (StringUtils.isEmpty(pid)){ - pids.add(menu.getMenuId()); + pids.add(pid); } updateSubCnt(pid); } if (!CollectionUtils.isEmpty(pids)){ - sysDictMapper.remove(new QueryWrapper().in("para1", pids).eq("code", DictConstantPool.DICT_SYS_CODE)); + sysDictMapper.delete(new QueryWrapper().in("para1", pids).eq("code", DictConstantPool.DICT_SYS_CODE)); } } @Transactional(rollbackFor = Exception.class) @Override public void update(SysMenu resources) { - String menuId = resources.getMenuId(); + String menuId = resources.getMenu_id(); SysMenu menu = baseMapper.selectById(menuId); - String allChild = baseMapper.findAllChild(menuId); - List allChildIds = new ArrayList<>(); - allChildIds.add(menuId); - if (StringUtils.isNotEmpty(allChild)){ - allChildIds.addAll(Arrays.asList(allChild.split(","))); - } - - if (allChildIds.contains(resources.getPid())){ + String allChild = baseMapper.findAllChild(menuId); // 获取当前菜单的所有子菜单 + List allChildIds = ObjectUtil.isNotEmpty(allChild)?Arrays.asList(allChild.split(",")):null; + if (ObjectUtil.isNotEmpty(allChildIds) && allChildIds.contains(resources.getPid())){ throw new BadRequestException("上级不能为自己或自己的下级"); } if (resources.getIframe()) { @@ -208,16 +208,13 @@ public class SysMenuServiceImpl extends ServiceImpl impl addSystemTypeDict(resources); } }else { - resources.setSystemType(this.findById(resources.getPid()).getSystemType()); + resources.setSystem_type(this.findById(resources.getPid()).getSystem_type()); } String oldPid = menu.getPid(); String newPid = resources.getPid(); // 记录的父节点ID if (oldPid == null && newPid != null){ - sysDictMapper.remove(new QueryWrapper().eq("para1",menu.getMenuId()).eq("code", DictConstantPool.DICT_SYS_CODE)); - } - if (!resources.getTitle().equals(menu.getTitle())){ - sysDictMapper.update(new UpdateWrapper().set("label",resources.getTitle()).eq("para1",menu.getMenuId()).eq("code", DictConstantPool.DICT_SYS_CODE)); + sysDictMapper.delete(new QueryWrapper().eq("para1",menu.getMenu_id())); } menu.setTitle(resources.getTitle()); menu.setComponent(resources.getComponent()); @@ -225,10 +222,10 @@ public class SysMenuServiceImpl extends ServiceImpl impl menu.setIcon(resources.getIcon()); menu.setIframe(resources.getIframe()); menu.setPid(resources.getPid()); - menu.setMenuSort(resources.getMenuSort()); + menu.setMenu_sort(resources.getMenu_sort()); menu.setCache(resources.getCache()); menu.setHidden(resources.getHidden()); - menu.setComponentName(resources.getComponentName()); + menu.setComponent_name(resources.getComponent_name()); menu.setPermission(resources.getPermission()); menu.setType(resources.getType()); baseMapper.updateById(menu); @@ -236,8 +233,8 @@ public class SysMenuServiceImpl extends ServiceImpl impl updateSubCnt(oldPid); updateSubCnt(newPid); //更新SystemType - if (!resources.getSystemType().equals(menu.getSystemType())){ - this.update(new UpdateWrapper().set(DictConstantPool.DICT_SYS_CODE,resources.getSystemType()).in("menu_id",allChildIds)); + if (!resources.getSystem_type().equals(menu.getSystem_type())){ + this.update(new UpdateWrapper().set(DictConstantPool.DICT_SYS_CODE,resources.getSystem_type()).in("menu_id",allChildIds)); } } @@ -252,7 +249,7 @@ public class SysMenuServiceImpl extends ServiceImpl impl int count = baseMapper.findByPid(menuId).size(); SysMenu sysMenu = baseMapper.selectById(menuId); if (ObjectUtil.isEmpty(sysMenu)) return; - sysMenu.setSubCount(count); + sysMenu.setSub_count(count); baseMapper.updateById(sysMenu); } } @@ -269,7 +266,7 @@ public class SysMenuServiceImpl extends ServiceImpl impl if (menuDTO != null) { List menuDtoList = menuDTO.getChildren(); MenuVo menuVo = new MenuVo(); - menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getTitle()); + menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponent_name()) ? menuDTO.getComponent_name() : menuDTO.getTitle()); // 一级目录需要加斜杠,不然会报警告 menuVo.setPath(ObjectUtil.isEmpty(menuDTO.getPid()) ? "/" + menuDTO.getPath() : menuDTO.getPath()); menuVo.setHidden(menuDTO.getHidden()); @@ -324,17 +321,17 @@ public class SysMenuServiceImpl extends ServiceImpl impl trees.add(menuDTO); } for (MenuDto it : menuDtos) { - if (menuDTO.getMenuId().equals(it.getPid())) { + if (menuDTO.getMenu_id().equals(it.getPid())) { if (menuDTO.getChildren() == null) { menuDTO.setChildren(new ArrayList<>()); } menuDTO.getChildren().add(it); - ids.add(it.getMenuId()); + ids.add(it.getMenu_id()); } } } if (trees.size() == 0) { - trees = menuDtos.stream().filter(s -> !ids.contains(s.getMenuId())).collect(Collectors.toList()); + trees = menuDtos.stream().filter(s -> !ids.contains(s.getMenu_id())).collect(Collectors.toList()); } return trees; } @@ -357,45 +354,45 @@ public class SysMenuServiceImpl extends ServiceImpl impl if (ObjectUtil.isEmpty(entity)){ return menuDto; } - menuDto.setMenuId(entity.getMenuId()); + menuDto.setMenu_id(entity.getMenu_id()); menuDto.setType(entity.getType()); menuDto.setPermission(entity.getPermission()); menuDto.setTitle(entity.getTitle()); - menuDto.setMenuSort(entity.getMenuSort()); + menuDto.setMenu_sort(entity.getMenu_sort()); menuDto.setPath(entity.getPath()); menuDto.setComponent(entity.getComponent()); - menuDto.setSystemType(entity.getSystemType()); + menuDto.setSystem_type(entity.getSystem_type()); menuDto.setPid(entity.getPid()); - menuDto.setSubCount(entity.getSubCount()); + menuDto.setSub_count(entity.getSub_count()); menuDto.setIframe(entity.getIframe()); menuDto.setCache(entity.getCache()); menuDto.setHidden(entity.getHidden()); - menuDto.setComponentName(entity.getComponentName()); + menuDto.setComponent_name(entity.getComponent_name()); menuDto.setIcon(entity.getIcon()); - menuDto.setCreateTime(entity.getCreateTime()); + menuDto.setCreate_time(entity.getCreate_time()); //构建前端需要的数据结构树 - Integer sub_count = entity.getSubCount(); + Integer sub_count = entity.getSub_count(); if (sub_count <= 0) { menuDto.setLeaf(true); - menuDto.setHasChildren(false); + menuDto.setHas_children(false); } else { menuDto.setLeaf(false); - menuDto.setHasChildren(true); + menuDto.setHas_children(true); } return menuDto; } @Override public List buildMenus(String systemType) { - Dict dict = sysDictMapper.getOne(new QueryWrapper().eq("code", DictConstantPool.DICT_SYS_CODE).eq("value", systemType)); + Dict dict = sysDictMapper.selectOne(new QueryWrapper().eq("code", DictConstantPool.DICT_SYS_CODE).eq("value", systemType)); if (dict == null || StringUtils.isEmpty(dict.getPara1())){ throw new BadRequestException("获取对应的系统菜单不存在"); } String pid = dict.getPara1(); List menuDtoList = baseMapper.findSystemMenu(SecurityUtils.getCurrentUserId(),systemType); //移除系统级菜单 - menuDtoList.removeIf(a->a.getMenuId().equals(pid)); + menuDtoList.removeIf(a->a.getMenu_id().equals(pid)); List menuDtos = this.buildTree(CopyUtil.copyList(menuDtoList, MenuDto.class)); return this.buildMenus(menuDtos,pid); } @@ -408,7 +405,7 @@ public class SysMenuServiceImpl extends ServiceImpl impl if (menuDTO != null) { List menuDtoList = menuDTO.getChildren(); MenuVo menuVo = new MenuVo(); - menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getTitle()); + menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponent_name()) ? menuDTO.getComponent_name() : menuDTO.getTitle()); // 一级目录需要加斜杠,不然会报警告 menuVo.setPath(pid.equals(menuDTO.getPid())? "/" + menuDTO.getPath() : menuDTO.getPath()); menuVo.setHidden(menuDTO.getHidden()); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/MonitorService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/MonitorService.java new file mode 100644 index 0000000..d0573f9 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/MonitorService.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.system.service.monitor; + +import java.util.Map; + +/** + * @author Zheng Jie + * @date 2020-05-02 + */ +public interface MonitorService { + + /** + * 查询数据分页 + * @return Map + */ + Map getServers(); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/impl/MonitorServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/impl/MonitorServiceImpl.java new file mode 100644 index 0000000..b721ec8 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/monitor/impl/MonitorServiceImpl.java @@ -0,0 +1,189 @@ +/* + * Copyright 2019-2020 Zheng Jie + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.nl.system.service.monitor.impl; + +import cn.hutool.core.date.BetweenFormatter; +import cn.hutool.core.date.DateUtil; +import org.nl.common.utils.ElAdminConstant; +import org.nl.common.utils.FileUtil; +import org.nl.common.utils.StringUtils; +import org.nl.system.service.monitor.MonitorService; +import org.springframework.stereotype.Service; +import oshi.SystemInfo; +import oshi.hardware.CentralProcessor; +import oshi.hardware.GlobalMemory; +import oshi.hardware.HardwareAbstractionLayer; +import oshi.hardware.VirtualMemory; +import oshi.software.os.FileSystem; +import oshi.software.os.OSFileStore; +import oshi.software.os.OperatingSystem; +import oshi.util.FormatUtil; +import oshi.util.Util; + +import java.lang.management.ManagementFactory; +import java.text.DecimalFormat; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Zheng Jie + * @date 2020-05-02 + */ +@Service +public class MonitorServiceImpl implements MonitorService { + + private final DecimalFormat df = new DecimalFormat("0.00"); + + @Override + public Map getServers(){ + Map resultMap = new LinkedHashMap<>(8); + try { + SystemInfo si = new SystemInfo(); + OperatingSystem os = si.getOperatingSystem(); + HardwareAbstractionLayer hal = si.getHardware(); + // 系统信息 + resultMap.put("sys", getSystemInfo(os)); + // cpu 信息 + resultMap.put("cpu", getCpuInfo(hal.getProcessor())); + // 内存信息 + resultMap.put("memory", getMemoryInfo(hal.getMemory())); + // 交换区信息 + resultMap.put("swap", getSwapInfo(hal.getMemory())); + // 磁盘 + resultMap.put("disk", getDiskInfo(os)); + resultMap.put("time", DateUtil.format(new Date(), "HH:mm:ss")); + } catch (Exception e) { + e.printStackTrace(); + } + return resultMap; + } + + /** + * 获取磁盘信息 + * @return / + */ + private Map getDiskInfo(OperatingSystem os) { + Map diskInfo = new LinkedHashMap<>(); + FileSystem fileSystem = os.getFileSystem(); + List fsArray = fileSystem.getFileStores(); + String osName = System.getProperty("os.name"); + long available = 0, total = 0; + for (OSFileStore fs : fsArray){ + // windows 需要将所有磁盘分区累加,linux 和 mac 直接累加会出现磁盘重复的问题,待修复 + if(osName.toLowerCase().startsWith(ElAdminConstant.WIN)) { + available += fs.getUsableSpace(); + total += fs.getTotalSpace(); + } else { + available = fs.getUsableSpace(); + total = fs.getTotalSpace(); + break; + } + } + long used = total - available; + diskInfo.put("total", total > 0 ? FileUtil.getSize(total) : "?"); + diskInfo.put("available", FileUtil.getSize(available)); + diskInfo.put("used", FileUtil.getSize(used)); + diskInfo.put("usageRate", df.format(used/(double)total * 100)); + return diskInfo; + } + + /** + * 获取交换区信息 + * @param memory / + * @return / + */ + private Map getSwapInfo(GlobalMemory memory) { + Map swapInfo = new LinkedHashMap<>(); + VirtualMemory virtualMemory = memory.getVirtualMemory(); + long total = virtualMemory.getSwapTotal(); + long used = virtualMemory.getSwapUsed(); + swapInfo.put("total", FormatUtil.formatBytes(total)); + swapInfo.put("used", FormatUtil.formatBytes(used)); + swapInfo.put("available", FormatUtil.formatBytes(total - used)); + if(used == 0){ + swapInfo.put("usageRate", 0); + } else { + swapInfo.put("usageRate", df.format(used/(double)total * 100)); + } + return swapInfo; + } + + /** + * 获取内存信息 + * @param memory / + * @return / + */ + private Map getMemoryInfo(GlobalMemory memory) { + Map memoryInfo = new LinkedHashMap<>(); + memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal())); + memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable())); + memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable())); + memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable())/(double)memory.getTotal() * 100)); + return memoryInfo; + } + + /** + * 获取Cpu相关信息 + * @param processor / + * @return / + */ + private Map getCpuInfo(CentralProcessor processor) { + Map cpuInfo = new LinkedHashMap<>(); + cpuInfo.put("name", processor.getProcessorIdentifier().getName()); + cpuInfo.put("package", processor.getPhysicalPackageCount() + "个物理CPU"); + cpuInfo.put("core", processor.getPhysicalProcessorCount() + "个物理核心"); + cpuInfo.put("coreNumber", processor.getPhysicalProcessorCount()); + cpuInfo.put("logic", processor.getLogicalProcessorCount() + "个逻辑CPU"); + // CPU信息 + long[] prevTicks = processor.getSystemCpuLoadTicks(); + // 等待1秒... + Util.sleep(1000); + long[] ticks = processor.getSystemCpuLoadTicks(); + long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; + long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; + long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; + long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; + long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; + long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; + long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; + long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; + long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal; + cpuInfo.put("used", df.format(100d * user / totalCpu + 100d * sys / totalCpu)); + cpuInfo.put("idle", df.format(100d * idle / totalCpu)); + return cpuInfo; + } + + /** + * 获取系统相关信息,系统、运行天数、系统IP + * @param os / + * @return / + */ + private Map getSystemInfo(OperatingSystem os){ + Map systemInfo = new LinkedHashMap<>(); + // jvm 运行时间 + long time = ManagementFactory.getRuntimeMXBean().getStartTime(); + Date date = new Date(time); + // 计算项目运行时间 5.4.3:BetweenFormater, 5.7.14改名为BetweenFormatter + String formatBetween = DateUtil.formatBetween(date, new Date(), BetweenFormatter.Level.HOUR); + // 系统信息 + systemInfo.put("os", os.toString()); + systemInfo.put("day", formatBetween); + systemInfo.put("ip", StringUtils.getLocalIp()); + return systemInfo; + } +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/ISysNoticeService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/ISysNoticeService.java new file mode 100644 index 0000000..2856250 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/ISysNoticeService.java @@ -0,0 +1,83 @@ +package org.nl.system.service.notice; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.notice.dao.SysNotice; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** +* @description 服务接口 +* @author lyd +* @date 2023-05-09 +**/ +public interface ISysNoticeService extends IService { + + /** + * 查询数据分页 + * @param whereJson 条件 + * @param pageable 分页参数 + * @return IPage + */ + IPage queryAll(Map whereJson, PageQuery pageable); + + /** + * 创建 + * @param entity / + */ + void create(SysNotice entity); + + /** + * 编辑 + * @param entity / + */ + void update(SysNotice entity); + + /** + * 多选删除 + * @param ids / + */ + void deleteAll(Set ids); + + /** + * 获取未读的接收消息条数 + */ + Integer countByReceiveNotRead(); + + /** + * 获取不同类型的前三条信息 + * @return + */ + LinkedList> pageByReceive(); + + /** + * 标记已读 + * @param id + */ + void read(String id); + + /** + * 处理信息 + * @param id + */ + void deal(String id); + + /** + * 批量已读 + * @param jsonObject + */ + void changeRead(JSONObject jsonObject); + + /** + * 写入信息 + * @param msg + * @param title + * @param type + */ + void createNotice(String msg, String title, String type); +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/SysNotice.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/SysNotice.java new file mode 100644 index 0000000..9b10d3a --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/SysNotice.java @@ -0,0 +1,51 @@ +package org.nl.system.service.notice.dao; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; + +/** +* @description / +* @author lyd +* @date 2023-05-09 +**/ +@Data +@Builder +@EqualsAndHashCode(callSuper = false) +@TableName("sys_notice") +public class SysNotice implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "notice_id", type = IdType.NONE) + @ApiModelProperty(value = "信息标识") + private String notice_id; + + @ApiModelProperty(value = "信息标题") + private String notice_title; + + @ApiModelProperty(value = "信息内容") + private String notice_content; + + @ApiModelProperty(value = "信息类型") + private String notice_type; + + @ApiModelProperty(value = "读取状态") + private String have_read; + + @ApiModelProperty(value = "读取时间") + private String read_time; + + @ApiModelProperty(value = "处理状态") + private String deal_status; + + @ApiModelProperty(value = "创建时间") + private String create_time; + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.java new file mode 100644 index 0000000..384f7cf --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.java @@ -0,0 +1,12 @@ +package org.nl.system.service.notice.dao.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.nl.system.service.notice.dao.SysNotice; + +/** +* @author lyd +* @date 2023-05-09 +**/ +public interface SysNoticeMapper extends BaseMapper { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.xml new file mode 100644 index 0000000..15b4868 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dao/mapper/SysNoticeMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeDto.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeDto.java new file mode 100644 index 0000000..cf427e1 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeDto.java @@ -0,0 +1,37 @@ +package org.nl.system.service.notice.dto; + +import lombok.Data; +import java.io.Serializable; + +/** +* @description / +* @author lyd +* @date 2023-05-09 +**/ +@Data +public class SysNoticeDto implements Serializable { + + /** 信息标识 */ + private String notice_id; + + /** 信息标题 */ + private String notice_title; + + /** 信息内容 */ + private String notice_content; + + /** 信息类型 */ + private String notice_type; + + /** 读取状态 */ + private String have_read; + + /** 读取时间 */ + private String read_time; + + /** 处理状态 */ + private String deal_status; + + /** 创建时间 */ + private String create_time; +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeQuery.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeQuery.java new file mode 100644 index 0000000..16a59bf --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/dto/SysNoticeQuery.java @@ -0,0 +1,12 @@ +package org.nl.system.service.notice.dto; + +import org.nl.common.domain.query.BaseQuery; +import org.nl.system.service.notice.dao.SysNotice; + +/** +* @author lyd +* @date 2023-05-09 +**/ +public class SysNoticeQuery extends BaseQuery { + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/impl/SysNoticeServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/impl/SysNoticeServiceImpl.java new file mode 100644 index 0000000..f41f485 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/notice/impl/SysNoticeServiceImpl.java @@ -0,0 +1,183 @@ +package org.nl.system.service.notice.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.enums.NoticeEnum; +import org.nl.common.exception.BadRequestException; +import org.nl.common.mnt.websocket.MsgType; +import org.nl.common.mnt.websocket.SocketMsg; +import org.nl.common.mnt.websocket.WebSocketServer; +import org.nl.common.utils.SecurityUtils; +import org.nl.system.service.dict.dao.Dict; +import org.nl.system.service.dict.dao.mapper.SysDictMapper; +import org.nl.system.service.notice.ISysNoticeService; +import org.nl.system.service.notice.dao.mapper.SysNoticeMapper; +import org.nl.system.service.notice.dao.SysNotice; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** +* @description 服务实现 +* @author lyd +* @date 2023-05-09 +**/ +@Slf4j +@Service +public class SysNoticeServiceImpl extends ServiceImpl implements ISysNoticeService { + + @Autowired + private SysNoticeMapper sysNoticeMapper; + + @Autowired + private SysDictMapper dictMapper; + + @Resource + private WebSocketServer webSocketServer; + + @Override + public IPage queryAll(Map whereJson, PageQuery page){ + String notice_title = ObjectUtil.isNotEmpty(whereJson.get("notice_title"))?whereJson.get("notice_title").toString():null; + String notice_type = ObjectUtil.isNotEmpty(whereJson.get("notice_type"))?whereJson.get("notice_type").toString():null; + String have_read = ObjectUtil.isNotEmpty(whereJson.get("have_read"))?whereJson.get("have_read").toString():null; + String deal_status = ObjectUtil.isNotEmpty(whereJson.get("deal_status"))?whereJson.get("deal_status").toString():null; + LambdaQueryWrapper lam = new LambdaQueryWrapper<>(); + lam.like(ObjectUtil.isNotEmpty(notice_title), SysNotice::getNotice_title, notice_title) + .eq(ObjectUtil.isNotEmpty(notice_type), SysNotice::getNotice_type, notice_type) + .eq(ObjectUtil.isNotEmpty(have_read), SysNotice::getHave_read, have_read) + .eq(ObjectUtil.isNotEmpty(deal_status), SysNotice::getDeal_status, deal_status) + .orderByAsc(SysNotice::getHave_read) + .orderByDesc(SysNotice::getCreate_time); + IPage pages = new Page<>(page.getPage() + 1, page.getSize()); + sysNoticeMapper.selectPage(pages, lam); + return pages; + } + + @Override + public void create(SysNotice entity) { + String now = DateUtil.now(); + + entity.setNotice_id(IdUtil.getSnowflake(1, 1).nextIdStr()); + entity.setCreate_time(now); + sysNoticeMapper.insert(entity); + } + + @Override + public void update(SysNotice entity) { + SysNotice dto = sysNoticeMapper.selectById(entity.getNotice_id()); + if (dto == null) throw new BadRequestException("被删除或无权限,操作失败!"); + sysNoticeMapper.updateById(entity); + } + + @Override + public void deleteAll(Set ids) { + // 真删除 + sysNoticeMapper.deleteBatchIds(ids); + } + + @Override + public Integer countByReceiveNotRead() { + List sysNotices = sysNoticeMapper.selectList(new LambdaQueryWrapper().eq(SysNotice::getHave_read, NoticeEnum.HAVE_READ_OFF.getValue())); + return ObjectUtil.isNotEmpty(sysNotices)?sysNotices.size():0; + } + + @Override + public LinkedList> pageByReceive() { + LinkedList> result = new LinkedList<>(); + List dictList = dictMapper.selectList(new LambdaQueryWrapper() + .eq(Dict::getCode, "notice_type") + .orderByAsc(Dict::getDict_sort)); + dictList.forEach(dict -> { + List sysNotices = sysNoticeMapper.selectList(new LambdaQueryWrapper() + .eq(SysNotice::getNotice_type, dict.getValue()) + .eq(SysNotice::getHave_read, NoticeEnum.HAVE_READ_OFF.getValue()) + .orderByDesc(SysNotice::getCreate_time) + .last("LIMIT 0,3")); + result.add(sysNotices); + }); + return result; + } + + @Override + public void read(String id) { + SysNotice notice = this.getById(id); + if (ObjectUtil.isEmpty(notice)) { + throw new BadRequestException("该信息不存在!"); + } + notice.setHave_read(NoticeEnum.HAVE_READ_ON.getValue()); + notice.setRead_time(DateUtil.now()); + sysNoticeMapper.updateById(notice); + } + + @Override + public void deal(String id) { + SysNotice notice = this.getById(id); + if (ObjectUtil.isEmpty(notice)) { + throw new BadRequestException("该信息不存在!"); + } + // 设置处理 + notice.setDeal_status(NoticeEnum.DEAL_STATUS_YES.getValue()); + // 判断是否读取 + if (notice.getHave_read().equals(NoticeEnum.HAVE_READ_OFF.getValue())) { + // 标记已读并设置读取时间 + notice.setHave_read(NoticeEnum.HAVE_READ_ON.getValue()); + notice.setRead_time(DateUtil.now()); + } + sysNoticeMapper.updateById(notice); + } + + @Override + public void changeRead(JSONObject jsonObject) { + JSONArray data = jsonObject.getJSONArray("data"); + String haveRead = jsonObject.getString("have_read"); + List sysNotices = JSON.parseArray(data.toJSONString(), SysNotice.class); + sysNotices.forEach(sysNotice -> sysNotice.setHave_read(haveRead)); + this.updateBatchById(sysNotices); + } + + @Override + public void createNotice(String msg, String title, String type) { + log.info("创建消息通知-信息:{}, 标题:{}, 类型:{}", msg, title, type); + // 获取标题相同的信息 + List sysNotices = sysNoticeMapper.selectList(new LambdaQueryWrapper().eq(SysNotice::getNotice_title, title)); + if (ObjectUtil.isNotEmpty(sysNotices)) return; + SysNotice noticeDto = SysNotice.builder() + .notice_id(IdUtil.getSnowflake(1,1).nextIdStr()) + .notice_type(type) + .notice_title(title) + .notice_content(msg) + .deal_status(NoticeEnum.DEAL_STATUS_NO.getValue()) + .have_read(NoticeEnum.HAVE_READ_OFF.getValue()) + .create_time(DateUtil.now()) + .build(); + // 插入 + sysNoticeMapper.insert(noticeDto); + JSONObject res = new JSONObject(); + res.put("data", "notice_message_update"); + SocketMsg messageInfo = new SocketMsg(res, MsgType.INFO); + try { + webSocketServer.sendInfo(messageInfo, "messageInfo"); + } catch (IOException e) { + throw new BadRequestException("消息发送失败"); + } + } + +} diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/Param.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/Param.java index 0cbb48e..b32705b 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/Param.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/Param.java @@ -2,11 +2,10 @@ package org.nl.system.service.param.dao; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; -import java.io.Serializable; - /** *

* 系统参数表 @@ -51,42 +50,42 @@ public class Param implements Serializable { /** * 是否启用 */ - private String isActive; + private Boolean is_active; /** * 是否删除 */ - private String isDelete; + private Boolean is_delete; /** * 创建者ID */ - private String createId; + private String create_id; /** * 创建者 */ - private String createName; + private String create_name; /** * 创建时间 */ - private String createTime; + private String create_time; /** * 修改者ID */ - private String updateId; + private String update_id; /** * 修改者 */ - private String updateName; + private String update_name; /** * 修改时间 */ - private String updateTime; + private String update_time; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/mapper/SysParamMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/mapper/SysParamMapper.java index 6b7b870..d2f5c86 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/mapper/SysParamMapper.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/dao/mapper/SysParamMapper.java @@ -1,7 +1,7 @@ package org.nl.system.service.param.dao.mapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.nl.system.service.param.dao.Param; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** *

diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/impl/SysParamServiceImpl.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/impl/SysParamServiceImpl.java index d58132d..a1578c3 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/impl/SysParamServiceImpl.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/param/impl/SysParamServiceImpl.java @@ -3,19 +3,19 @@ package org.nl.system.service.param.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.yomahub.tlog.core.annotation.TLogAspect; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.common.aspect.exception.BadRequestException; import org.nl.common.domain.query.PageQuery; -import org.nl.common.utils.MapOf; +import org.nl.common.exception.BadRequestException; import org.nl.common.utils.SecurityUtils; +import org.nl.config.MapOf; import org.nl.system.service.param.ISysParamService; import org.nl.system.service.param.dao.Param; import org.nl.system.service.param.dao.mapper.SysParamMapper; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -23,75 +23,75 @@ import java.util.List; import java.util.Map; /** + *

* 系统参数表 服务实现类 + *

* * @author generator * @since 2022-12-14 */ -@Service -@RequiredArgsConstructor @Slf4j -@Transactional -public class SysParamServiceImpl extends ServiceImpl - implements ISysParamService { +@Service +public class SysParamServiceImpl extends ServiceImpl implements ISysParamService { - private final SysParamMapper paramMapper; + @Autowired + private SysParamMapper paramMapper; - @Override - @TLogAspect - public Page queryPage(Map whereJson, PageQuery page) { - log.info("这是第一条日志"); - log.info("这是第二条日志"); - log.info("这是第三条日志"); - new Thread(() -> log.info("这是异步日志")).start(); + @Override + public Page queryPage(Map whereJson, PageQuery page) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.orderBy(true, true, "create_time"); + Page paramPage = paramMapper.selectPage(page.build(), queryWrapper); + return paramPage; + } + @Override + @Transactional(rollbackFor = Exception.class) + public void create(Param param) { + List code = paramMapper.selectByMap(MapOf.of("code", param.getCode())); + if (ObjectUtil.isNotEmpty(code)) throw new BadRequestException("编码不能一致"); + param.setId(IdUtil.getSnowflake(1, 1).nextIdStr()); + String currentUserId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + param.setCreate_id(currentUserId); + param.setCreate_name(nickName); + param.setCreate_time(now); + param.setUpdate_id(currentUserId); + param.setUpdate_name(nickName); + param.setUpdate_time(now); + paramMapper.insert(param); + } - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.orderBy(true, true, "create_time"); - Page paramPage = paramMapper.selectPage(page.build(), queryWrapper); - return paramPage; - } + @Override + @Transactional(rollbackFor = Exception.class) + public void update(Param param) { + Param paramObj = paramMapper.selectById(param.getId()); + if (ObjectUtil.isEmpty(paramObj)) { + throw new BadRequestException("被删除或无权限,操作失败!"); + } + Param param1 = paramMapper.selectOne(new LambdaQueryWrapper().eq(Param::getCode, param.getCode()) + .and(lam -> lam.ne(Param::getId, param.getId()))); + if (ObjectUtil.isNotEmpty(param1)) { + throw new BadRequestException("编码[" + param.getCode() + "]已存在"); + } + param.setUpdate_id(SecurityUtils.getCurrentUserId()); + param.setUpdate_name(SecurityUtils.getCurrentNickName()); + param.setUpdate_time(DateUtil.now()); + paramMapper.updateById(param); + } - @Override - @Transactional(rollbackFor = Exception.class) - public void create(Param param) { - List code = paramMapper.selectByMap(MapOf.of("code", param.getCode())); - if (ObjectUtil.isNotEmpty(code)) throw new BadRequestException("编码不能一致"); - param.setId(IdUtil.getSnowflake(1, 1).nextIdStr()); - String currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - param.setCreateId(currentUserId); - param.setCreateName(nickName); - param.setCreateTime(now); - param.setUpdateId(currentUserId); - param.setUpdateName(nickName); - param.setUpdateTime(now); - paramMapper.insert(param); - } + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteByIds(List ids) { + paramMapper.deleteBatchIds(ids); + } - @Override - @Transactional(rollbackFor = Exception.class) - public void update(Param param) { - Param paramObj = paramMapper.selectById(param.getId()); - if (ObjectUtil.isEmpty(paramObj)) throw new BadRequestException("被删除或无权限,操作失败!"); - param.setUpdateId(SecurityUtils.getCurrentUserId()); - param.setUpdateName(SecurityUtils.getCurrentNickName()); - param.setUpdateTime(DateUtil.now()); - paramMapper.updateById(param); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void deleteByIds(List ids) { - paramMapper.deleteBatchIds(ids); - } - - @Override - public Param findByCode(String code) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("code", code); - Param param = paramMapper.selectOne(queryWrapper); - return param; - } + @Override + public Param findByCode(String code) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("code", code); + Param param = paramMapper.selectOne(queryWrapper); + return param; + } } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/ISysDataPermissionService.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/ISysDataPermissionService.java index db0769f..58bf417 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/ISysDataPermissionService.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/ISysDataPermissionService.java @@ -2,10 +2,10 @@ package org.nl.system.service.permission; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.service.IService; import org.nl.common.domain.query.PageQuery; import org.nl.system.service.dict.dao.Dict; import org.nl.system.service.permission.dao.SysDataPermission; +import com.baomidou.mybatisplus.extension.service.IService; import org.nl.system.service.permission.dao.SysDataScope; import org.nl.system.service.permission.dto.SysDataPermissionQuery; import org.nl.system.service.user.dto.UserDataPermissionDto; @@ -33,7 +33,7 @@ public interface ISysDataPermissionService extends IService { /** * 新增数据权限 - * @param permission + * @param dto */ void create(SysDataPermission permission); diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataPermission.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataPermission.java index d796b17..a289345 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataPermission.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataPermission.java @@ -1,13 +1,14 @@ package org.nl.system.service.permission.dao; +import java.math.BigDecimal; + import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotNull; -import java.io.Serializable; -import java.math.BigDecimal; /** *

@@ -28,7 +29,7 @@ public class SysDataPermission implements Serializable { * permission_id */ @TableId(value = "permission_id") - private String permissionId; + private String permission_id; /** * 编码 @@ -45,7 +46,7 @@ public class SysDataPermission implements Serializable { /** * 排序 */ - private BigDecimal orderSort; + private BigDecimal order_sort; /** * 备注 @@ -55,42 +56,42 @@ public class SysDataPermission implements Serializable { /** * 是否启用 */ - private String isUsed; + private String is_used; /** * 是否删除 */ - private String isDelete; + private String is_delete; /** * 创建人标识 */ - private String createId; + private String create_id; /** * 创建人 */ - private String createName; + private String create_name; /** * 创建时间 */ - private String createTime; + private String create_time; /** * 修改人标识 */ - private String updateId; + private String update_id; /** * 修改人 */ - private String updateName; + private String update_name; /** * 修改时间 */ - private String updateTime; + private String update_time; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataScope.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataScope.java index 0160f66..41dc8ff 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataScope.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/SysDataScope.java @@ -1,12 +1,10 @@ package org.nl.system.service.permission.dao; -import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; -import java.io.Serializable; - /** *

* 数据权限规则表 @@ -25,32 +23,22 @@ public class SysDataScope implements Serializable { /** * 当前用户 */ - private String selfUserId; + private String self_user_id; /** * 数据权限类型 */ - private String permissionScopeType; + private String permission_scope_type; /** * 部门权限列表 */ - private String deptId; + private String dept_id; /** * 用户权限列表 */ - private String userId; + private String user_id; - @TableField(exist = false) - private String deptName; - @TableField(exist = false) - private String personName; - - @TableField(exist = false) - private String permissionName; - - @TableField(exist = false) - private String permissionId; } diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.java b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.java index cdcc817..0312e64 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.java +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.java @@ -1,8 +1,8 @@ package org.nl.system.service.permission.dao.mapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.nl.system.service.permission.dao.SysDataPermission; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.nl.system.service.permission.dao.SysDataScope; import java.util.List; diff --git a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.xml b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.xml index a8a0097..7311d1f 100644 --- a/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.xml +++ b/nladmin-system/nlsso-server/src/main/java/org/nl/system/service/permission/dao/mapper/SysDataPermissionMapper.xml @@ -3,11 +3,11 @@ INSERT INTO sys_data_scope(self_user_id, permission_scope_type, user_id) - VALUES (#{dataScope.selfUserId}, #{dataScope.permissionScopeType}, #{dataScope.userId}) + VALUES (#{dataScope.self_user_id}, #{dataScope.permission_scope_type}, #{dataScope.user_id}) INSERT INTO sys_data_scope(self_user_id, permission_scope_type, user_id, dept_id) - VALUES (#{dataScope.selfUserId}, #{dataScope.permissionScopeType}, #{dataScope.userId}, #{dataScope.deptId}) + VALUES (#{dataScope.self_user_id}, #{dataScope.permission_scope_type}, #{dataScope.user_id}, #{dataScope.dept_id}) DELETE FROM sys_data_scope WHERE self_user_id = #{userId} @@ -37,17 +37,17 @@ SELECT - ,sys_dept.dept_id as deptId - ,sys_dept.name as deptName - ,sys_users_roles.role_id as roleId + ,sys_dept.dept_id + ,sys_dept.name as dept_name + ,sys_users_roles.role_id FROM sys_user left join sys_user_dept on sys_user.user_id = sys_user_dept.user_id left join sys_users_roles on sys_users_roles.user_id = sys_user.user_id left join sys_dept on sys_user_dept.dept_id = sys_dept.dept_id - + and - sys_user.user_id in (select user_id from sys_user_dept where dept_id = #{query.deptId}) + sys_user.user_id in (select user_id from sys_user_dept where dept_id = #{query.dept_id}) - - and sys_user.is_used = #{query.isUsed} + + and sys_user.is_used = #{query.is_used} - + and and sys_user.create_time >= #{query.startTime} - - and #{query.endTime} >= sys_user.create_time + + and #{query.end_time} >= sys_user.create_time - and (email like "%"#{query.blurry}"%" or username like "%"#{query.blurry}"%" or person_name like "%"#{query.blurry}"%") + and (email like #{query.blurry} or username like #{query.blurry} or person_name like #{query.blurry}) @@ -110,7 +110,7 @@ and sys_user.is_used = #{query.isUsed} - and and sys_user.create_time >= #{query.startTime} + and sys_user.create_time >= #{query.startTime} and #{query.endTime} >= sys_user.create_time @@ -131,9 +131,9 @@ - - - -

-
-
- Port -
- -
-
- -
-
-
- AgentId -
- -
-
- -
- - - Arthas Output -
- - - - - -
-
-
-
-
- -
- -
- - - \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/resources/static/jquery-3.3.1.slim.min.js b/nladmin-system/nlsso-server/src/main/resources/static/jquery-3.3.1.slim.min.js deleted file mode 100755 index f4ca9b2..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/jquery-3.3.1.slim.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.3.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,u=n.push,s=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,d=f.toString,p=d.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},v=function e(t){return null!=t&&t===t.window},y={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in y)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function b(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var x="3.3.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector",w=function(e,t){return new w.fn.init(e,t)},C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:x,constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,u,s,l,c,f,d,p,h,g,v,y,m,b,x="sizzle"+1*new Date,w=e.document,C=0,T=0,E=ae(),N=ae(),k=ae(),A=function(e,t){return e===t&&(f=!0),0},D={}.hasOwnProperty,S=[],L=S.pop,j=S.push,q=S.push,O=S.slice,P=function(e,t){for(var n=0,r=e.length;n+~]|"+I+")"+I+"*"),_=new RegExp("="+I+"*([^\\]'\"]*?)"+I+"*\\]","g"),U=new RegExp(M),V=new RegExp("^"+R+"$"),X={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+B),PSEUDO:new RegExp("^"+M),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+I+"*(even|odd|(([+-]|)(\\d*)n|)"+I+"*(?:([+-]|)"+I+"*(\\d+)|))"+I+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+I+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+I+"*((?:-\\d)?\\d*)"+I+"*\\)|)(?=[^-]|$)","i")},Q=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,G=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,J=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+I+"?|("+I+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){d()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{q.apply(S=O.call(w.childNodes),w.childNodes),S[w.childNodes.length].nodeType}catch(e){q={apply:S.length?function(e,t){j.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,u,l,c,f,h,y,m=t&&t.ownerDocument,C=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==C&&9!==C&&11!==C)return r;if(!i&&((t?t.ownerDocument||t:w)!==p&&d(t),t=t||p,g)){if(11!==C&&(f=K.exec(e)))if(o=f[1]){if(9===C){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&b(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return q.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return q.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!k[e+" "]&&(!v||!v.test(e))){if(1!==C)m=t,y=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=x),u=(h=a(e)).length;while(u--)h[u]="#"+c+" "+ye(h[u]);y=h.join(","),m=J.test(e)&&ge(t.parentNode)||t}if(y)try{return q.apply(r,m.querySelectorAll(y)),r}catch(e){}finally{c===x&&t.removeAttribute("id")}}}return s(e.replace($,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ue(e){return e[x]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function de(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ue(function(t){return t=+t,ue(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},d=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==p&&9===a.nodeType&&a.documentElement?(p=a,h=p.documentElement,g=!o(p),w!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=G.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=x,!p.getElementsByName||!p.getElementsByName(x).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],v=[],(n.qsa=G.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+I+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+I+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+x+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+x+"+*").length||v.push(".#.+[+~]")}),se(function(e){e.innerHTML="";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+I+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(n.matchesSelector=G.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),y.push("!=",M)}),v=v.length&&new RegExp(v.join("|")),y=y.length&&new RegExp(y.join("|")),t=G.test(h.compareDocumentPosition),b=t||G.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===w&&b(w,e)?-1:t===p||t.ownerDocument===w&&b(w,t)?1:c?P(c,e)-P(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],u=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:c?P(c,e)-P(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)u.unshift(n);while(a[r]===u[r])r++;return r?ce(a[r],u[r]):a[r]===w?-1:u[r]===w?1:0},p):p},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),t=t.replace(_,"='$1']"),n.matchesSelector&&g&&!k[t+" "]&&(!y||!y.test(t))&&(!v||!v.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,p,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),b(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&D.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(A),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:ue,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return X.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&U.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+I+")"+e+"("+I+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(W," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),u="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,s){var l,c,f,d,p,h,g=o!==a?"nextSibling":"previousSibling",v=t.parentNode,y=u&&t.nodeName.toLowerCase(),m=!s&&!u,b=!1;if(v){if(o){while(g){d=t;while(d=d[g])if(u?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?v.firstChild:v.lastChild],a&&m){b=(p=(l=(c=(f=(d=v)[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===C&&l[1])&&l[2],d=p&&v.childNodes[p];while(d=++p&&d&&d[g]||(b=p=0)||h.pop())if(1===d.nodeType&&++b&&d===t){c[e]=[C,p,b];break}}else if(m&&(b=p=(l=(c=(f=(d=t)[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===C&&l[1]),!1===b)while(d=++p&&d&&d[g]||(b=p=0)||h.pop())if((u?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++b&&(m&&((c=(f=d[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[C,b]),d===t))break;return(b-=i)===r||b%r==0&&b/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[x]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ue(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=P(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ue(function(e){var t=[],n=[],r=u(e.replace($,"$1"));return r[x]?ue(function(e,t,n,i){var o,a=r(e,null,i,[]),u=e.length;while(u--)(o=a[u])&&(e[u]=!(t[u]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ue(function(e){return function(t){return oe(e,t).length>0}}),contains:ue(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:ue(function(e){return V.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xe(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else y=we(y===a?y.splice(h,y.length):y),i?i(null,a,y,s):q.apply(a,y)})}function Te(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],u=a||r.relative[" "],s=a?1:0,c=me(function(e){return e===t},u,!0),f=me(function(e){return P(t,e)>-1},u,!0),d=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];s1&&be(d),s>1&&ye(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace($,"$1"),n,s0,i=e.length>0,o=function(o,a,u,s,c){var f,h,v,y=0,m="0",b=o&&[],x=[],w=l,T=o||i&&r.find.TAG("*",c),E=C+=null==w?1:Math.random()||.1,N=T.length;for(c&&(l=a===p||a||c);m!==N&&null!=(f=T[m]);m++){if(i&&f){h=0,a||f.ownerDocument===p||(d(f),u=!g);while(v=e[h++])if(v(f,a||p,u)){s.push(f);break}c&&(C=E)}n&&((f=!v&&f)&&y--,o&&b.push(f))}if(y+=m,n&&m!==y){h=0;while(v=t[h++])v(b,x,a,u);if(o){if(y>0)while(m--)b[m]||x[m]||(x[m]=L.call(s));x=we(x)}q.apply(s,x),c&&!o&&x.length>0&&y+t.length>1&&oe.uniqueSort(s)}return c&&(C=E,l=w),b};return n?ue(o):o}return u=oe.compile=function(e,t){var n,r=[],i=[],o=k[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Te(t[n]))[x]?r.push(o):i.push(o);(o=k(e,Ee(i,r))).selector=e}return o},s=oe.select=function(e,t,n,i){var o,s,l,c,f,d="function"==typeof e&&e,p=!i&&a(e=d.selector||e);if(n=n||[],1===p.length){if((s=p[0]=p[0].slice(0)).length>2&&"ID"===(l=s[0]).type&&9===t.nodeType&&g&&r.relative[s[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(s.shift().value.length)}o=X.needsContext.test(e)?0:s.length;while(o--){if(l=s[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),J.test(s[0].type)&&ge(t.parentNode)||t))){if(s.splice(o,1),!(e=i.length&&ye(s)))return q.apply(n,i),n;break}}}return(d||u(e,p))(i,t,!g,n,!t||J.test(e)&&ge(t.parentNode)||t),n},n.sortStable=x.split("").sort(A).join("")===x,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||le(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var N=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},k=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},A=w.expr.match.needsContext;function D(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var S=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function L(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return s.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(L(this,e||[],!1))},not:function(e){return this.pushStack(L(this,e||[],!0))},is:function(e){return!!L(this,"string"==typeof e&&A.test(e)?w(e):e||[],!1).length}});var j,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:q.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),S.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,j=w(r);var O=/^(?:parents|prev(?:Until|All))/,P={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?s.call(w(e),this[0]):s.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function H(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return N(e,"parentNode")},parentsUntil:function(e,t,n){return N(e,"parentNode",n)},next:function(e){return H(e,"nextSibling")},prev:function(e){return H(e,"previousSibling")},nextAll:function(e){return N(e,"nextSibling")},prevAll:function(e){return N(e,"previousSibling")},nextUntil:function(e,t,n){return N(e,"nextSibling",n)},prevUntil:function(e,t,n){return N(e,"previousSibling",n)},siblings:function(e){return k((e.parentNode||{}).firstChild,e)},children:function(e){return k(e.firstChild)},contents:function(e){return D(e,"iframe")?e.contentDocument:(D(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(P[e]||w.uniqueSort(i),O.test(e)&&i.reverse()),this.pushStack(i)}});var I=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(I)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],u=-1,s=function(){for(i=i||e.once,r=t=!0;a.length;u=-1){n=a.shift();while(++u-1)o.splice(n,1),n<=u&&u--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||s()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function B(e){return e}function M(e){throw e}function W(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var u=this,s=arguments,l=function(){var e,l;if(!(t=o&&(r!==M&&(u=void 0,s=[e]),n.rejectWith(u,s))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:B,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:B)),n[2][3].add(a(0,e,g(r)?r:M))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],u=t[5];i[t[1]]=a.add,u&&a.add(function(){r=u},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),u=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&(W(e,a.done(u(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)W(i[n],u(n),a.reject);return a.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&$.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function z(){r.removeEventListener("DOMContentLoaded",z),e.removeEventListener("load",z),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",z),e.addEventListener("load",z));var _=function(e,t,n,r,i,o,a){var u=0,s=e.length,l=null==n;if("object"===b(n)){i=!0;for(u in n)_(e,t,u,n[u],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;u1,null,!0)},removeData:function(e){return this.each(function(){J.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=K.get(e,t),n&&(!r||Array.isArray(n)?r=K.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return K.get(e,n)||K.access(e,n,{empty:w.Callbacks("once memory").add(function(){K.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&D(e,t)?w.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var xe=r.documentElement,we=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Te=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function Ne(){return!1}function ke(){try{return r.activeElement}catch(e){}}function Ae(e,t,n,r,i,o){var a,u;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(u in t)Ae(e,u,n,r,t[u],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ne;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,u,s,l,c,f,d,p,h,g,v=K.get(e);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(xe,i),n.guid||(n.guid=w.guid++),(s=v.events)||(s=v.events={}),(a=v.handle)||(a=v.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(I)||[""]).length;while(l--)p=g=(u=Te.exec(t[l])||[])[1],h=(u[2]||"").split(".").sort(),p&&(f=w.event.special[p]||{},p=(i?f.delegateType:f.bindType)||p,f=w.event.special[p]||{},c=w.extend({type:p,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(d=s[p])||((d=s[p]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(p,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,c):d.push(c),w.event.global[p]=!0)}},remove:function(e,t,n,r,i){var o,a,u,s,l,c,f,d,p,h,g,v=K.hasData(e)&&K.get(e);if(v&&(s=v.events)){l=(t=(t||"").match(I)||[""]).length;while(l--)if(u=Te.exec(t[l])||[],p=g=u[1],h=(u[2]||"").split(".").sort(),p){f=w.event.special[p]||{},d=s[p=(r?f.delegateType:f.bindType)||p]||[],u=u[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=d.length;while(o--)c=d[o],!i&&g!==c.origType||n&&n.guid!==c.guid||u&&!u.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(d.splice(o,1),c.selector&&d.delegateCount--,f.remove&&f.remove.call(e,c));a&&!d.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||w.removeEvent(e,p,v.handle),delete s[p])}else for(p in s)w.event.remove(e,p+t[l],n,r,!0);w.isEmptyObject(s)&&K.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,u,s=new Array(arguments.length),l=(K.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(s[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&u.push({elem:l,handlers:o})}return l=this,s\x20\t\r\n\f]*)[^>]*)\/>/gi,Se=/\s*$/g;function qe(e,t){return D(e,"table")&&D(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function Oe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Pe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function He(e,t){var n,r,i,o,a,u,s,l;if(1===t.nodeType){if(K.hasData(e)&&(o=K.access(e),a=K.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof v&&!h.checkClone&&Le.test(v))return e.each(function(i){var o=e.eq(i);y&&(t[0]=v.call(this,i,o.html())),Re(o,t,n,r)});if(d&&(i=be(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(s=(u=w.map(ve(i,"script"),Oe)).length;f")},clone:function(e,t,n){var r,i,o,a,u=e.cloneNode(!0),s=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ve(u),r=0,i=(o=ve(e)).length;r0&&ye(a,!s&&ve(e,"script")),u},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[K.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[K.expando]=void 0}n[J.expando]&&(n[J.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Be(this,e,!0)},remove:function(e){return Be(this,e)},text:function(e){return _(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||qe(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=qe(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return _(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Se.test(e)&&!ge[(pe.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(s+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-s-u-.5))),s}function et(e,t,n){var r=We(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(Me.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,u=Q(t),s=Ue.test(t),l=e.style;if(s||(t=Ke(u)),a=w.cssHooks[t]||w.cssHooks[u],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[u]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(s?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,u=Q(t);return Ue.test(t)||(t=Ke(u)),(a=w.cssHooks[t]||w.cssHooks[u])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Xe&&(i=Xe[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!_e.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):ue(e,Ve,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=We(e),a="border-box"===w.css(e,"boxSizing",!1,o),u=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(u-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),u&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Je(e,n,u)}}}),w.cssHooks.marginLeft=ze(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-ue(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Je)}),w.fn.extend({css:function(e,t){return _(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=We(e),i=t.length;a1)}}),w.fn.delay=function(t,n){return t=w.fx?w.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e=r.createElement("input"),t=r.createElement("select").appendChild(r.createElement("option"));e.type="checkbox",h.checkOn=""!==e.value,h.optSelected=t.selected,(e=r.createElement("input")).value="t",e.type="radio",h.radioValue="t"===e.value}();var tt,nt=w.expr.attrHandle;w.fn.extend({attr:function(e,t){return _(this,w.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?tt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&D(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(I);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),tt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=nt[t]||w.find.attr;nt[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=nt[a],nt[a]=i,i=null!=n(e,t,r)?a:null,nt[a]=o),i}});var rt=/^(?:input|select|textarea|button)$/i,it=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return _(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):rt.test(e.nodeName)||it.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function ot(e){return(e.match(I)||[]).join(" ")}function at(e){return e.getAttribute&&e.getAttribute("class")||""}function ut(e){return Array.isArray(e)?e:"string"==typeof e?e.match(I)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,u,s=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,at(this)))});if((t=ut(e)).length)while(n=this[s++])if(i=at(n),r=1===n.nodeType&&" "+ot(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(u=ot(r))&&n.setAttribute("class",u)}return this},removeClass:function(e){var t,n,r,i,o,a,u,s=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,at(this)))});if(!arguments.length)return this.attr("class","");if((t=ut(e)).length)while(n=this[s++])if(i=at(n),r=1===n.nodeType&&" "+ot(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(u=ot(r))&&n.setAttribute("class",u)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,at(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=ut(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=at(this))&&K.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":K.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+ot(at(n))+" ").indexOf(t)>-1)return!0;return!1}});var st=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(st,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:ot(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,u=a?null:[],s=a?o+1:i.length;for(r=o<0?s:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var lt=/^(?:focusinfocus|focusoutblur)$/,ct=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,u,s,l,c,d,p,h,y=[i||r],m=f.call(t,"type")?t.type:t,b=f.call(t,"namespace")?t.namespace.split("."):[];if(u=h=s=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!lt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(b=m.split(".")).shift(),b.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=b.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),p=w.event.special[m]||{},o||!p.trigger||!1!==p.trigger.apply(i,n))){if(!o&&!p.noBubble&&!v(i)){for(l=p.delegateType||m,lt.test(l+m)||(u=u.parentNode);u;u=u.parentNode)y.push(u),s=u;s===(i.ownerDocument||r)&&y.push(s.defaultView||s.parentWindow||e)}a=0;while((u=y[a++])&&!t.isPropagationStopped())h=u,t.type=a>1?l:p.bindType||m,(d=(K.get(u,"events")||{})[t.type]&&K.get(u,"handle"))&&d.apply(u,n),(d=c&&u[c])&&d.apply&&Y(u)&&(t.result=d.apply(u,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||p._default&&!1!==p._default.apply(y.pop(),n)||!Y(i)||c&&g(i[m])&&!v(i)&&((s=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,ct),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,ct),w.event.triggered=void 0,s&&(i[c]=s)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=K.access(r,t);i||r.addEventListener(e,n,!0),K.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=K.access(r,t)-1;i?K.access(r,t,i):(r.removeEventListener(e,n,!0),K.remove(r,t))}}});var ft=/\[\]$/,dt=/\r?\n/g,pt=/^(?:submit|button|image|reset|file)$/i,ht=/^(?:input|select|textarea|keygen)/i;function gt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||ft.test(e)?r(e,i):gt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==b(t))r(e,t);else for(i in t)gt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)gt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&ht.test(this.nodeName)&&!pt.test(e)&&(this.checked||!de.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(dt,"\r\n")}}):{name:t.name,value:n.replace(dt,"\r\n")}}).get()}}),w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},h.createHTMLDocument=function(){var e=r.implementation.createHTMLDocument("").body;return e.innerHTML="
",2===e.childNodes.length}(),w.parseHTML=function(e,t,n){if("string"!=typeof e)return[];"boolean"==typeof t&&(n=t,t=!1);var i,o,a;return t||(h.createHTMLDocument?((i=(t=r.implementation.createHTMLDocument("")).createElement("base")).href=r.location.href,t.head.appendChild(i)):t=r),o=S.exec(e),a=!n&&[],o?[t.createElement(o[1])]:(o=be([e],t,a),a&&a.length&&w(a).remove(),w.merge([],o.childNodes))},w.offset={setOffset:function(e,t,n){var r,i,o,a,u,s,l,c=w.css(e,"position"),f=w(e),d={};"static"===c&&(e.style.position="relative"),u=f.offset(),o=w.css(e,"top"),s=w.css(e,"left"),(l=("absolute"===c||"fixed"===c)&&(o+s).indexOf("auto")>-1)?(a=(r=f.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(s)||0),g(t)&&(t=t.call(e,n,w.extend({},u))),null!=t.top&&(d.top=t.top-u.top+a),null!=t.left&&(d.left=t.left-u.left+i),"using"in t?t.using.call(e,d):f.css(d)}},w.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){w.offset.setOffset(this,e,t)});var t,n,r=this[0];if(r)return r.getClientRects().length?(t=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:t.top+n.pageYOffset,left:t.left+n.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===w.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===w.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),i.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-w.css(r,"marginTop",!0),left:t.left-i.left-w.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===w.css(e,"position"))e=e.offsetParent;return e||xe})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;w.fn[e]=function(r){return _(this,function(e,r,i){var o;if(v(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===i)return o?o[t]:e[r];o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):e[r]=i},e,r,arguments.length)}}),w.each(["top","left"],function(e,t){w.cssHooks[t]=ze(h.pixelPosition,function(e,n){if(n)return n=Fe(e,t),Me.test(n)?w(e).position()[t]+"px":n})}),w.each({Height:"height",Width:"width"},function(e,t){w.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){w.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),u=n||(!0===i||!0===o?"margin":"border");return _(this,function(t,n,i){var o;return v(t)?0===r.indexOf("outer")?t["inner"+e]:t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?w.css(t,n,u):w.style(t,n,i,u)},t,a?i:void 0,a)}})}),w.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,t){w.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),w.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),w.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),w.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),g(e))return r=o.call(arguments,2),i=function(){return e.apply(t||this,r.concat(o.call(arguments)))},i.guid=e.guid=e.guid||w.guid++,i},w.holdReady=function(e){e?w.readyWait++:w.ready(!0)},w.isArray=Array.isArray,w.parseJSON=JSON.parse,w.nodeName=D,w.isFunction=g,w.isWindow=v,w.camelCase=Q,w.type=b,w.now=Date.now,w.isNumeric=function(e){var t=w.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return w});var vt=e.jQuery,yt=e.$;return w.noConflict=function(t){return e.$===w&&(e.$=yt),t&&e.jQuery===w&&(e.jQuery=vt),w},t||(e.jQuery=e.$=w),w}); diff --git a/nladmin-system/nlsso-server/src/main/resources/static/logo.png b/nladmin-system/nlsso-server/src/main/resources/static/logo.png deleted file mode 100755 index a58394e..0000000 Binary files a/nladmin-system/nlsso-server/src/main/resources/static/logo.png and /dev/null differ diff --git a/nladmin-system/nlsso-server/src/main/resources/static/main.css b/nladmin-system/nlsso-server/src/main/resources/static/main.css deleted file mode 100755 index 9c15ed8..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/main.css +++ /dev/null @@ -1,20 +0,0 @@ -#terminal:-webkit-full-screen{ - background-color: rgb(255, 255, 12); -} -.container { - width: 100%; - min-height: 600px; -} -.fullSc { - z-index: 10000; - position: fixed; - top: 25%; - left: 90%; - display: none; -} -#fullScBtn { - border-radius:17px; - border: 0; - cursor: pointer; - background-color: black; -} \ No newline at end of file diff --git a/nladmin-system/nlsso-server/src/main/resources/static/popper-1.14.6.min.js b/nladmin-system/nlsso-server/src/main/resources/static/popper-1.14.6.min.js deleted file mode 100755 index 9b7dbeb..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/popper-1.14.6.min.js +++ /dev/null @@ -1,5 +0,0 @@ -/* - Copyright (C) Federico Zivolo 2018 - Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). - */(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?module.exports=t():'function'==typeof define&&define.amd?define(t):e.Popper=t()})(this,function(){'use strict';function e(e){return e&&'[object Function]'==={}.toString.call(e)}function t(e,t){if(1!==e.nodeType)return[];var o=e.ownerDocument.defaultView,n=o.getComputedStyle(e,null);return t?n[t]:n}function o(e){return'HTML'===e.nodeName?e:e.parentNode||e.host}function n(e){if(!e)return document.body;switch(e.nodeName){case'HTML':case'BODY':return e.ownerDocument.body;case'#document':return e.body;}var i=t(e),r=i.overflow,p=i.overflowX,s=i.overflowY;return /(auto|scroll|overlay)/.test(r+s+p)?e:n(o(e))}function r(e){return 11===e?pe:10===e?se:pe||se}function p(e){if(!e)return document.documentElement;for(var o=r(10)?document.body:null,n=e.offsetParent||null;n===o&&e.nextElementSibling;)n=(e=e.nextElementSibling).offsetParent;var i=n&&n.nodeName;return i&&'BODY'!==i&&'HTML'!==i?-1!==['TH','TD','TABLE'].indexOf(n.nodeName)&&'static'===t(n,'position')?p(n):n:e?e.ownerDocument.documentElement:document.documentElement}function s(e){var t=e.nodeName;return'BODY'!==t&&('HTML'===t||p(e.firstElementChild)===e)}function d(e){return null===e.parentNode?e:d(e.parentNode)}function a(e,t){if(!e||!e.nodeType||!t||!t.nodeType)return document.documentElement;var o=e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING,n=o?e:t,i=o?t:e,r=document.createRange();r.setStart(n,0),r.setEnd(i,0);var l=r.commonAncestorContainer;if(e!==l&&t!==l||n.contains(i))return s(l)?l:p(l);var f=d(e);return f.host?a(f.host,t):a(e,d(t).host)}function l(e){var t=1=o.clientWidth&&n>=o.clientHeight}),l=0a[e]&&!t.escapeWithReference&&(n=Q(f[o],a[e]-('right'===e?f.width:f.height))),le({},o,n)}};return l.forEach(function(e){var t=-1===['left','top'].indexOf(e)?'secondary':'primary';f=fe({},f,m[t](e))}),e.offsets.popper=f,e},priority:['left','right','top','bottom'],padding:5,boundariesElement:'scrollParent'},keepTogether:{order:400,enabled:!0,fn:function(e){var t=e.offsets,o=t.popper,n=t.reference,i=e.placement.split('-')[0],r=Z,p=-1!==['top','bottom'].indexOf(i),s=p?'right':'bottom',d=p?'left':'top',a=p?'width':'height';return o[s]r(n[s])&&(e.offsets.popper[d]=r(n[s])),e}},arrow:{order:500,enabled:!0,fn:function(e,o){var n;if(!K(e.instance.modifiers,'arrow','keepTogether'))return e;var i=o.element;if('string'==typeof i){if(i=e.instance.popper.querySelector(i),!i)return e;}else if(!e.instance.popper.contains(i))return console.warn('WARNING: `arrow.element` must be child of its popper element!'),e;var r=e.placement.split('-')[0],p=e.offsets,s=p.popper,d=p.reference,a=-1!==['left','right'].indexOf(r),l=a?'height':'width',f=a?'Top':'Left',m=f.toLowerCase(),h=a?'left':'top',c=a?'bottom':'right',u=S(i)[l];d[c]-us[c]&&(e.offsets.popper[m]+=d[m]+u-s[c]),e.offsets.popper=g(e.offsets.popper);var b=d[m]+d[l]/2-u/2,w=t(e.instance.popper),y=parseFloat(w['margin'+f],10),E=parseFloat(w['border'+f+'Width'],10),v=b-e.offsets.popper[m]-y-E;return v=ee(Q(s[l]-u,v),0),e.arrowElement=i,e.offsets.arrow=(n={},le(n,m,$(v)),le(n,h,''),n),e},element:'[x-arrow]'},flip:{order:600,enabled:!0,fn:function(e,t){if(W(e.instance.modifiers,'inner'))return e;if(e.flipped&&e.placement===e.originalPlacement)return e;var o=v(e.instance.popper,e.instance.reference,t.padding,t.boundariesElement,e.positionFixed),n=e.placement.split('-')[0],i=T(n),r=e.placement.split('-')[1]||'',p=[];switch(t.behavior){case ge.FLIP:p=[n,i];break;case ge.CLOCKWISE:p=G(n);break;case ge.COUNTERCLOCKWISE:p=G(n,!0);break;default:p=t.behavior;}return p.forEach(function(s,d){if(n!==s||p.length===d+1)return e;n=e.placement.split('-')[0],i=T(n);var a=e.offsets.popper,l=e.offsets.reference,f=Z,m='left'===n&&f(a.right)>f(l.left)||'right'===n&&f(a.left)f(l.top)||'bottom'===n&&f(a.top)f(o.right),g=f(a.top)f(o.bottom),b='left'===n&&h||'right'===n&&c||'top'===n&&g||'bottom'===n&&u,w=-1!==['top','bottom'].indexOf(n),y=!!t.flipVariations&&(w&&'start'===r&&h||w&&'end'===r&&c||!w&&'start'===r&&g||!w&&'end'===r&&u);(m||b||y)&&(e.flipped=!0,(m||b)&&(n=p[d+1]),y&&(r=z(r)),e.placement=n+(r?'-'+r:''),e.offsets.popper=fe({},e.offsets.popper,D(e.instance.popper,e.offsets.reference,e.placement)),e=P(e.instance.modifiers,e,'flip'))}),e},behavior:'flip',padding:5,boundariesElement:'viewport'},inner:{order:700,enabled:!1,fn:function(e){var t=e.placement,o=t.split('-')[0],n=e.offsets,i=n.popper,r=n.reference,p=-1!==['left','right'].indexOf(o),s=-1===['top','left'].indexOf(o);return i[p?'left':'top']=r[o]-(s?i[p?'width':'height']:0),e.placement=T(t),e.offsets.popper=g(i),e}},hide:{order:800,enabled:!0,fn:function(e){if(!K(e.instance.modifiers,'hide','preventOverflow'))return e;var t=e.offsets.reference,o=C(e.instance.modifiers,function(e){return'preventOverflow'===e.name}).boundaries;if(t.bottomo.right||t.top>o.bottom||t.rightwindow.devicePixelRatio||!me),c='bottom'===o?'top':'bottom',g='right'===n?'left':'right',b=H('transform');if(d='bottom'==c?'HTML'===l.nodeName?-l.clientHeight+h.bottom:-f.height+h.bottom:h.top,s='right'==g?'HTML'===l.nodeName?-l.clientWidth+h.right:-f.width+h.right:h.left,a&&b)m[b]='translate3d('+s+'px, '+d+'px, 0)',m[c]=0,m[g]=0,m.willChange='transform';else{var w='bottom'==c?-1:1,y='right'==g?-1:1;m[c]=d*w,m[g]=s*y,m.willChange=c+', '+g}var E={"x-placement":e.placement};return e.attributes=fe({},E,e.attributes),e.styles=fe({},m,e.styles),e.arrowStyles=fe({},e.offsets.arrow,e.arrowStyles),e},gpuAcceleration:!0,x:'bottom',y:'right'},applyStyle:{order:900,enabled:!0,fn:function(e){return j(e.instance.popper,e.styles),V(e.instance.popper,e.attributes),e.arrowElement&&Object.keys(e.arrowStyles).length&&j(e.arrowElement,e.arrowStyles),e},onLoad:function(e,t,o,n,i){var r=L(i,t,e,o.positionFixed),p=O(o.placement,r,t,e,o.modifiers.flip.boundariesElement,o.modifiers.flip.padding);return t.setAttribute('x-placement',p),j(t,{position:o.positionFixed?'fixed':'absolute'}),o},gpuAcceleration:void 0}}},ue}); -//# sourceMappingURL=popper.min.js.map diff --git a/nladmin-system/nlsso-server/src/main/resources/static/web-console.js b/nladmin-system/nlsso-server/src/main/resources/static/web-console.js deleted file mode 100755 index 5fb9b60..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/web-console.js +++ /dev/null @@ -1,206 +0,0 @@ -var ws; -var xterm; - -$(function () { - var url = window.location.href; - var ip = getUrlParam('ip'); - var port = getUrlParam('port'); - var agentId = getUrlParam('agentId'); - - if (ip != '' && ip != null) { - $('#ip').val(ip); - } else { - $('#ip').val(window.location.hostname); - } - if (port != '' && port != null) { - $('#port').val(port); - } - if (agentId != '' && agentId != null) { - $('#agentId').val(agentId); - } - - var iframe = getUrlParam('iframe'); - if (iframe != null && iframe != 'false') { - $("nav").hide() - } - - startConnect(true); -}); - -/** get params in url **/ -function getUrlParam (name, url) { - if (!url) url = window.location.href; - name = name.replace(/[\[\]]/g, '\\$&'); - var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), - results = regex.exec(url); - if (!results) return null; - if (!results[2]) return ''; - return decodeURIComponent(results[2].replace(/\+/g, ' ')); -} - -function getCharSize () { - var tempDiv = $('
').attr({'role': 'listitem'}); - var tempSpan = $('
').html('qwertyuiopasdfghjklzxcvbnm'); - tempDiv.append(tempSpan); - $("html body").append(tempDiv); - var size = { - width: tempSpan.outerWidth() / 26, - height: tempSpan.outerHeight(), - left: tempDiv.outerWidth() - tempSpan.outerWidth(), - top: tempDiv.outerHeight() - tempSpan.outerHeight(), - }; - tempDiv.remove(); - return size; -} - -function getWindowSize () { - var e = window; - var a = 'inner'; - if (!('innerWidth' in window )) { - a = 'client'; - e = document.documentElement || document.body; - } - var terminalDiv = document.getElementById("terminal-card"); - var terminalDivRect = terminalDiv.getBoundingClientRect(); - return { - width: terminalDivRect.width, - height: e[a + 'Height'] - terminalDivRect.top - }; -} - -function getTerminalSize () { - var charSize = getCharSize(); - var windowSize = getWindowSize(); - console.log('charsize'); - console.log(charSize); - console.log('windowSize'); - console.log(windowSize); - return { - cols: Math.floor((windowSize.width - charSize.left) / 10), - rows: Math.floor((windowSize.height - charSize.top) / 17) - }; -} - -/** init websocket **/ -function initWs (ip, port, path, agentId, targetServer) { - var protocol= location.protocol === 'https:' ? 'wss://' : 'ws://'; - var uri = protocol + ip + ':' + port + '/' + encodeURIComponent(path) + '?method=connectArthas&id=' + agentId; - if (targetServer != null) { - uri = uri + '&targetServer=' + encodeURIComponent(targetServer); - } - ws = new WebSocket(uri); -} - -/** init xterm **/ -function initXterm (cols, rows) { - xterm = new Terminal({ - cols: cols, - rows: rows, - screenReaderMode: true, - rendererType: 'canvas', - convertEol: true - }); -} - -/** begin connect **/ -function startConnect (silent) { - var ip = $('#ip').val(); - var port = $('#port').val(); - var agentId = $('#agentId').val(); - if (ip == '' || port == '') { - alert('Ip or port can not be empty'); - return; - } - if (agentId == '') { - if (silent) { - return; - } - alert('AgentId can not be empty'); - return; - } - if (ws != null) { - alert('Already connected'); - return; - } - - var path = getUrlParam('path'); - if (path == null) { - path = "ws"; - } - - var targetServer = getUrlParam('targetServer'); - - // init webSocket - initWs(ip, port, path, agentId, targetServer); - ws.onerror = function () { - ws.close(); - ws = null; - !silent && alert('Connect error'); - }; - ws.onclose = function (message) { - if (message.code === 2000) { - alert(message.reason); - } - }; - ws.onopen = function () { - console.log('open'); - $('#fullSc').show(); - var terminalSize = getTerminalSize() - console.log('terminalSize') - console.log(terminalSize) - // init xterm - initXterm(terminalSize.cols, terminalSize.rows) - ws.onmessage = function (event) { - if (event.type === 'message') { - var data = event.data; - xterm.write(data); - } - }; - xterm.open(document.getElementById('terminal')); - xterm.on('data', function (data) { - ws.send(JSON.stringify({action: 'read', data: data})) - }); - ws.send(JSON.stringify({action: 'resize', cols: terminalSize.cols, rows: terminalSize.rows})); - window.setInterval(function () { - if (ws != null && ws.readyState === 1) { - ws.send(JSON.stringify({action: 'read', data: ""})); - } - }, 30000); - } -} - -function disconnect () { - try { - ws.close(); - ws.onmessage = null; - ws.onclose = null; - ws = null; - xterm.destroy(); - $('#fullSc').hide(); - alert('Connection was closed successfully!'); - } catch (e) { - alert('No connection, please start connect first.'); - } -} - -function updateArthasOutputLink() { - $('#arthasOutputA').prop("href", "proxy/" + $('#agentId').val() + "/arthas-output/") -} - -/** full screen show **/ -function xtermFullScreen () { - var ele = document.getElementById('terminal-card'); - requestFullScreen(ele); -} - -function requestFullScreen (element) { - var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen; - if (requestMethod) { - requestMethod.call(element); - } else if (typeof window.ActiveXObject !== "undefined") { - var wscript = new ActiveXObject("WScript.Shell"); - if (wscript !== null) { - wscript.SendKeys("{F11}"); - } - } -} diff --git a/nladmin-system/nlsso-server/src/main/resources/static/xterm.css b/nladmin-system/nlsso-server/src/main/resources/static/xterm.css deleted file mode 100755 index 24cd475..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/xterm.css +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright (c) 2014 The xterm.js authors. All rights reserved. - * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) - * https://github.com/chjj/term.js - * @license MIT - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * Originally forked from (with the author's permission): - * Fabrice Bellard's javascript vt100 for jslinux: - * http://bellard.org/jslinux/ - * Copyright (c) 2011 Fabrice Bellard - * The original design remains. The terminal itself - * has been extended to include xterm CSI codes, among - * other features. - */ - -/** - * Default styles for xterm.js - */ - -.xterm { - font-family: courier-new, courier, monospace; - font-feature-settings: "liga" 0; - position: relative; - user-select: none; - -ms-user-select: none; - -webkit-user-select: none; -} - -.xterm.focus, -.xterm:focus { - outline: none; -} - -.xterm .xterm-helpers { - position: absolute; - top: 0; - /** - * The z-index of the helpers must be higher than the canvases in order for - * IMEs to appear on top. - */ - z-index: 10; -} - -.xterm .xterm-helper-textarea { - /* - * HACK: to fix IE's blinking cursor - * Move textarea out of the screen to the far left, so that the cursor is not visible. - */ - position: absolute; - opacity: 0; - left: -9999em; - top: 0; - width: 0; - height: 0; - z-index: -10; - /** Prevent wrapping so the IME appears against the textarea at the correct position */ - white-space: nowrap; - overflow: hidden; - resize: none; -} - -.xterm .composition-view { - /* TODO: Composition position got messed up somewhere */ - background: #000; - color: #FFF; - display: none; - position: absolute; - white-space: nowrap; - z-index: 1; -} - -.xterm .composition-view.active { - display: block; -} - -.xterm .xterm-viewport { - /* On OS X this is required in order for the scroll bar to appear fully opaque */ - background-color: #000; - overflow-y: scroll; - cursor: default; - position: absolute; - right: 0; - left: 0; - top: 0; - bottom: 0; -} - -.xterm .xterm-screen { - position: relative; -} - -.xterm .xterm-screen canvas { - position: absolute; - left: 0; - top: 0; -} - -.xterm .xterm-scroll-area { - visibility: hidden; -} - -.xterm-char-measure-element { - display: inline-block; - visibility: hidden; - position: absolute; - top: 0; - left: -9999em; - line-height: normal; -} - -.xterm { - cursor: text; -} - -.xterm.enable-mouse-events { - /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ - cursor: default; -} - -.xterm.xterm-cursor-pointer { - cursor: pointer; -} - -.xterm.column-select.focus { - /* Column selection mode */ - cursor: crosshair; -} - -.xterm .xterm-accessibility, -.xterm .xterm-message { - position: absolute; - left: 0; - top: 0; - bottom: 0; - right: 0; - z-index: 100; - color: transparent; -} - -.xterm .live-region { - position: absolute; - left: -9999px; - width: 1px; - height: 1px; - overflow: hidden; -} diff --git a/nladmin-system/nlsso-server/src/main/resources/static/xterm.js b/nladmin-system/nlsso-server/src/main/resources/static/xterm.js deleted file mode 100755 index 0477d15..0000000 --- a/nladmin-system/nlsso-server/src/main/resources/static/xterm.js +++ /dev/null @@ -1,9225 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Terminal = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i rows) { - this._rowContainer.removeChild(this._rowElements.pop()); - } - this._rowElements[this._rowElements.length - 1].addEventListener('focus', this._bottomBoundaryFocusListener); - this._refreshRowsDimensions(); - }; - AccessibilityManager.prototype._createAccessibilityTreeNode = function () { - var element = document.createElement('div'); - element.setAttribute('role', 'listitem'); - element.tabIndex = -1; - this._refreshRowDimensions(element); - return element; - }; - AccessibilityManager.prototype._onTab = function (spaceCount) { - for (var i = 0; i < spaceCount; i++) { - this._onChar(' '); - } - }; - AccessibilityManager.prototype._onChar = function (char) { - var _this = this; - if (this._liveRegionLineCount < MAX_ROWS_TO_READ + 1) { - if (this._charsToConsume.length > 0) { - var shiftedChar = this._charsToConsume.shift(); - if (shiftedChar !== char) { - this._announceCharacter(char); - } - } - else { - this._announceCharacter(char); - } - if (char === '\n') { - this._liveRegionLineCount++; - if (this._liveRegionLineCount === MAX_ROWS_TO_READ + 1) { - this._liveRegion.textContent += Strings.tooMuchOutput; - } - } - if (Platform_1.isMac) { - if (this._liveRegion.textContent && this._liveRegion.textContent.length > 0 && !this._liveRegion.parentNode) { - setTimeout(function () { - _this._accessibilityTreeRoot.appendChild(_this._liveRegion); - }, 0); - } - } - } - }; - AccessibilityManager.prototype._clearLiveRegion = function () { - this._liveRegion.textContent = ''; - this._liveRegionLineCount = 0; - if (Platform_1.isMac) { - if (this._liveRegion.parentNode) { - this._accessibilityTreeRoot.removeChild(this._liveRegion); - } - } - }; - AccessibilityManager.prototype._onKey = function (keyChar) { - this._clearLiveRegion(); - this._charsToConsume.push(keyChar); - }; - AccessibilityManager.prototype._refreshRows = function (start, end) { - this._renderRowsDebouncer.refresh(start, end); - }; - AccessibilityManager.prototype._renderRows = function (start, end) { - var buffer = this._terminal.buffer; - var setSize = buffer.lines.length.toString(); - for (var i = start; i <= end; i++) { - var lineData = buffer.translateBufferLineToString(buffer.ydisp + i, true); - var posInSet = (buffer.ydisp + i + 1).toString(); - var element = this._rowElements[i]; - element.textContent = lineData.length === 0 ? Strings.blankLine : lineData; - element.setAttribute('aria-posinset', posInSet); - element.setAttribute('aria-setsize', setSize); - } - }; - AccessibilityManager.prototype._refreshRowsDimensions = function () { - if (!this._terminal.renderer.dimensions.actualCellHeight) { - return; - } - if (this._rowElements.length !== this._terminal.rows) { - this._onResize(this._terminal.rows); - } - for (var i = 0; i < this._terminal.rows; i++) { - this._refreshRowDimensions(this._rowElements[i]); - } - }; - AccessibilityManager.prototype._refreshRowDimensions = function (element) { - element.style.height = this._terminal.renderer.dimensions.actualCellHeight + "px"; - }; - AccessibilityManager.prototype._announceCharacter = function (char) { - if (char === ' ') { - this._liveRegion.innerHTML += ' '; - } - else { - this._liveRegion.textContent += char; - } - }; - return AccessibilityManager; -}(Lifecycle_2.Disposable)); -exports.AccessibilityManager = AccessibilityManager; - -},{"./Strings":13,"./common/Lifecycle":18,"./core/Platform":21,"./ui/Lifecycle":48,"./ui/RenderDebouncer":50}],2:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var CircularList_1 = require("./common/CircularList"); -var EventEmitter_1 = require("./common/EventEmitter"); -var BufferLine_1 = require("./BufferLine"); -var Types_1 = require("./renderer/atlas/Types"); -exports.DEFAULT_ATTR = (0 << 18) | (Types_1.DEFAULT_COLOR << 9) | (256 << 0); -exports.CHAR_DATA_ATTR_INDEX = 0; -exports.CHAR_DATA_CHAR_INDEX = 1; -exports.CHAR_DATA_WIDTH_INDEX = 2; -exports.CHAR_DATA_CODE_INDEX = 3; -exports.MAX_BUFFER_SIZE = 4294967295; -exports.NULL_CELL_CHAR = ' '; -exports.NULL_CELL_WIDTH = 1; -exports.NULL_CELL_CODE = 32; -var Buffer = (function () { - function Buffer(_terminal, _hasScrollback) { - this._terminal = _terminal; - this._hasScrollback = _hasScrollback; - this.markers = []; - this.clear(); - } - Buffer.prototype.setBufferLineFactory = function (type) { - if (type === 'JsArray') { - if (this._bufferLineConstructor !== BufferLine_1.BufferLineJSArray) { - this._bufferLineConstructor = BufferLine_1.BufferLineJSArray; - this._recreateLines(); - } - } - else { - if (this._bufferLineConstructor !== BufferLine_1.BufferLine) { - this._bufferLineConstructor = BufferLine_1.BufferLine; - this._recreateLines(); - } - } - }; - Buffer.prototype._recreateLines = function () { - if (!this.lines) - return; - for (var i = 0; i < this.lines.length; ++i) { - var oldLine = this.lines.get(i); - var newLine = new this._bufferLineConstructor(oldLine.length); - for (var j = 0; j < oldLine.length; ++j) { - newLine.set(j, oldLine.get(j)); - } - this.lines.set(i, newLine); - } - }; - Buffer.prototype.getBlankLine = function (attr, isWrapped) { - var fillCharData = [attr, exports.NULL_CELL_CHAR, exports.NULL_CELL_WIDTH, exports.NULL_CELL_CODE]; - return new this._bufferLineConstructor(this._terminal.cols, fillCharData, isWrapped); - }; - Object.defineProperty(Buffer.prototype, "hasScrollback", { - get: function () { - return this._hasScrollback && this.lines.maxLength > this._terminal.rows; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Buffer.prototype, "isCursorInViewport", { - get: function () { - var absoluteY = this.ybase + this.y; - var relativeY = absoluteY - this.ydisp; - return (relativeY >= 0 && relativeY < this._terminal.rows); - }, - enumerable: true, - configurable: true - }); - Buffer.prototype._getCorrectBufferLength = function (rows) { - if (!this._hasScrollback) { - return rows; - } - var correctBufferLength = rows + this._terminal.options.scrollback; - return correctBufferLength > exports.MAX_BUFFER_SIZE ? exports.MAX_BUFFER_SIZE : correctBufferLength; - }; - Buffer.prototype.fillViewportRows = function (fillAttr) { - if (this.lines.length === 0) { - if (fillAttr === undefined) { - fillAttr = exports.DEFAULT_ATTR; - } - var i = this._terminal.rows; - while (i--) { - this.lines.push(this.getBlankLine(fillAttr)); - } - } - }; - Buffer.prototype.clear = function () { - this.setBufferLineFactory(this._terminal.options.experimentalBufferLineImpl); - this.ydisp = 0; - this.ybase = 0; - this.y = 0; - this.x = 0; - this.lines = new CircularList_1.CircularList(this._getCorrectBufferLength(this._terminal.rows)); - this.scrollTop = 0; - this.scrollBottom = this._terminal.rows - 1; - this.setupTabStops(); - }; - Buffer.prototype.resize = function (newCols, newRows) { - var newMaxLength = this._getCorrectBufferLength(newRows); - if (newMaxLength > this.lines.maxLength) { - this.lines.maxLength = newMaxLength; - } - if (this.lines.length > 0) { - if (this._terminal.cols < newCols) { - var ch = [exports.DEFAULT_ATTR, exports.NULL_CELL_CHAR, exports.NULL_CELL_WIDTH, exports.NULL_CELL_CODE]; - for (var i = 0; i < this.lines.length; i++) { - this.lines.get(i).resize(newCols, ch); - } - } - var addToY = 0; - if (this._terminal.rows < newRows) { - for (var y = this._terminal.rows; y < newRows; y++) { - if (this.lines.length < newRows + this.ybase) { - if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) { - this.ybase--; - addToY++; - if (this.ydisp > 0) { - this.ydisp--; - } - } - else { - var fillCharData = [exports.DEFAULT_ATTR, exports.NULL_CELL_CHAR, exports.NULL_CELL_WIDTH, exports.NULL_CELL_CODE]; - this.lines.push(new this._bufferLineConstructor(newCols, fillCharData)); - } - } - } - } - else { - for (var y = this._terminal.rows; y > newRows; y--) { - if (this.lines.length > newRows + this.ybase) { - if (this.lines.length > this.ybase + this.y + 1) { - this.lines.pop(); - } - else { - this.ybase++; - this.ydisp++; - } - } - } - } - if (newMaxLength < this.lines.maxLength) { - var amountToTrim = this.lines.length - newMaxLength; - if (amountToTrim > 0) { - this.lines.trimStart(amountToTrim); - this.ybase = Math.max(this.ybase - amountToTrim, 0); - this.ydisp = Math.max(this.ydisp - amountToTrim, 0); - } - this.lines.maxLength = newMaxLength; - } - this.x = Math.min(this.x, newCols - 1); - this.y = Math.min(this.y, newRows - 1); - if (addToY) { - this.y += addToY; - } - this.savedY = Math.min(this.savedY, newRows - 1); - this.savedX = Math.min(this.savedX, newCols - 1); - this.scrollTop = 0; - } - this.scrollBottom = newRows - 1; - }; - Buffer.prototype.stringIndexToBufferIndex = function (lineIndex, stringIndex) { - while (stringIndex) { - var line = this.lines.get(lineIndex); - if (!line) { - [-1, -1]; - } - for (var i = 0; i < line.length; ++i) { - stringIndex -= line.get(i)[exports.CHAR_DATA_CHAR_INDEX].length; - if (stringIndex < 0) { - return [lineIndex, i]; - } - } - lineIndex++; - } - return [lineIndex, 0]; - }; - Buffer.prototype.translateBufferLineToString = function (lineIndex, trimRight, startCol, endCol) { - if (startCol === void 0) { startCol = 0; } - if (endCol === void 0) { endCol = null; } - var lineString = ''; - var line = this.lines.get(lineIndex); - if (!line) { - return ''; - } - var startIndex = startCol; - if (endCol === null) { - endCol = line.length; - } - var endIndex = endCol; - for (var i = 0; i < line.length; i++) { - var char = line.get(i); - lineString += char[exports.CHAR_DATA_CHAR_INDEX]; - if (char[exports.CHAR_DATA_WIDTH_INDEX] === 0) { - if (startCol >= i) { - startIndex--; - } - if (endCol > i) { - endIndex--; - } - } - else { - if (char[exports.CHAR_DATA_CHAR_INDEX].length > 1) { - if (startCol > i) { - startIndex += char[exports.CHAR_DATA_CHAR_INDEX].length - 1; - } - if (endCol > i) { - endIndex += char[exports.CHAR_DATA_CHAR_INDEX].length - 1; - } - } - } - } - if (trimRight) { - var rightWhitespaceIndex = lineString.search(/\s+$/); - if (rightWhitespaceIndex !== -1) { - endIndex = Math.min(endIndex, rightWhitespaceIndex); - } - if (endIndex <= startIndex) { - return ''; - } - } - return lineString.substring(startIndex, endIndex); - }; - Buffer.prototype.getWrappedRangeForLine = function (y) { - var first = y; - var last = y; - while (first > 0 && this.lines.get(first).isWrapped) { - first--; - } - while (last + 1 < this.lines.length && this.lines.get(last + 1).isWrapped) { - last++; - } - return { first: first, last: last }; - }; - Buffer.prototype.setupTabStops = function (i) { - if (i !== null && i !== undefined) { - if (!this.tabs[i]) { - i = this.prevStop(i); - } - } - else { - this.tabs = {}; - i = 0; - } - for (; i < this._terminal.cols; i += this._terminal.options.tabStopWidth) { - this.tabs[i] = true; - } - }; - Buffer.prototype.prevStop = function (x) { - if (x === null || x === undefined) { - x = this.x; - } - while (!this.tabs[--x] && x > 0) - ; - return x >= this._terminal.cols ? this._terminal.cols - 1 : x < 0 ? 0 : x; - }; - Buffer.prototype.nextStop = function (x) { - if (x === null || x === undefined) { - x = this.x; - } - while (!this.tabs[++x] && x < this._terminal.cols) - ; - return x >= this._terminal.cols ? this._terminal.cols - 1 : x < 0 ? 0 : x; - }; - Buffer.prototype.addMarker = function (y) { - var _this = this; - var marker = new Marker(y); - this.markers.push(marker); - marker.register(this.lines.addDisposableListener('trim', function (amount) { - marker.line -= amount; - if (marker.line < 0) { - marker.dispose(); - } - })); - marker.register(marker.addDisposableListener('dispose', function () { return _this._removeMarker(marker); })); - return marker; - }; - Buffer.prototype._removeMarker = function (marker) { - this.markers.splice(this.markers.indexOf(marker), 1); - }; - Buffer.prototype.iterator = function (trimRight, startIndex, endIndex, startOverscan, endOverscan) { - return new BufferStringIterator(this, trimRight, startIndex, endIndex, startOverscan, endOverscan); - }; - return Buffer; -}()); -exports.Buffer = Buffer; -var Marker = (function (_super) { - __extends(Marker, _super); - function Marker(line) { - var _this = _super.call(this) || this; - _this.line = line; - _this._id = Marker._nextId++; - _this.isDisposed = false; - return _this; - } - Object.defineProperty(Marker.prototype, "id", { - get: function () { return this._id; }, - enumerable: true, - configurable: true - }); - Marker.prototype.dispose = function () { - if (this.isDisposed) { - return; - } - this.isDisposed = true; - this.emit('dispose'); - _super.prototype.dispose.call(this); - }; - Marker._nextId = 1; - return Marker; -}(EventEmitter_1.EventEmitter)); -exports.Marker = Marker; -var BufferStringIterator = (function () { - function BufferStringIterator(_buffer, _trimRight, _startIndex, _endIndex, _startOverscan, _endOverscan) { - if (_startIndex === void 0) { _startIndex = 0; } - if (_endIndex === void 0) { _endIndex = _buffer.lines.length; } - if (_startOverscan === void 0) { _startOverscan = 0; } - if (_endOverscan === void 0) { _endOverscan = 0; } - this._buffer = _buffer; - this._trimRight = _trimRight; - this._startIndex = _startIndex; - this._endIndex = _endIndex; - this._startOverscan = _startOverscan; - this._endOverscan = _endOverscan; - if (this._startIndex < 0) { - this._startIndex = 0; - } - if (this._endIndex > this._buffer.lines.length) { - this._endIndex = this._buffer.lines.length; - } - this._current = this._startIndex; - } - BufferStringIterator.prototype.hasNext = function () { - return this._current < this._endIndex; - }; - BufferStringIterator.prototype.next = function () { - var range = this._buffer.getWrappedRangeForLine(this._current); - if (range.first < this._startIndex - this._startOverscan) { - range.first = this._startIndex - this._startOverscan; - } - if (range.last > this._endIndex + this._endOverscan) { - range.last = this._endIndex + this._endOverscan; - } - range.first = Math.max(range.first, 0); - range.last = Math.min(range.last, this._buffer.lines.length); - var result = ''; - for (var i = range.first; i <= range.last; ++i) { - result += this._buffer.translateBufferLineToString(i, (this._trimRight) ? i === range.last : false); - } - this._current = range.last + 1; - return { range: range, content: result }; - }; - return BufferStringIterator; -}()); -exports.BufferStringIterator = BufferStringIterator; - -},{"./BufferLine":3,"./common/CircularList":16,"./common/EventEmitter":17,"./renderer/atlas/Types":43}],3:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("./Buffer"); -var BufferLineJSArray = (function () { - function BufferLineJSArray(cols, fillCharData, isWrapped) { - this.isWrapped = false; - this._data = []; - if (!fillCharData) { - fillCharData = [0, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]; - } - for (var i = 0; i < cols; i++) { - this._push(fillCharData); - } - if (isWrapped) { - this.isWrapped = true; - } - this.length = this._data.length; - } - BufferLineJSArray.prototype._pop = function () { - var data = this._data.pop(); - this.length = this._data.length; - return data; - }; - BufferLineJSArray.prototype._push = function (data) { - this._data.push(data); - this.length = this._data.length; - }; - BufferLineJSArray.prototype._splice = function (start, deleteCount) { - var items = []; - for (var _i = 2; _i < arguments.length; _i++) { - items[_i - 2] = arguments[_i]; - } - var _a; - var removed = (_a = this._data).splice.apply(_a, [start, deleteCount].concat(items)); - this.length = this._data.length; - return removed; - }; - BufferLineJSArray.prototype.get = function (index) { - return this._data[index]; - }; - BufferLineJSArray.prototype.set = function (index, data) { - this._data[index] = data; - }; - BufferLineJSArray.prototype.insertCells = function (pos, n, ch) { - while (n--) { - this._splice(pos, 0, ch); - this._pop(); - } - }; - BufferLineJSArray.prototype.deleteCells = function (pos, n, fillCharData) { - while (n--) { - this._splice(pos, 1); - this._push(fillCharData); - } - }; - BufferLineJSArray.prototype.replaceCells = function (start, end, fillCharData) { - while (start < end && start < this.length) { - this.set(start++, fillCharData); - } - }; - BufferLineJSArray.prototype.resize = function (cols, fillCharData, shrink) { - if (shrink === void 0) { shrink = false; } - while (this._data.length < cols) { - this._data.push(fillCharData); - } - if (shrink) { - while (this._data.length > cols) { - this._data.pop(); - } - } - this.length = this._data.length; - }; - BufferLineJSArray.prototype.fill = function (fillCharData) { - for (var i = 0; i < this.length; ++i) { - this.set(i, fillCharData); - } - }; - BufferLineJSArray.prototype.copyFrom = function (line) { - this._data = line._data.slice(0); - this.length = line.length; - this.isWrapped = line.isWrapped; - }; - BufferLineJSArray.prototype.clone = function () { - var newLine = new BufferLineJSArray(0); - newLine.copyFrom(this); - return newLine; - }; - return BufferLineJSArray; -}()); -exports.BufferLineJSArray = BufferLineJSArray; -var CELL_SIZE = 3; -var BufferLine = (function () { - function BufferLine(cols, fillCharData, isWrapped) { - if (isWrapped === void 0) { isWrapped = false; } - this.isWrapped = isWrapped; - this._data = null; - this._combined = {}; - if (!fillCharData) { - fillCharData = [0, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]; - } - if (cols) { - this._data = new Uint32Array(cols * CELL_SIZE); - for (var i = 0; i < cols; ++i) { - this.set(i, fillCharData); - } - } - this.length = cols; - } - BufferLine.prototype.get = function (index) { - var stringData = this._data[index * CELL_SIZE + 1]; - return [ - this._data[index * CELL_SIZE + 0], - (stringData & 0x80000000) - ? this._combined[index] - : (stringData) ? String.fromCharCode(stringData) : '', - this._data[index * CELL_SIZE + 2], - (stringData & 0x80000000) - ? this._combined[index].charCodeAt(this._combined[index].length - 1) - : stringData - ]; - }; - BufferLine.prototype.set = function (index, value) { - this._data[index * CELL_SIZE + 0] = value[0]; - if (value[1].length > 1) { - this._combined[index] = value[1]; - this._data[index * CELL_SIZE + 1] = index | 0x80000000; - } - else { - this._data[index * CELL_SIZE + 1] = value[1].charCodeAt(0); - } - this._data[index * CELL_SIZE + 2] = value[2]; - }; - BufferLine.prototype.insertCells = function (pos, n, fillCharData) { - pos %= this.length; - if (n < this.length - pos) { - for (var i = this.length - pos - n - 1; i >= 0; --i) { - this.set(pos + n + i, this.get(pos + i)); - } - for (var i = 0; i < n; ++i) { - this.set(pos + i, fillCharData); - } - } - else { - for (var i = pos; i < this.length; ++i) { - this.set(i, fillCharData); - } - } - }; - BufferLine.prototype.deleteCells = function (pos, n, fillCharData) { - pos %= this.length; - if (n < this.length - pos) { - for (var i = 0; i < this.length - pos - n; ++i) { - this.set(pos + i, this.get(pos + n + i)); - } - for (var i = this.length - n; i < this.length; ++i) { - this.set(i, fillCharData); - } - } - else { - for (var i = pos; i < this.length; ++i) { - this.set(i, fillCharData); - } - } - }; - BufferLine.prototype.replaceCells = function (start, end, fillCharData) { - while (start < end && start < this.length) { - this.set(start++, fillCharData); - } - }; - BufferLine.prototype.resize = function (cols, fillCharData, shrink) { - if (shrink === void 0) { shrink = false; } - if (cols === this.length || (!shrink && cols < this.length)) { - return; - } - if (cols > this.length) { - var data = new Uint32Array(cols * CELL_SIZE); - if (this.length) { - if (cols * CELL_SIZE < this._data.length) { - data.set(this._data.subarray(0, cols * CELL_SIZE)); - } - else { - data.set(this._data); - } - } - this._data = data; - for (var i = this.length; i < cols; ++i) { - this.set(i, fillCharData); - } - } - else if (shrink) { - if (cols) { - var data = new Uint32Array(cols * CELL_SIZE); - data.set(this._data.subarray(0, cols * CELL_SIZE)); - this._data = data; - } - else { - this._data = null; - } - } - this.length = cols; - }; - BufferLine.prototype.fill = function (fillCharData) { - this._combined = {}; - for (var i = 0; i < this.length; ++i) { - this.set(i, fillCharData); - } - }; - BufferLine.prototype.copyFrom = function (line) { - if (this.length !== line.length) { - this._data = new Uint32Array(line._data); - } - else { - this._data.set(line._data); - } - this.length = line.length; - this._combined = {}; - for (var el in line._combined) { - this._combined[el] = line._combined[el]; - } - this.isWrapped = line.isWrapped; - }; - BufferLine.prototype.clone = function () { - var newLine = new BufferLine(0); - newLine._data = new Uint32Array(this._data); - newLine.length = this.length; - for (var el in this._combined) { - newLine._combined[el] = this._combined[el]; - } - newLine.isWrapped = this.isWrapped; - return newLine; - }; - return BufferLine; -}()); -exports.BufferLine = BufferLine; - -},{"./Buffer":2}],4:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("./Buffer"); -var EventEmitter_1 = require("./common/EventEmitter"); -var BufferSet = (function (_super) { - __extends(BufferSet, _super); - function BufferSet(_terminal) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._normal = new Buffer_1.Buffer(_this._terminal, true); - _this._normal.fillViewportRows(); - _this._alt = new Buffer_1.Buffer(_this._terminal, false); - _this._activeBuffer = _this._normal; - _this.setupTabStops(); - return _this; - } - Object.defineProperty(BufferSet.prototype, "alt", { - get: function () { - return this._alt; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(BufferSet.prototype, "active", { - get: function () { - return this._activeBuffer; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(BufferSet.prototype, "normal", { - get: function () { - return this._normal; - }, - enumerable: true, - configurable: true - }); - BufferSet.prototype.activateNormalBuffer = function () { - if (this._activeBuffer === this._normal) { - return; - } - this._normal.x = this._alt.x; - this._normal.y = this._alt.y; - this._alt.clear(); - this._activeBuffer = this._normal; - this.emit('activate', { - activeBuffer: this._normal, - inactiveBuffer: this._alt - }); - }; - BufferSet.prototype.activateAltBuffer = function (fillAttr) { - if (this._activeBuffer === this._alt) { - return; - } - this._alt.fillViewportRows(fillAttr); - this._alt.x = this._normal.x; - this._alt.y = this._normal.y; - this._activeBuffer = this._alt; - this.emit('activate', { - activeBuffer: this._alt, - inactiveBuffer: this._normal - }); - }; - BufferSet.prototype.resize = function (newCols, newRows) { - this._normal.resize(newCols, newRows); - this._alt.resize(newCols, newRows); - }; - BufferSet.prototype.setupTabStops = function (i) { - this._normal.setupTabStops(i); - this._alt.setupTabStops(i); - }; - return BufferSet; -}(EventEmitter_1.EventEmitter)); -exports.BufferSet = BufferSet; - -},{"./Buffer":2,"./common/EventEmitter":17}],5:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var TypedArrayUtils_1 = require("./common/TypedArrayUtils"); -exports.wcwidth = (function (opts) { - var COMBINING_BMP = [ - [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489], - [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2], - [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603], - [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670], - [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED], - [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A], - [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902], - [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D], - [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981], - [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD], - [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C], - [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D], - [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC], - [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD], - [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C], - [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D], - [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0], - [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48], - [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC], - [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD], - [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D], - [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6], - [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E], - [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC], - [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35], - [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E], - [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97], - [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030], - [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039], - [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F], - [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753], - [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD], - [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD], - [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922], - [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B], - [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34], - [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42], - [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF], - [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063], - [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F], - [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B], - [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F], - [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB] - ]; - var COMBINING_HIGH = [ - [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F], - [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169], - [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD], - [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F], - [0xE0100, 0xE01EF] - ]; - function bisearch(ucs, data) { - var min = 0; - var max = data.length - 1; - var mid; - if (ucs < data[0][0] || ucs > data[max][1]) { - return false; - } - while (max >= min) { - mid = (min + max) >> 1; - if (ucs > data[mid][1]) { - min = mid + 1; - } - else if (ucs < data[mid][0]) { - max = mid - 1; - } - else { - return true; - } - } - return false; - } - function wcwidthHigh(ucs) { - if (bisearch(ucs, COMBINING_HIGH)) { - return 0; - } - if ((ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd)) { - return 2; - } - return 1; - } - var control = opts.control | 0; - var table = new Uint8Array(65536); - TypedArrayUtils_1.fill(table, 1); - table[0] = opts.nul; - TypedArrayUtils_1.fill(table, opts.control, 1, 32); - TypedArrayUtils_1.fill(table, opts.control, 0x7f, 0xa0); - TypedArrayUtils_1.fill(table, 2, 0x1100, 0x1160); - table[0x2329] = 2; - table[0x232a] = 2; - TypedArrayUtils_1.fill(table, 2, 0x2e80, 0xa4d0); - table[0x303f] = 1; - TypedArrayUtils_1.fill(table, 2, 0xac00, 0xd7a4); - TypedArrayUtils_1.fill(table, 2, 0xf900, 0xfb00); - TypedArrayUtils_1.fill(table, 2, 0xfe10, 0xfe1a); - TypedArrayUtils_1.fill(table, 2, 0xfe30, 0xfe70); - TypedArrayUtils_1.fill(table, 2, 0xff00, 0xff61); - TypedArrayUtils_1.fill(table, 2, 0xffe0, 0xffe7); - for (var r = 0; r < COMBINING_BMP.length; ++r) { - TypedArrayUtils_1.fill(table, 0, COMBINING_BMP[r][0], COMBINING_BMP[r][1] + 1); - } - return function (num) { - if (num < 32) { - return control | 0; - } - if (num < 127) { - return 1; - } - if (num < 65536) { - return table[num]; - } - return wcwidthHigh(num); - }; -})({ nul: 0, control: 0 }); -function getStringCellWidth(s) { - var result = 0; - var length = s.length; - for (var i = 0; i < length; ++i) { - var code = s.charCodeAt(i); - if (0xD800 <= code && code <= 0xDBFF) { - if (++i >= length) { - return result + exports.wcwidth(code); - } - var second = s.charCodeAt(i); - if (0xDC00 <= second && second <= 0xDFFF) { - code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - else { - result += exports.wcwidth(second); - } - } - result += exports.wcwidth(code); - } - return result; -} -exports.getStringCellWidth = getStringCellWidth; - -},{"./common/TypedArrayUtils":19}],6:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var CompositionHelper = (function () { - function CompositionHelper(_textarea, _compositionView, _terminal) { - this._textarea = _textarea; - this._compositionView = _compositionView; - this._terminal = _terminal; - this._isComposing = false; - this._isSendingComposition = false; - this._compositionPosition = { start: null, end: null }; - } - CompositionHelper.prototype.compositionstart = function () { - this._isComposing = true; - this._compositionPosition.start = this._textarea.value.length; - this._compositionView.textContent = ''; - this._compositionView.classList.add('active'); - }; - CompositionHelper.prototype.compositionupdate = function (ev) { - var _this = this; - this._compositionView.textContent = ev.data; - this.updateCompositionElements(); - setTimeout(function () { - _this._compositionPosition.end = _this._textarea.value.length; - }, 0); - }; - CompositionHelper.prototype.compositionend = function () { - this._finalizeComposition(true); - }; - CompositionHelper.prototype.keydown = function (ev) { - if (this._isComposing || this._isSendingComposition) { - if (ev.keyCode === 229) { - return false; - } - else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) { - return false; - } - this._finalizeComposition(false); - } - if (ev.keyCode === 229) { - this._handleAnyTextareaChanges(); - return false; - } - return true; - }; - CompositionHelper.prototype._finalizeComposition = function (waitForPropogation) { - var _this = this; - this._compositionView.classList.remove('active'); - this._isComposing = false; - this._clearTextareaPosition(); - if (!waitForPropogation) { - this._isSendingComposition = false; - var input = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end); - this._terminal.handler(input); - } - else { - var currentCompositionPosition_1 = { - start: this._compositionPosition.start, - end: this._compositionPosition.end - }; - this._isSendingComposition = true; - setTimeout(function () { - if (_this._isSendingComposition) { - _this._isSendingComposition = false; - var input = void 0; - if (_this._isComposing) { - input = _this._textarea.value.substring(currentCompositionPosition_1.start, currentCompositionPosition_1.end); - } - else { - input = _this._textarea.value.substring(currentCompositionPosition_1.start); - } - _this._terminal.handler(input); - } - }, 0); - } - }; - CompositionHelper.prototype._handleAnyTextareaChanges = function () { - var _this = this; - var oldValue = this._textarea.value; - setTimeout(function () { - if (!_this._isComposing) { - var newValue = _this._textarea.value; - var diff = newValue.replace(oldValue, ''); - if (diff.length > 0) { - _this._terminal.handler(diff); - } - } - }, 0); - }; - CompositionHelper.prototype.updateCompositionElements = function (dontRecurse) { - var _this = this; - if (!this._isComposing) { - return; - } - if (this._terminal.buffer.isCursorInViewport) { - var cellHeight = Math.ceil(this._terminal.charMeasure.height * this._terminal.options.lineHeight); - var cursorTop = this._terminal.buffer.y * cellHeight; - var cursorLeft = this._terminal.buffer.x * this._terminal.charMeasure.width; - this._compositionView.style.left = cursorLeft + 'px'; - this._compositionView.style.top = cursorTop + 'px'; - this._compositionView.style.height = cellHeight + 'px'; - this._compositionView.style.lineHeight = cellHeight + 'px'; - var compositionViewBounds = this._compositionView.getBoundingClientRect(); - this._textarea.style.left = cursorLeft + 'px'; - this._textarea.style.top = cursorTop + 'px'; - this._textarea.style.width = compositionViewBounds.width + 'px'; - this._textarea.style.height = compositionViewBounds.height + 'px'; - this._textarea.style.lineHeight = compositionViewBounds.height + 'px'; - } - if (!dontRecurse) { - setTimeout(function () { return _this.updateCompositionElements(true); }, 0); - } - }; - CompositionHelper.prototype._clearTextareaPosition = function () { - this._textarea.style.left = ''; - this._textarea.style.top = ''; - }; - return CompositionHelper; -}()); -exports.CompositionHelper = CompositionHelper; - -},{}],7:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Lifecycle_1 = require("./common/Lifecycle"); -function r(low, high) { - var c = high - low; - var arr = new Array(c); - while (c--) { - arr[c] = --high; - } - return arr; -} -var TransitionTable = (function () { - function TransitionTable(length) { - this.table = (typeof Uint8Array === 'undefined') - ? new Array(length) - : new Uint8Array(length); - } - TransitionTable.prototype.add = function (code, state, action, next) { - this.table[state << 8 | code] = ((action | 0) << 4) | ((next === undefined) ? state : next); - }; - TransitionTable.prototype.addMany = function (codes, state, action, next) { - for (var i = 0; i < codes.length; i++) { - this.add(codes[i], state, action, next); - } - }; - return TransitionTable; -}()); -exports.TransitionTable = TransitionTable; -var PRINTABLES = r(0x20, 0x7f); -var EXECUTABLES = r(0x00, 0x18); -EXECUTABLES.push(0x19); -EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20)); -var DEFAULT_TRANSITION = 1 << 4 | 0; -exports.VT500_TRANSITION_TABLE = (function () { - var table = new TransitionTable(4095); - var states = r(0, 13 + 1); - var state; - for (state in states) { - for (var code = 0; code < 160; ++code) { - table.add(code, state, 1, 0); - } - } - table.addMany(PRINTABLES, 0, 2, 0); - for (state in states) { - table.addMany([0x18, 0x1a, 0x99, 0x9a], state, 3, 0); - table.addMany(r(0x80, 0x90), state, 3, 0); - table.addMany(r(0x90, 0x98), state, 3, 0); - table.add(0x9c, state, 0, 0); - table.add(0x1b, state, 11, 1); - table.add(0x9d, state, 4, 8); - table.addMany([0x98, 0x9e, 0x9f], state, 0, 7); - table.add(0x9b, state, 11, 3); - table.add(0x90, state, 11, 9); - } - table.addMany(EXECUTABLES, 0, 3, 0); - table.addMany(EXECUTABLES, 1, 3, 1); - table.add(0x7f, 1, 0, 1); - table.addMany(EXECUTABLES, 8, 0, 8); - table.addMany(EXECUTABLES, 3, 3, 3); - table.add(0x7f, 3, 0, 3); - table.addMany(EXECUTABLES, 4, 3, 4); - table.add(0x7f, 4, 0, 4); - table.addMany(EXECUTABLES, 6, 3, 6); - table.addMany(EXECUTABLES, 5, 3, 5); - table.add(0x7f, 5, 0, 5); - table.addMany(EXECUTABLES, 2, 3, 2); - table.add(0x7f, 2, 0, 2); - table.add(0x5d, 1, 4, 8); - table.addMany(PRINTABLES, 8, 5, 8); - table.add(0x7f, 8, 5, 8); - table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], 8, 6, 0); - table.addMany(r(0x1c, 0x20), 8, 0, 8); - table.addMany([0x58, 0x5e, 0x5f], 1, 0, 7); - table.addMany(PRINTABLES, 7, 0, 7); - table.addMany(EXECUTABLES, 7, 0, 7); - table.add(0x9c, 7, 0, 0); - table.add(0x5b, 1, 11, 3); - table.addMany(r(0x40, 0x7f), 3, 7, 0); - table.addMany(r(0x30, 0x3a), 3, 8, 4); - table.add(0x3b, 3, 8, 4); - table.addMany([0x3c, 0x3d, 0x3e, 0x3f], 3, 9, 4); - table.addMany(r(0x30, 0x3a), 4, 8, 4); - table.add(0x3b, 4, 8, 4); - table.addMany(r(0x40, 0x7f), 4, 7, 0); - table.addMany([0x3a, 0x3c, 0x3d, 0x3e, 0x3f], 4, 0, 6); - table.addMany(r(0x20, 0x40), 6, 0, 6); - table.add(0x7f, 6, 0, 6); - table.addMany(r(0x40, 0x7f), 6, 0, 0); - table.add(0x3a, 3, 0, 6); - table.addMany(r(0x20, 0x30), 3, 9, 5); - table.addMany(r(0x20, 0x30), 5, 9, 5); - table.addMany(r(0x30, 0x40), 5, 0, 6); - table.addMany(r(0x40, 0x7f), 5, 7, 0); - table.addMany(r(0x20, 0x30), 4, 9, 5); - table.addMany(r(0x20, 0x30), 1, 9, 2); - table.addMany(r(0x20, 0x30), 2, 9, 2); - table.addMany(r(0x30, 0x7f), 2, 10, 0); - table.addMany(r(0x30, 0x50), 1, 10, 0); - table.addMany(r(0x51, 0x58), 1, 10, 0); - table.addMany([0x59, 0x5a, 0x5c], 1, 10, 0); - table.addMany(r(0x60, 0x7f), 1, 10, 0); - table.add(0x50, 1, 11, 9); - table.addMany(EXECUTABLES, 9, 0, 9); - table.add(0x7f, 9, 0, 9); - table.addMany(r(0x1c, 0x20), 9, 0, 9); - table.addMany(r(0x20, 0x30), 9, 9, 12); - table.add(0x3a, 9, 0, 11); - table.addMany(r(0x30, 0x3a), 9, 8, 10); - table.add(0x3b, 9, 8, 10); - table.addMany([0x3c, 0x3d, 0x3e, 0x3f], 9, 9, 10); - table.addMany(EXECUTABLES, 11, 0, 11); - table.addMany(r(0x20, 0x80), 11, 0, 11); - table.addMany(r(0x1c, 0x20), 11, 0, 11); - table.addMany(EXECUTABLES, 10, 0, 10); - table.add(0x7f, 10, 0, 10); - table.addMany(r(0x1c, 0x20), 10, 0, 10); - table.addMany(r(0x30, 0x3a), 10, 8, 10); - table.add(0x3b, 10, 8, 10); - table.addMany([0x3a, 0x3c, 0x3d, 0x3e, 0x3f], 10, 0, 11); - table.addMany(r(0x20, 0x30), 10, 9, 12); - table.addMany(EXECUTABLES, 12, 0, 12); - table.add(0x7f, 12, 0, 12); - table.addMany(r(0x1c, 0x20), 12, 0, 12); - table.addMany(r(0x20, 0x30), 12, 9, 12); - table.addMany(r(0x30, 0x40), 12, 0, 11); - table.addMany(r(0x40, 0x7f), 12, 12, 13); - table.addMany(r(0x40, 0x7f), 10, 12, 13); - table.addMany(r(0x40, 0x7f), 9, 12, 13); - table.addMany(EXECUTABLES, 13, 13, 13); - table.addMany(PRINTABLES, 13, 13, 13); - table.add(0x7f, 13, 0, 13); - table.addMany([0x1b, 0x9c], 13, 14, 0); - return table; -})(); -var DcsDummy = (function () { - function DcsDummy() { - } - DcsDummy.prototype.hook = function (collect, params, flag) { }; - DcsDummy.prototype.put = function (data, start, end) { }; - DcsDummy.prototype.unhook = function () { }; - return DcsDummy; -}()); -var EscapeSequenceParser = (function (_super) { - __extends(EscapeSequenceParser, _super); - function EscapeSequenceParser(TRANSITIONS) { - if (TRANSITIONS === void 0) { TRANSITIONS = exports.VT500_TRANSITION_TABLE; } - var _this = _super.call(this) || this; - _this.TRANSITIONS = TRANSITIONS; - _this.initialState = 0; - _this.currentState = _this.initialState; - _this._osc = ''; - _this._params = [0]; - _this._collect = ''; - _this._printHandlerFb = function (data, start, end) { }; - _this._executeHandlerFb = function (code) { }; - _this._csiHandlerFb = function (collect, params, flag) { }; - _this._escHandlerFb = function (collect, flag) { }; - _this._oscHandlerFb = function (identifier, data) { }; - _this._dcsHandlerFb = new DcsDummy(); - _this._errorHandlerFb = function (state) { return state; }; - _this._printHandler = _this._printHandlerFb; - _this._executeHandlers = Object.create(null); - _this._csiHandlers = Object.create(null); - _this._escHandlers = Object.create(null); - _this._oscHandlers = Object.create(null); - _this._dcsHandlers = Object.create(null); - _this._activeDcsHandler = null; - _this._errorHandler = _this._errorHandlerFb; - _this.setEscHandler('\\', function () { }); - return _this; - } - EscapeSequenceParser.prototype.dispose = function () { - this._printHandlerFb = null; - this._executeHandlerFb = null; - this._csiHandlerFb = null; - this._escHandlerFb = null; - this._oscHandlerFb = null; - this._dcsHandlerFb = null; - this._errorHandlerFb = null; - this._printHandler = null; - this._executeHandlers = null; - this._csiHandlers = null; - this._escHandlers = null; - this._oscHandlers = null; - this._dcsHandlers = null; - this._activeDcsHandler = null; - this._errorHandler = null; - }; - EscapeSequenceParser.prototype.setPrintHandler = function (callback) { - this._printHandler = callback; - }; - EscapeSequenceParser.prototype.clearPrintHandler = function () { - this._printHandler = this._printHandlerFb; - }; - EscapeSequenceParser.prototype.setExecuteHandler = function (flag, callback) { - this._executeHandlers[flag.charCodeAt(0)] = callback; - }; - EscapeSequenceParser.prototype.clearExecuteHandler = function (flag) { - if (this._executeHandlers[flag.charCodeAt(0)]) - delete this._executeHandlers[flag.charCodeAt(0)]; - }; - EscapeSequenceParser.prototype.setExecuteHandlerFallback = function (callback) { - this._executeHandlerFb = callback; - }; - EscapeSequenceParser.prototype.setCsiHandler = function (flag, callback) { - this._csiHandlers[flag.charCodeAt(0)] = callback; - }; - EscapeSequenceParser.prototype.clearCsiHandler = function (flag) { - if (this._csiHandlers[flag.charCodeAt(0)]) - delete this._csiHandlers[flag.charCodeAt(0)]; - }; - EscapeSequenceParser.prototype.setCsiHandlerFallback = function (callback) { - this._csiHandlerFb = callback; - }; - EscapeSequenceParser.prototype.setEscHandler = function (collectAndFlag, callback) { - this._escHandlers[collectAndFlag] = callback; - }; - EscapeSequenceParser.prototype.clearEscHandler = function (collectAndFlag) { - if (this._escHandlers[collectAndFlag]) - delete this._escHandlers[collectAndFlag]; - }; - EscapeSequenceParser.prototype.setEscHandlerFallback = function (callback) { - this._escHandlerFb = callback; - }; - EscapeSequenceParser.prototype.setOscHandler = function (ident, callback) { - this._oscHandlers[ident] = callback; - }; - EscapeSequenceParser.prototype.clearOscHandler = function (ident) { - if (this._oscHandlers[ident]) - delete this._oscHandlers[ident]; - }; - EscapeSequenceParser.prototype.setOscHandlerFallback = function (callback) { - this._oscHandlerFb = callback; - }; - EscapeSequenceParser.prototype.setDcsHandler = function (collectAndFlag, handler) { - this._dcsHandlers[collectAndFlag] = handler; - }; - EscapeSequenceParser.prototype.clearDcsHandler = function (collectAndFlag) { - if (this._dcsHandlers[collectAndFlag]) - delete this._dcsHandlers[collectAndFlag]; - }; - EscapeSequenceParser.prototype.setDcsHandlerFallback = function (handler) { - this._dcsHandlerFb = handler; - }; - EscapeSequenceParser.prototype.setErrorHandler = function (callback) { - this._errorHandler = callback; - }; - EscapeSequenceParser.prototype.clearErrorHandler = function () { - this._errorHandler = this._errorHandlerFb; - }; - EscapeSequenceParser.prototype.reset = function () { - this.currentState = this.initialState; - this._osc = ''; - this._params = [0]; - this._collect = ''; - this._activeDcsHandler = null; - }; - EscapeSequenceParser.prototype.parse = function (data) { - var code = 0; - var transition = 0; - var error = false; - var currentState = this.currentState; - var print = -1; - var dcs = -1; - var osc = this._osc; - var collect = this._collect; - var params = this._params; - var table = this.TRANSITIONS.table; - var dcsHandler = this._activeDcsHandler; - var callback = null; - var l = data.length; - for (var i = 0; i < l; ++i) { - code = data.charCodeAt(i); - if (currentState === 0 && code > 0x1f && code < 0x80) { - print = (~print) ? print : i; - do - i++; - while (i < l && data.charCodeAt(i) > 0x1f && data.charCodeAt(i) < 0x80); - i--; - continue; - } - if (currentState === 4 && (code > 0x2f && code < 0x39)) { - params[params.length - 1] = params[params.length - 1] * 10 + code - 48; - continue; - } - transition = (code < 0xa0) ? (table[currentState << 8 | code]) : DEFAULT_TRANSITION; - switch (transition >> 4) { - case 2: - print = (~print) ? print : i; - break; - case 3: - if (~print) { - this._printHandler(data, print, i); - print = -1; - } - callback = this._executeHandlers[code]; - if (callback) - callback(); - else - this._executeHandlerFb(code); - break; - case 0: - if (~print) { - this._printHandler(data, print, i); - print = -1; - } - else if (~dcs) { - dcsHandler.put(data, dcs, i); - dcs = -1; - } - break; - case 1: - if (code > 0x9f) { - switch (currentState) { - case 0: - print = (~print) ? print : i; - break; - case 8: - osc += String.fromCharCode(code); - transition |= 8; - break; - case 6: - transition |= 6; - break; - case 11: - transition |= 11; - break; - case 13: - dcs = (~dcs) ? dcs : i; - transition |= 13; - break; - default: - error = true; - } - } - else { - error = true; - } - if (error) { - var inject = this._errorHandler({ - position: i, - code: code, - currentState: currentState, - print: print, - dcs: dcs, - osc: osc, - collect: collect, - params: params, - abort: false - }); - if (inject.abort) - return; - error = false; - } - break; - case 7: - callback = this._csiHandlers[code]; - if (callback) - callback(params, collect); - else - this._csiHandlerFb(collect, params, code); - break; - case 8: - if (code === 0x3b) - params.push(0); - else - params[params.length - 1] = params[params.length - 1] * 10 + code - 48; - break; - case 9: - collect += String.fromCharCode(code); - break; - case 10: - callback = this._escHandlers[collect + String.fromCharCode(code)]; - if (callback) - callback(collect, code); - else - this._escHandlerFb(collect, code); - break; - case 11: - if (~print) { - this._printHandler(data, print, i); - print = -1; - } - osc = ''; - params = [0]; - collect = ''; - dcs = -1; - break; - case 12: - dcsHandler = this._dcsHandlers[collect + String.fromCharCode(code)]; - if (!dcsHandler) - dcsHandler = this._dcsHandlerFb; - dcsHandler.hook(collect, params, code); - break; - case 13: - dcs = (~dcs) ? dcs : i; - break; - case 14: - if (dcsHandler) { - if (~dcs) - dcsHandler.put(data, dcs, i); - dcsHandler.unhook(); - dcsHandler = null; - } - if (code === 0x1b) - transition |= 1; - osc = ''; - params = [0]; - collect = ''; - dcs = -1; - break; - case 4: - if (~print) { - this._printHandler(data, print, i); - print = -1; - } - osc = ''; - break; - case 5: - osc += data.charAt(i); - break; - case 6: - if (osc && code !== 0x18 && code !== 0x1a) { - var idx = osc.indexOf(';'); - if (idx === -1) { - this._oscHandlerFb(-1, osc); - } - else { - var identifier = parseInt(osc.substring(0, idx)); - var content = osc.substring(idx + 1); - callback = this._oscHandlers[identifier]; - if (callback) - callback(content); - else - this._oscHandlerFb(identifier, content); - } - } - if (code === 0x1b) - transition |= 1; - osc = ''; - params = [0]; - collect = ''; - dcs = -1; - break; - } - currentState = transition & 15; - } - if (currentState === 0 && ~print) { - this._printHandler(data, print, data.length); - } - else if (currentState === 13 && ~dcs && dcsHandler) { - dcsHandler.put(data, dcs, data.length); - } - this._osc = osc; - this._collect = collect; - this._params = params; - this._activeDcsHandler = dcsHandler; - this.currentState = currentState; - }; - return EscapeSequenceParser; -}(Lifecycle_1.Disposable)); -exports.EscapeSequenceParser = EscapeSequenceParser; - -},{"./common/Lifecycle":18}],8:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var EscapeSequences_1 = require("./common/data/EscapeSequences"); -var Charsets_1 = require("./core/data/Charsets"); -var Buffer_1 = require("./Buffer"); -var CharWidth_1 = require("./CharWidth"); -var EscapeSequenceParser_1 = require("./EscapeSequenceParser"); -var Lifecycle_1 = require("./common/Lifecycle"); -var GLEVEL = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 }; -var RequestTerminfo = (function () { - function RequestTerminfo(_terminal) { - this._terminal = _terminal; - } - RequestTerminfo.prototype.hook = function (collect, params, flag) { - this._data = ''; - }; - RequestTerminfo.prototype.put = function (data, start, end) { - this._data += data.substring(start, end); - }; - RequestTerminfo.prototype.unhook = function () { - this._terminal.handler(EscapeSequences_1.C0.ESC + "P0+r" + this._data + EscapeSequences_1.C0.ESC + "\\"); - }; - return RequestTerminfo; -}()); -var DECRQSS = (function () { - function DECRQSS(_terminal) { - this._terminal = _terminal; - } - DECRQSS.prototype.hook = function (collect, params, flag) { - this._data = ''; - }; - DECRQSS.prototype.put = function (data, start, end) { - this._data += data.substring(start, end); - }; - DECRQSS.prototype.unhook = function () { - switch (this._data) { - case '"q': - return this._terminal.handler(EscapeSequences_1.C0.ESC + "P1$r0\"q" + EscapeSequences_1.C0.ESC + "\\"); - case '"p': - return this._terminal.handler(EscapeSequences_1.C0.ESC + "P1$r61\"p" + EscapeSequences_1.C0.ESC + "\\"); - case 'r': - var pt = '' + (this._terminal.buffer.scrollTop + 1) + - ';' + (this._terminal.buffer.scrollBottom + 1) + 'r'; - return this._terminal.handler(EscapeSequences_1.C0.ESC + "P1$r" + pt + EscapeSequences_1.C0.ESC + "\\"); - case 'm': - return this._terminal.handler(EscapeSequences_1.C0.ESC + "P1$r0m" + EscapeSequences_1.C0.ESC + "\\"); - case ' q': - var STYLES = { 'block': 2, 'underline': 4, 'bar': 6 }; - var style = STYLES[this._terminal.getOption('cursorStyle')]; - style -= this._terminal.getOption('cursorBlink'); - return this._terminal.handler(EscapeSequences_1.C0.ESC + "P1$r" + style + " q" + EscapeSequences_1.C0.ESC + "\\"); - default: - this._terminal.error('Unknown DCS $q %s', this._data); - this._terminal.handler(EscapeSequences_1.C0.ESC + "P0$r" + this._data + EscapeSequences_1.C0.ESC + "\\"); - } - }; - return DECRQSS; -}()); -var InputHandler = (function (_super) { - __extends(InputHandler, _super); - function InputHandler(_terminal, _parser) { - if (_parser === void 0) { _parser = new EscapeSequenceParser_1.EscapeSequenceParser(); } - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._parser = _parser; - _this.register(_this._parser); - _this._surrogateFirst = ''; - _this._parser.setCsiHandlerFallback(function (collect, params, flag) { - _this._terminal.error('Unknown CSI code: ', { collect: collect, params: params, flag: String.fromCharCode(flag) }); - }); - _this._parser.setEscHandlerFallback(function (collect, flag) { - _this._terminal.error('Unknown ESC code: ', { collect: collect, flag: String.fromCharCode(flag) }); - }); - _this._parser.setExecuteHandlerFallback(function (code) { - _this._terminal.error('Unknown EXECUTE code: ', { code: code }); - }); - _this._parser.setOscHandlerFallback(function (identifier, data) { - _this._terminal.error('Unknown OSC code: ', { identifier: identifier, data: data }); - }); - _this._parser.setPrintHandler(function (data, start, end) { return _this.print(data, start, end); }); - _this._parser.setCsiHandler('@', function (params, collect) { return _this.insertChars(params); }); - _this._parser.setCsiHandler('A', function (params, collect) { return _this.cursorUp(params); }); - _this._parser.setCsiHandler('B', function (params, collect) { return _this.cursorDown(params); }); - _this._parser.setCsiHandler('C', function (params, collect) { return _this.cursorForward(params); }); - _this._parser.setCsiHandler('D', function (params, collect) { return _this.cursorBackward(params); }); - _this._parser.setCsiHandler('E', function (params, collect) { return _this.cursorNextLine(params); }); - _this._parser.setCsiHandler('F', function (params, collect) { return _this.cursorPrecedingLine(params); }); - _this._parser.setCsiHandler('G', function (params, collect) { return _this.cursorCharAbsolute(params); }); - _this._parser.setCsiHandler('H', function (params, collect) { return _this.cursorPosition(params); }); - _this._parser.setCsiHandler('I', function (params, collect) { return _this.cursorForwardTab(params); }); - _this._parser.setCsiHandler('J', function (params, collect) { return _this.eraseInDisplay(params); }); - _this._parser.setCsiHandler('K', function (params, collect) { return _this.eraseInLine(params); }); - _this._parser.setCsiHandler('L', function (params, collect) { return _this.insertLines(params); }); - _this._parser.setCsiHandler('M', function (params, collect) { return _this.deleteLines(params); }); - _this._parser.setCsiHandler('P', function (params, collect) { return _this.deleteChars(params); }); - _this._parser.setCsiHandler('S', function (params, collect) { return _this.scrollUp(params); }); - _this._parser.setCsiHandler('T', function (params, collect) { return _this.scrollDown(params, collect); }); - _this._parser.setCsiHandler('X', function (params, collect) { return _this.eraseChars(params); }); - _this._parser.setCsiHandler('Z', function (params, collect) { return _this.cursorBackwardTab(params); }); - _this._parser.setCsiHandler('`', function (params, collect) { return _this.charPosAbsolute(params); }); - _this._parser.setCsiHandler('a', function (params, collect) { return _this.hPositionRelative(params); }); - _this._parser.setCsiHandler('b', function (params, collect) { return _this.repeatPrecedingCharacter(params); }); - _this._parser.setCsiHandler('c', function (params, collect) { return _this.sendDeviceAttributes(params, collect); }); - _this._parser.setCsiHandler('d', function (params, collect) { return _this.linePosAbsolute(params); }); - _this._parser.setCsiHandler('e', function (params, collect) { return _this.vPositionRelative(params); }); - _this._parser.setCsiHandler('f', function (params, collect) { return _this.hVPosition(params); }); - _this._parser.setCsiHandler('g', function (params, collect) { return _this.tabClear(params); }); - _this._parser.setCsiHandler('h', function (params, collect) { return _this.setMode(params, collect); }); - _this._parser.setCsiHandler('l', function (params, collect) { return _this.resetMode(params, collect); }); - _this._parser.setCsiHandler('m', function (params, collect) { return _this.charAttributes(params); }); - _this._parser.setCsiHandler('n', function (params, collect) { return _this.deviceStatus(params, collect); }); - _this._parser.setCsiHandler('p', function (params, collect) { return _this.softReset(params, collect); }); - _this._parser.setCsiHandler('q', function (params, collect) { return _this.setCursorStyle(params, collect); }); - _this._parser.setCsiHandler('r', function (params, collect) { return _this.setScrollRegion(params, collect); }); - _this._parser.setCsiHandler('s', function (params, collect) { return _this.saveCursor(params); }); - _this._parser.setCsiHandler('u', function (params, collect) { return _this.restoreCursor(params); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.BEL, function () { return _this.bell(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.LF, function () { return _this.lineFeed(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.VT, function () { return _this.lineFeed(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.FF, function () { return _this.lineFeed(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.CR, function () { return _this.carriageReturn(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.BS, function () { return _this.backspace(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.HT, function () { return _this.tab(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.SO, function () { return _this.shiftOut(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C0.SI, function () { return _this.shiftIn(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C1.IND, function () { return _this.index(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C1.NEL, function () { return _this.nextLine(); }); - _this._parser.setExecuteHandler(EscapeSequences_1.C1.HTS, function () { return _this.tabSet(); }); - _this._parser.setOscHandler(0, function (data) { return _this.setTitle(data); }); - _this._parser.setOscHandler(2, function (data) { return _this.setTitle(data); }); - _this._parser.setEscHandler('7', function () { return _this.saveCursor([]); }); - _this._parser.setEscHandler('8', function () { return _this.restoreCursor([]); }); - _this._parser.setEscHandler('D', function () { return _this.index(); }); - _this._parser.setEscHandler('E', function () { return _this.nextLine(); }); - _this._parser.setEscHandler('H', function () { return _this.tabSet(); }); - _this._parser.setEscHandler('M', function () { return _this.reverseIndex(); }); - _this._parser.setEscHandler('=', function () { return _this.keypadApplicationMode(); }); - _this._parser.setEscHandler('>', function () { return _this.keypadNumericMode(); }); - _this._parser.setEscHandler('c', function () { return _this.reset(); }); - _this._parser.setEscHandler('n', function () { return _this.setgLevel(2); }); - _this._parser.setEscHandler('o', function () { return _this.setgLevel(3); }); - _this._parser.setEscHandler('|', function () { return _this.setgLevel(3); }); - _this._parser.setEscHandler('}', function () { return _this.setgLevel(2); }); - _this._parser.setEscHandler('~', function () { return _this.setgLevel(1); }); - _this._parser.setEscHandler('%@', function () { return _this.selectDefaultCharset(); }); - _this._parser.setEscHandler('%G', function () { return _this.selectDefaultCharset(); }); - var _loop_1 = function (flag) { - this_1._parser.setEscHandler('(' + flag, function () { return _this.selectCharset('(' + flag); }); - this_1._parser.setEscHandler(')' + flag, function () { return _this.selectCharset(')' + flag); }); - this_1._parser.setEscHandler('*' + flag, function () { return _this.selectCharset('*' + flag); }); - this_1._parser.setEscHandler('+' + flag, function () { return _this.selectCharset('+' + flag); }); - this_1._parser.setEscHandler('-' + flag, function () { return _this.selectCharset('-' + flag); }); - this_1._parser.setEscHandler('.' + flag, function () { return _this.selectCharset('.' + flag); }); - this_1._parser.setEscHandler('/' + flag, function () { return _this.selectCharset('/' + flag); }); - }; - var this_1 = this; - for (var flag in Charsets_1.CHARSETS) { - _loop_1(flag); - } - _this._parser.setErrorHandler(function (state) { - _this._terminal.error('Parsing error: ', state); - return state; - }); - _this._parser.setDcsHandler('$q', new DECRQSS(_this._terminal)); - _this._parser.setDcsHandler('+q', new RequestTerminfo(_this._terminal)); - return _this; - } - InputHandler.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._terminal = null; - }; - InputHandler.prototype.parse = function (data) { - if (!this._terminal) { - return; - } - var buffer = this._terminal.buffer; - var cursorStartX = buffer.x; - var cursorStartY = buffer.y; - if (this._terminal.debug) { - this._terminal.log('data: ' + data); - } - if (this._surrogateFirst) { - data = this._surrogateFirst + data; - this._surrogateFirst = ''; - } - this._parser.parse(data); - buffer = this._terminal.buffer; - if (buffer.x !== cursorStartX || buffer.y !== cursorStartY) { - this._terminal.emit('cursormove'); - } - }; - InputHandler.prototype.print = function (data, start, end) { - var char; - var code; - var chWidth; - var buffer = this._terminal.buffer; - var charset = this._terminal.charset; - var screenReaderMode = this._terminal.options.screenReaderMode; - var cols = this._terminal.cols; - var wraparoundMode = this._terminal.wraparoundMode; - var insertMode = this._terminal.insertMode; - var curAttr = this._terminal.curAttr; - var bufferRow = buffer.lines.get(buffer.y + buffer.ybase); - this._terminal.updateRange(buffer.y); - for (var stringPosition = start; stringPosition < end; ++stringPosition) { - char = data.charAt(stringPosition); - code = data.charCodeAt(stringPosition); - if (0xD800 <= code && code <= 0xDBFF) { - if (++stringPosition >= end) { - this._surrogateFirst = char; - continue; - } - var second = data.charCodeAt(stringPosition); - if (0xDC00 <= second && second <= 0xDFFF) { - code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - char += data.charAt(stringPosition); - } - else { - stringPosition--; - } - } - chWidth = CharWidth_1.wcwidth(code); - if (charset) { - char = charset[char] || char; - code = char.charCodeAt(0); - } - if (screenReaderMode) { - this._terminal.emit('a11y.char', char); - } - if (!chWidth && buffer.x) { - var chMinusOne = bufferRow.get(buffer.x - 1); - if (chMinusOne) { - if (!chMinusOne[Buffer_1.CHAR_DATA_WIDTH_INDEX]) { - var chMinusTwo = bufferRow.get(buffer.x - 2); - if (chMinusTwo) { - chMinusTwo[Buffer_1.CHAR_DATA_CHAR_INDEX] += char; - chMinusTwo[Buffer_1.CHAR_DATA_CODE_INDEX] = code; - bufferRow.set(buffer.x - 2, chMinusTwo); - } - } - else { - chMinusOne[Buffer_1.CHAR_DATA_CHAR_INDEX] += char; - chMinusOne[Buffer_1.CHAR_DATA_CODE_INDEX] = code; - bufferRow.set(buffer.x - 1, chMinusOne); - } - } - continue; - } - if (buffer.x + chWidth - 1 >= cols) { - if (wraparoundMode) { - buffer.x = 0; - buffer.y++; - if (buffer.y > buffer.scrollBottom) { - buffer.y--; - this._terminal.scroll(true); - } - else { - buffer.lines.get(buffer.y).isWrapped = true; - } - bufferRow = buffer.lines.get(buffer.y + buffer.ybase); - } - else { - if (chWidth === 2) { - continue; - } - } - } - if (insertMode) { - bufferRow.insertCells(buffer.x, chWidth, [curAttr, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - var lastCell = bufferRow.get(cols - 1); - if (lastCell[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) { - bufferRow.set(cols - 1, [curAttr, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - } - } - bufferRow.set(buffer.x++, [curAttr, char, chWidth, code]); - if (chWidth > 0) { - while (--chWidth) { - bufferRow.set(buffer.x++, [curAttr, '', 0, undefined]); - } - } - } - this._terminal.updateRange(buffer.y); - }; - InputHandler.prototype.bell = function () { - this._terminal.bell(); - }; - InputHandler.prototype.lineFeed = function () { - var buffer = this._terminal.buffer; - if (this._terminal.options.convertEol) { - buffer.x = 0; - } - buffer.y++; - if (buffer.y > buffer.scrollBottom) { - buffer.y--; - this._terminal.scroll(); - } - if (buffer.x >= this._terminal.cols) { - buffer.x--; - } - this._terminal.emit('linefeed'); - }; - InputHandler.prototype.carriageReturn = function () { - this._terminal.buffer.x = 0; - }; - InputHandler.prototype.backspace = function () { - if (this._terminal.buffer.x > 0) { - this._terminal.buffer.x--; - } - }; - InputHandler.prototype.tab = function () { - var originalX = this._terminal.buffer.x; - this._terminal.buffer.x = this._terminal.buffer.nextStop(); - if (this._terminal.options.screenReaderMode) { - this._terminal.emit('a11y.tab', this._terminal.buffer.x - originalX); - } - }; - InputHandler.prototype.shiftOut = function () { - this._terminal.setgLevel(1); - }; - InputHandler.prototype.shiftIn = function () { - this._terminal.setgLevel(0); - }; - InputHandler.prototype.insertChars = function (params) { - this._terminal.buffer.lines.get(this._terminal.buffer.y + this._terminal.buffer.ybase).insertCells(this._terminal.buffer.x, params[0] || 1, [this._terminal.eraseAttr(), Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - this._terminal.updateRange(this._terminal.buffer.y); - }; - InputHandler.prototype.cursorUp = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y -= param; - if (this._terminal.buffer.y < 0) { - this._terminal.buffer.y = 0; - } - }; - InputHandler.prototype.cursorDown = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y += param; - if (this._terminal.buffer.y >= this._terminal.rows) { - this._terminal.buffer.y = this._terminal.rows - 1; - } - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x--; - } - }; - InputHandler.prototype.cursorForward = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.x += param; - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x = this._terminal.cols - 1; - } - }; - InputHandler.prototype.cursorBackward = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x--; - } - this._terminal.buffer.x -= param; - if (this._terminal.buffer.x < 0) { - this._terminal.buffer.x = 0; - } - }; - InputHandler.prototype.cursorNextLine = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y += param; - if (this._terminal.buffer.y >= this._terminal.rows) { - this._terminal.buffer.y = this._terminal.rows - 1; - } - this._terminal.buffer.x = 0; - }; - InputHandler.prototype.cursorPrecedingLine = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y -= param; - if (this._terminal.buffer.y < 0) { - this._terminal.buffer.y = 0; - } - this._terminal.buffer.x = 0; - }; - InputHandler.prototype.cursorCharAbsolute = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.x = param - 1; - }; - InputHandler.prototype.cursorPosition = function (params) { - var col; - var row = params[0] - 1; - if (params.length >= 2) { - col = params[1] - 1; - } - else { - col = 0; - } - if (row < 0) { - row = 0; - } - else if (row >= this._terminal.rows) { - row = this._terminal.rows - 1; - } - if (col < 0) { - col = 0; - } - else if (col >= this._terminal.cols) { - col = this._terminal.cols - 1; - } - this._terminal.buffer.x = col; - this._terminal.buffer.y = row; - }; - InputHandler.prototype.cursorForwardTab = function (params) { - var param = params[0] || 1; - while (param--) { - this._terminal.buffer.x = this._terminal.buffer.nextStop(); - } - }; - InputHandler.prototype._eraseInBufferLine = function (y, start, end, clearWrap) { - if (clearWrap === void 0) { clearWrap = false; } - var line = this._terminal.buffer.lines.get(this._terminal.buffer.ybase + y); - line.replaceCells(start, end, [this._terminal.eraseAttr(), Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - if (clearWrap) { - line.isWrapped = false; - } - }; - InputHandler.prototype._resetBufferLine = function (y) { - this._eraseInBufferLine(y, 0, this._terminal.cols, true); - }; - InputHandler.prototype.eraseInDisplay = function (params) { - var j; - switch (params[0]) { - case 0: - j = this._terminal.buffer.y; - this._terminal.updateRange(j); - this._eraseInBufferLine(j++, this._terminal.buffer.x, this._terminal.cols, this._terminal.buffer.x === 0); - for (; j < this._terminal.rows; j++) { - this._resetBufferLine(j); - } - this._terminal.updateRange(j); - break; - case 1: - j = this._terminal.buffer.y; - this._terminal.updateRange(j); - this._eraseInBufferLine(j, 0, this._terminal.buffer.x + 1, true); - if (this._terminal.buffer.x + 1 >= this._terminal.cols) { - this._terminal.buffer.lines.get(j + 1).isWrapped = false; - } - while (j--) { - this._resetBufferLine(j); - } - this._terminal.updateRange(0); - break; - case 2: - j = this._terminal.rows; - this._terminal.updateRange(j - 1); - while (j--) { - this._resetBufferLine(j); - } - this._terminal.updateRange(0); - break; - case 3: - var scrollBackSize = this._terminal.buffer.lines.length - this._terminal.rows; - if (scrollBackSize > 0) { - this._terminal.buffer.lines.trimStart(scrollBackSize); - this._terminal.buffer.ybase = Math.max(this._terminal.buffer.ybase - scrollBackSize, 0); - this._terminal.buffer.ydisp = Math.max(this._terminal.buffer.ydisp - scrollBackSize, 0); - this._terminal.emit('scroll', 0); - } - break; - } - }; - InputHandler.prototype.eraseInLine = function (params) { - switch (params[0]) { - case 0: - this._eraseInBufferLine(this._terminal.buffer.y, this._terminal.buffer.x, this._terminal.cols); - break; - case 1: - this._eraseInBufferLine(this._terminal.buffer.y, 0, this._terminal.buffer.x + 1); - break; - case 2: - this._eraseInBufferLine(this._terminal.buffer.y, 0, this._terminal.cols); - break; - } - this._terminal.updateRange(this._terminal.buffer.y); - }; - InputHandler.prototype.insertLines = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - var buffer = this._terminal.buffer; - var row = buffer.y + buffer.ybase; - var scrollBottomRowsOffset = this._terminal.rows - 1 - buffer.scrollBottom; - var scrollBottomAbsolute = this._terminal.rows - 1 + buffer.ybase - scrollBottomRowsOffset + 1; - while (param--) { - buffer.lines.splice(scrollBottomAbsolute - 1, 1); - buffer.lines.splice(row, 0, buffer.getBlankLine(this._terminal.eraseAttr())); - } - this._terminal.updateRange(buffer.y); - this._terminal.updateRange(buffer.scrollBottom); - }; - InputHandler.prototype.deleteLines = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - var buffer = this._terminal.buffer; - var row = buffer.y + buffer.ybase; - var j; - j = this._terminal.rows - 1 - buffer.scrollBottom; - j = this._terminal.rows - 1 + buffer.ybase - j; - while (param--) { - buffer.lines.splice(row, 1); - buffer.lines.splice(j, 0, buffer.getBlankLine(this._terminal.eraseAttr())); - } - this._terminal.updateRange(buffer.y); - this._terminal.updateRange(buffer.scrollBottom); - }; - InputHandler.prototype.deleteChars = function (params) { - this._terminal.buffer.lines.get(this._terminal.buffer.y + this._terminal.buffer.ybase).deleteCells(this._terminal.buffer.x, params[0] || 1, [this._terminal.eraseAttr(), Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - this._terminal.updateRange(this._terminal.buffer.y); - }; - InputHandler.prototype.scrollUp = function (params) { - var param = params[0] || 1; - var buffer = this._terminal.buffer; - while (param--) { - buffer.lines.splice(buffer.ybase + buffer.scrollTop, 1); - buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(Buffer_1.DEFAULT_ATTR)); - } - this._terminal.updateRange(buffer.scrollTop); - this._terminal.updateRange(buffer.scrollBottom); - }; - InputHandler.prototype.scrollDown = function (params, collect) { - if (params.length < 2 && !collect) { - var param = params[0] || 1; - var buffer = this._terminal.buffer; - while (param--) { - buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 1); - buffer.lines.splice(buffer.ybase + buffer.scrollBottom, 0, buffer.getBlankLine(Buffer_1.DEFAULT_ATTR)); - } - this._terminal.updateRange(buffer.scrollTop); - this._terminal.updateRange(buffer.scrollBottom); - } - }; - InputHandler.prototype.eraseChars = function (params) { - this._terminal.buffer.lines.get(this._terminal.buffer.y + this._terminal.buffer.ybase).replaceCells(this._terminal.buffer.x, this._terminal.buffer.x + (params[0] || 1), [this._terminal.eraseAttr(), Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - }; - InputHandler.prototype.cursorBackwardTab = function (params) { - var param = params[0] || 1; - var buffer = this._terminal.buffer; - while (param--) { - buffer.x = buffer.prevStop(); - } - }; - InputHandler.prototype.charPosAbsolute = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.x = param - 1; - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x = this._terminal.cols - 1; - } - }; - InputHandler.prototype.hPositionRelative = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.x += param; - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x = this._terminal.cols - 1; - } - }; - InputHandler.prototype.repeatPrecedingCharacter = function (params) { - var buffer = this._terminal.buffer; - var line = buffer.lines.get(buffer.ybase + buffer.y); - line.replaceCells(buffer.x, buffer.x + (params[0] || 1), line.get(buffer.x - 1) || [Buffer_1.DEFAULT_ATTR, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]); - }; - InputHandler.prototype.sendDeviceAttributes = function (params, collect) { - if (params[0] > 0) { - return; - } - if (!collect) { - if (this._terminal.is('xterm') || this._terminal.is('rxvt-unicode') || this._terminal.is('screen')) { - this._terminal.handler(EscapeSequences_1.C0.ESC + '[?1;2c'); - } - else if (this._terminal.is('linux')) { - this._terminal.handler(EscapeSequences_1.C0.ESC + '[?6c'); - } - } - else if (collect === '>') { - if (this._terminal.is('xterm')) { - this._terminal.handler(EscapeSequences_1.C0.ESC + '[>0;276;0c'); - } - else if (this._terminal.is('rxvt-unicode')) { - this._terminal.handler(EscapeSequences_1.C0.ESC + '[>85;95;0c'); - } - else if (this._terminal.is('linux')) { - this._terminal.handler(params[0] + 'c'); - } - else if (this._terminal.is('screen')) { - this._terminal.handler(EscapeSequences_1.C0.ESC + '[>83;40003;0c'); - } - } - }; - InputHandler.prototype.linePosAbsolute = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y = param - 1; - if (this._terminal.buffer.y >= this._terminal.rows) { - this._terminal.buffer.y = this._terminal.rows - 1; - } - }; - InputHandler.prototype.vPositionRelative = function (params) { - var param = params[0]; - if (param < 1) { - param = 1; - } - this._terminal.buffer.y += param; - if (this._terminal.buffer.y >= this._terminal.rows) { - this._terminal.buffer.y = this._terminal.rows - 1; - } - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x--; - } - }; - InputHandler.prototype.hVPosition = function (params) { - if (params[0] < 1) - params[0] = 1; - if (params[1] < 1) - params[1] = 1; - this._terminal.buffer.y = params[0] - 1; - if (this._terminal.buffer.y >= this._terminal.rows) { - this._terminal.buffer.y = this._terminal.rows - 1; - } - this._terminal.buffer.x = params[1] - 1; - if (this._terminal.buffer.x >= this._terminal.cols) { - this._terminal.buffer.x = this._terminal.cols - 1; - } - }; - InputHandler.prototype.tabClear = function (params) { - var param = params[0]; - if (param <= 0) { - delete this._terminal.buffer.tabs[this._terminal.buffer.x]; - } - else if (param === 3) { - this._terminal.buffer.tabs = {}; - } - }; - InputHandler.prototype.setMode = function (params, collect) { - if (params.length > 1) { - for (var i = 0; i < params.length; i++) { - this.setMode([params[i]]); - } - return; - } - if (!collect) { - switch (params[0]) { - case 4: - this._terminal.insertMode = true; - break; - case 20: - break; - } - } - else if (collect === '?') { - switch (params[0]) { - case 1: - this._terminal.applicationCursor = true; - break; - case 2: - this._terminal.setgCharset(0, Charsets_1.DEFAULT_CHARSET); - this._terminal.setgCharset(1, Charsets_1.DEFAULT_CHARSET); - this._terminal.setgCharset(2, Charsets_1.DEFAULT_CHARSET); - this._terminal.setgCharset(3, Charsets_1.DEFAULT_CHARSET); - break; - case 3: - this._terminal.savedCols = this._terminal.cols; - this._terminal.resize(132, this._terminal.rows); - break; - case 6: - this._terminal.originMode = true; - break; - case 7: - this._terminal.wraparoundMode = true; - break; - case 12: - break; - case 66: - this._terminal.log('Serial port requested application keypad.'); - this._terminal.applicationKeypad = true; - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - break; - case 9: - case 1000: - case 1002: - case 1003: - this._terminal.x10Mouse = params[0] === 9; - this._terminal.vt200Mouse = params[0] === 1000; - this._terminal.normalMouse = params[0] > 1000; - this._terminal.mouseEvents = true; - this._terminal.element.classList.add('enable-mouse-events'); - this._terminal.selectionManager.disable(); - this._terminal.log('Binding to mouse events.'); - break; - case 1004: - this._terminal.sendFocus = true; - break; - case 1005: - this._terminal.utfMouse = true; - break; - case 1006: - this._terminal.sgrMouse = true; - break; - case 1015: - this._terminal.urxvtMouse = true; - break; - case 25: - this._terminal.cursorHidden = false; - break; - case 1048: - this.saveCursor(params); - break; - case 1049: - this.saveCursor(params); - case 47: - case 1047: - this._terminal.buffers.activateAltBuffer(this._terminal.eraseAttr()); - this._terminal.refresh(0, this._terminal.rows - 1); - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - this._terminal.showCursor(); - break; - case 2004: - this._terminal.bracketedPasteMode = true; - break; - } - } - }; - InputHandler.prototype.resetMode = function (params, collect) { - if (params.length > 1) { - for (var i = 0; i < params.length; i++) { - this.resetMode([params[i]]); - } - return; - } - if (!collect) { - switch (params[0]) { - case 4: - this._terminal.insertMode = false; - break; - case 20: - break; - } - } - else if (collect === '?') { - switch (params[0]) { - case 1: - this._terminal.applicationCursor = false; - break; - case 3: - if (this._terminal.cols === 132 && this._terminal.savedCols) { - this._terminal.resize(this._terminal.savedCols, this._terminal.rows); - } - delete this._terminal.savedCols; - break; - case 6: - this._terminal.originMode = false; - break; - case 7: - this._terminal.wraparoundMode = false; - break; - case 12: - break; - case 66: - this._terminal.log('Switching back to normal keypad.'); - this._terminal.applicationKeypad = false; - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - break; - case 9: - case 1000: - case 1002: - case 1003: - this._terminal.x10Mouse = false; - this._terminal.vt200Mouse = false; - this._terminal.normalMouse = false; - this._terminal.mouseEvents = false; - this._terminal.element.classList.remove('enable-mouse-events'); - this._terminal.selectionManager.enable(); - break; - case 1004: - this._terminal.sendFocus = false; - break; - case 1005: - this._terminal.utfMouse = false; - break; - case 1006: - this._terminal.sgrMouse = false; - break; - case 1015: - this._terminal.urxvtMouse = false; - break; - case 25: - this._terminal.cursorHidden = true; - break; - case 1048: - this.restoreCursor(params); - break; - case 1049: - case 47: - case 1047: - this._terminal.buffers.activateNormalBuffer(); - if (params[0] === 1049) { - this.restoreCursor(params); - } - this._terminal.refresh(0, this._terminal.rows - 1); - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - this._terminal.showCursor(); - break; - case 2004: - this._terminal.bracketedPasteMode = false; - break; - } - } - }; - InputHandler.prototype.charAttributes = function (params) { - if (params.length === 1 && params[0] === 0) { - this._terminal.curAttr = Buffer_1.DEFAULT_ATTR; - return; - } - var l = params.length; - var flags = this._terminal.curAttr >> 18; - var fg = (this._terminal.curAttr >> 9) & 0x1ff; - var bg = this._terminal.curAttr & 0x1ff; - var p; - for (var i = 0; i < l; i++) { - p = params[i]; - if (p >= 30 && p <= 37) { - fg = p - 30; - } - else if (p >= 40 && p <= 47) { - bg = p - 40; - } - else if (p >= 90 && p <= 97) { - p += 8; - fg = p - 90; - } - else if (p >= 100 && p <= 107) { - p += 8; - bg = p - 100; - } - else if (p === 0) { - flags = Buffer_1.DEFAULT_ATTR >> 18; - fg = (Buffer_1.DEFAULT_ATTR >> 9) & 0x1ff; - bg = Buffer_1.DEFAULT_ATTR & 0x1ff; - } - else if (p === 1) { - flags |= 1; - } - else if (p === 3) { - flags |= 64; - } - else if (p === 4) { - flags |= 2; - } - else if (p === 5) { - flags |= 4; - } - else if (p === 7) { - flags |= 8; - } - else if (p === 8) { - flags |= 16; - } - else if (p === 2) { - flags |= 32; - } - else if (p === 22) { - flags &= ~1; - flags &= ~32; - } - else if (p === 23) { - flags &= ~64; - } - else if (p === 24) { - flags &= ~2; - } - else if (p === 25) { - flags &= ~4; - } - else if (p === 27) { - flags &= ~8; - } - else if (p === 28) { - flags &= ~16; - } - else if (p === 39) { - fg = (Buffer_1.DEFAULT_ATTR >> 9) & 0x1ff; - } - else if (p === 49) { - bg = Buffer_1.DEFAULT_ATTR & 0x1ff; - } - else if (p === 38) { - if (params[i + 1] === 2) { - i += 2; - fg = this._terminal.matchColor(params[i] & 0xff, params[i + 1] & 0xff, params[i + 2] & 0xff); - if (fg === -1) - fg = 0x1ff; - i += 2; - } - else if (params[i + 1] === 5) { - i += 2; - p = params[i] & 0xff; - fg = p; - } - } - else if (p === 48) { - if (params[i + 1] === 2) { - i += 2; - bg = this._terminal.matchColor(params[i] & 0xff, params[i + 1] & 0xff, params[i + 2] & 0xff); - if (bg === -1) - bg = 0x1ff; - i += 2; - } - else if (params[i + 1] === 5) { - i += 2; - p = params[i] & 0xff; - bg = p; - } - } - else if (p === 100) { - fg = (Buffer_1.DEFAULT_ATTR >> 9) & 0x1ff; - bg = Buffer_1.DEFAULT_ATTR & 0x1ff; - } - else { - this._terminal.error('Unknown SGR attribute: %d.', p); - } - } - this._terminal.curAttr = (flags << 18) | (fg << 9) | bg; - }; - InputHandler.prototype.deviceStatus = function (params, collect) { - if (!collect) { - switch (params[0]) { - case 5: - this._terminal.emit('data', EscapeSequences_1.C0.ESC + "[0n"); - break; - case 6: - var y = this._terminal.buffer.y + 1; - var x = this._terminal.buffer.x + 1; - this._terminal.emit('data', EscapeSequences_1.C0.ESC + "[" + y + ";" + x + "R"); - break; - } - } - else if (collect === '?') { - switch (params[0]) { - case 6: - var y = this._terminal.buffer.y + 1; - var x = this._terminal.buffer.x + 1; - this._terminal.emit('data', EscapeSequences_1.C0.ESC + "[?" + y + ";" + x + "R"); - break; - case 15: - break; - case 25: - break; - case 26: - break; - case 53: - break; - } - } - }; - InputHandler.prototype.softReset = function (params, collect) { - if (collect === '!') { - this._terminal.cursorHidden = false; - this._terminal.insertMode = false; - this._terminal.originMode = false; - this._terminal.wraparoundMode = true; - this._terminal.applicationKeypad = false; - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - this._terminal.applicationCursor = false; - this._terminal.buffer.scrollTop = 0; - this._terminal.buffer.scrollBottom = this._terminal.rows - 1; - this._terminal.curAttr = Buffer_1.DEFAULT_ATTR; - this._terminal.buffer.x = this._terminal.buffer.y = 0; - this._terminal.charset = null; - this._terminal.glevel = 0; - this._terminal.charsets = [null]; - } - }; - InputHandler.prototype.setCursorStyle = function (params, collect) { - if (collect === ' ') { - var param = params[0] < 1 ? 1 : params[0]; - switch (param) { - case 1: - case 2: - this._terminal.setOption('cursorStyle', 'block'); - break; - case 3: - case 4: - this._terminal.setOption('cursorStyle', 'underline'); - break; - case 5: - case 6: - this._terminal.setOption('cursorStyle', 'bar'); - break; - } - var isBlinking = param % 2 === 1; - this._terminal.setOption('cursorBlink', isBlinking); - } - }; - InputHandler.prototype.setScrollRegion = function (params, collect) { - if (collect) - return; - this._terminal.buffer.scrollTop = (params[0] || 1) - 1; - this._terminal.buffer.scrollBottom = (params[1] && params[1] <= this._terminal.rows ? params[1] : this._terminal.rows) - 1; - this._terminal.buffer.x = 0; - this._terminal.buffer.y = 0; - }; - InputHandler.prototype.saveCursor = function (params) { - this._terminal.buffer.savedX = this._terminal.buffer.x; - this._terminal.buffer.savedY = this._terminal.buffer.y; - this._terminal.buffer.savedCurAttr = this._terminal.curAttr; - }; - InputHandler.prototype.restoreCursor = function (params) { - this._terminal.buffer.x = this._terminal.buffer.savedX || 0; - this._terminal.buffer.y = this._terminal.buffer.savedY || 0; - this._terminal.curAttr = this._terminal.buffer.savedCurAttr || Buffer_1.DEFAULT_ATTR; - }; - InputHandler.prototype.setTitle = function (data) { - this._terminal.handleTitle(data); - }; - InputHandler.prototype.nextLine = function () { - this._terminal.buffer.x = 0; - this.index(); - }; - InputHandler.prototype.keypadApplicationMode = function () { - this._terminal.log('Serial port requested application keypad.'); - this._terminal.applicationKeypad = true; - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - }; - InputHandler.prototype.keypadNumericMode = function () { - this._terminal.log('Switching back to normal keypad.'); - this._terminal.applicationKeypad = false; - if (this._terminal.viewport) { - this._terminal.viewport.syncScrollArea(); - } - }; - InputHandler.prototype.selectDefaultCharset = function () { - this._terminal.setgLevel(0); - this._terminal.setgCharset(0, Charsets_1.DEFAULT_CHARSET); - }; - InputHandler.prototype.selectCharset = function (collectAndFlag) { - if (collectAndFlag.length !== 2) - return this.selectDefaultCharset(); - if (collectAndFlag[0] === '/') - return; - this._terminal.setgCharset(GLEVEL[collectAndFlag[0]], Charsets_1.CHARSETS[collectAndFlag[1]] || Charsets_1.DEFAULT_CHARSET); - }; - InputHandler.prototype.index = function () { - this._terminal.index(); - }; - InputHandler.prototype.tabSet = function () { - this._terminal.tabSet(); - }; - InputHandler.prototype.reverseIndex = function () { - this._terminal.reverseIndex(); - }; - InputHandler.prototype.reset = function () { - this._parser.reset(); - this._terminal.reset(); - }; - InputHandler.prototype.setgLevel = function (level) { - this._terminal.setgLevel(level); - }; - return InputHandler; -}(Lifecycle_1.Disposable)); -exports.InputHandler = InputHandler; - -},{"./Buffer":2,"./CharWidth":5,"./EscapeSequenceParser":7,"./common/Lifecycle":18,"./common/data/EscapeSequences":20,"./core/data/Charsets":22}],9:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var MouseZoneManager_1 = require("./ui/MouseZoneManager"); -var EventEmitter_1 = require("./common/EventEmitter"); -var Buffer_1 = require("./Buffer"); -var CharWidth_1 = require("./CharWidth"); -var Linkifier = (function (_super) { - __extends(Linkifier, _super); - function Linkifier(_terminal) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._linkMatchers = []; - _this._nextLinkMatcherId = 0; - _this._rowsToLinkify = { - start: null, - end: null - }; - return _this; - } - Linkifier.prototype.attachToDom = function (mouseZoneManager) { - this._mouseZoneManager = mouseZoneManager; - }; - Linkifier.prototype.linkifyRows = function (start, end) { - var _this = this; - if (!this._mouseZoneManager) { - return; - } - if (this._rowsToLinkify.start === null) { - this._rowsToLinkify.start = start; - this._rowsToLinkify.end = end; - } - else { - this._rowsToLinkify.start = Math.min(this._rowsToLinkify.start, start); - this._rowsToLinkify.end = Math.max(this._rowsToLinkify.end, end); - } - this._mouseZoneManager.clearAll(start, end); - if (this._rowsTimeoutId) { - clearTimeout(this._rowsTimeoutId); - } - this._rowsTimeoutId = setTimeout(function () { return _this._linkifyRows(); }, Linkifier.TIME_BEFORE_LINKIFY); - }; - Linkifier.prototype._linkifyRows = function () { - this._rowsTimeoutId = null; - var buffer = this._terminal.buffer; - var absoluteRowIndexStart = buffer.ydisp + this._rowsToLinkify.start; - if (absoluteRowIndexStart >= buffer.lines.length) { - return; - } - var absoluteRowIndexEnd = buffer.ydisp + Math.min(this._rowsToLinkify.end, this._terminal.rows) + 1; - var overscanLineLimit = Math.ceil(Linkifier.OVERSCAN_CHAR_LIMIT / this._terminal.cols); - var iterator = this._terminal.buffer.iterator(false, absoluteRowIndexStart, absoluteRowIndexEnd, overscanLineLimit, overscanLineLimit); - while (iterator.hasNext()) { - var lineData = iterator.next(); - for (var i = 0; i < this._linkMatchers.length; i++) { - this._doLinkifyRow(lineData.range.first, lineData.content, this._linkMatchers[i]); - } - } - this._rowsToLinkify.start = null; - this._rowsToLinkify.end = null; - }; - Linkifier.prototype.registerLinkMatcher = function (regex, handler, options) { - if (options === void 0) { options = {}; } - if (!handler) { - throw new Error('handler must be defined'); - } - var matcher = { - id: this._nextLinkMatcherId++, - regex: regex, - handler: handler, - matchIndex: options.matchIndex, - validationCallback: options.validationCallback, - hoverTooltipCallback: options.tooltipCallback, - hoverLeaveCallback: options.leaveCallback, - willLinkActivate: options.willLinkActivate, - priority: options.priority || 0 - }; - this._addLinkMatcherToList(matcher); - return matcher.id; - }; - Linkifier.prototype._addLinkMatcherToList = function (matcher) { - if (this._linkMatchers.length === 0) { - this._linkMatchers.push(matcher); - return; - } - for (var i = this._linkMatchers.length - 1; i >= 0; i--) { - if (matcher.priority <= this._linkMatchers[i].priority) { - this._linkMatchers.splice(i + 1, 0, matcher); - return; - } - } - this._linkMatchers.splice(0, 0, matcher); - }; - Linkifier.prototype.deregisterLinkMatcher = function (matcherId) { - for (var i = 0; i < this._linkMatchers.length; i++) { - if (this._linkMatchers[i].id === matcherId) { - this._linkMatchers.splice(i, 1); - return true; - } - } - return false; - }; - Linkifier.prototype._doLinkifyRow = function (rowIndex, text, matcher) { - var _this = this; - var rex = new RegExp(matcher.regex.source, matcher.regex.flags + 'g'); - var match; - var stringIndex = -1; - var _loop_1 = function () { - var uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex]; - if (!uri) { - if (this_1._terminal.debug) { - console.log({ match: match, matcher: matcher }); - throw new Error('match found without corresponding matchIndex'); - } - return "break"; - } - stringIndex = text.indexOf(uri, stringIndex + 1); - rex.lastIndex = stringIndex + uri.length; - var bufferIndex = this_1._terminal.buffer.stringIndexToBufferIndex(rowIndex, stringIndex); - var line = this_1._terminal.buffer.lines.get(bufferIndex[0]); - var char = line.get(bufferIndex[1]); - var fg; - if (char) { - var attr = char[Buffer_1.CHAR_DATA_ATTR_INDEX]; - fg = (attr >> 9) & 0x1ff; - } - if (matcher.validationCallback) { - matcher.validationCallback(uri, function (isValid) { - if (_this._rowsTimeoutId) { - return; - } - if (isValid) { - _this._addLink(bufferIndex[1], bufferIndex[0] - _this._terminal.buffer.ydisp, uri, matcher, fg); - } - }); - } - else { - this_1._addLink(bufferIndex[1], bufferIndex[0] - this_1._terminal.buffer.ydisp, uri, matcher, fg); - } - }; - var this_1 = this; - while ((match = rex.exec(text)) !== null) { - var state_1 = _loop_1(); - if (state_1 === "break") - break; - } - }; - Linkifier.prototype._addLink = function (x, y, uri, matcher, fg) { - var _this = this; - var width = CharWidth_1.getStringCellWidth(uri); - var x1 = x % this._terminal.cols; - var y1 = y + Math.floor(x / this._terminal.cols); - var x2 = (x1 + width) % this._terminal.cols; - var y2 = y1 + Math.floor((x1 + width) / this._terminal.cols); - if (x2 === 0) { - x2 = this._terminal.cols; - y2--; - } - this._mouseZoneManager.add(new MouseZoneManager_1.MouseZone(x1 + 1, y1 + 1, x2 + 1, y2 + 1, function (e) { - if (matcher.handler) { - return matcher.handler(e, uri); - } - window.open(uri, '_blank'); - }, function (e) { - _this.emit("linkhover", _this._createLinkHoverEvent(x1, y1, x2, y2, fg)); - _this._terminal.element.classList.add('xterm-cursor-pointer'); - }, function (e) { - _this.emit("linktooltip", _this._createLinkHoverEvent(x1, y1, x2, y2, fg)); - if (matcher.hoverTooltipCallback) { - matcher.hoverTooltipCallback(e, uri); - } - }, function () { - _this.emit("linkleave", _this._createLinkHoverEvent(x1, y1, x2, y2, fg)); - _this._terminal.element.classList.remove('xterm-cursor-pointer'); - if (matcher.hoverLeaveCallback) { - matcher.hoverLeaveCallback(); - } - }, function (e) { - if (matcher.willLinkActivate) { - return matcher.willLinkActivate(e, uri); - } - return true; - })); - }; - Linkifier.prototype._createLinkHoverEvent = function (x1, y1, x2, y2, fg) { - return { x1: x1, y1: y1, x2: x2, y2: y2, cols: this._terminal.cols, fg: fg }; - }; - Linkifier.TIME_BEFORE_LINKIFY = 200; - Linkifier.OVERSCAN_CHAR_LIMIT = 2000; - return Linkifier; -}(EventEmitter_1.EventEmitter)); -exports.Linkifier = Linkifier; - -},{"./Buffer":2,"./CharWidth":5,"./common/EventEmitter":17,"./ui/MouseZoneManager":49}],10:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var MouseHelper_1 = require("./utils/MouseHelper"); -var Browser = require("./core/Platform"); -var EventEmitter_1 = require("./common/EventEmitter"); -var SelectionModel_1 = require("./SelectionModel"); -var Buffer_1 = require("./Buffer"); -var AltClickHandler_1 = require("./handlers/AltClickHandler"); -var DRAG_SCROLL_MAX_THRESHOLD = 50; -var DRAG_SCROLL_MAX_SPEED = 15; -var DRAG_SCROLL_INTERVAL = 50; -var ALT_CLICK_MOVE_CURSOR_TIME = 500; -var WORD_SEPARATORS = ' ()[]{}\'"'; -var NON_BREAKING_SPACE_CHAR = String.fromCharCode(160); -var ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g'); -var SelectionManager = (function (_super) { - __extends(SelectionManager, _super); - function SelectionManager(_terminal, _charMeasure) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._charMeasure = _charMeasure; - _this._enabled = true; - _this._initListeners(); - _this.enable(); - _this._model = new SelectionModel_1.SelectionModel(_terminal); - _this._activeSelectionMode = 0; - return _this; - } - SelectionManager.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._removeMouseDownListeners(); - }; - Object.defineProperty(SelectionManager.prototype, "_buffer", { - get: function () { - return this._terminal.buffers.active; - }, - enumerable: true, - configurable: true - }); - SelectionManager.prototype._initListeners = function () { - var _this = this; - this._mouseMoveListener = function (event) { return _this._onMouseMove(event); }; - this._mouseUpListener = function (event) { return _this._onMouseUp(event); }; - this._trimListener = function (amount) { return _this._onTrim(amount); }; - this.initBuffersListeners(); - }; - SelectionManager.prototype.initBuffersListeners = function () { - var _this = this; - this._terminal.buffer.lines.on('trim', this._trimListener); - this._terminal.buffers.on('activate', function (e) { return _this._onBufferActivate(e); }); - }; - SelectionManager.prototype.disable = function () { - this.clearSelection(); - this._enabled = false; - }; - SelectionManager.prototype.enable = function () { - this._enabled = true; - }; - Object.defineProperty(SelectionManager.prototype, "selectionStart", { - get: function () { return this._model.finalSelectionStart; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SelectionManager.prototype, "selectionEnd", { - get: function () { return this._model.finalSelectionEnd; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SelectionManager.prototype, "hasSelection", { - get: function () { - var start = this._model.finalSelectionStart; - var end = this._model.finalSelectionEnd; - if (!start || !end) { - return false; - } - return start[0] !== end[0] || start[1] !== end[1]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SelectionManager.prototype, "selectionText", { - get: function () { - var start = this._model.finalSelectionStart; - var end = this._model.finalSelectionEnd; - if (!start || !end) { - return ''; - } - var result = []; - if (this._activeSelectionMode === 3) { - if (start[0] === end[0]) { - return ''; - } - for (var i = start[1]; i <= end[1]; i++) { - var lineText = this._buffer.translateBufferLineToString(i, true, start[0], end[0]); - result.push(lineText); - } - } - else { - var startRowEndCol = start[1] === end[1] ? end[0] : null; - result.push(this._buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol)); - for (var i = start[1] + 1; i <= end[1] - 1; i++) { - var bufferLine = this._buffer.lines.get(i); - var lineText = this._buffer.translateBufferLineToString(i, true); - if (bufferLine.isWrapped) { - result[result.length - 1] += lineText; - } - else { - result.push(lineText); - } - } - if (start[1] !== end[1]) { - var bufferLine = this._buffer.lines.get(end[1]); - var lineText = this._buffer.translateBufferLineToString(end[1], true, 0, end[0]); - if (bufferLine.isWrapped) { - result[result.length - 1] += lineText; - } - else { - result.push(lineText); - } - } - } - var formattedResult = result.map(function (line) { - return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' '); - }).join(Browser.isMSWindows ? '\r\n' : '\n'); - return formattedResult; - }, - enumerable: true, - configurable: true - }); - SelectionManager.prototype.clearSelection = function () { - this._model.clearSelection(); - this._removeMouseDownListeners(); - this.refresh(); - }; - SelectionManager.prototype.refresh = function (isNewSelection) { - var _this = this; - if (!this._refreshAnimationFrame) { - this._refreshAnimationFrame = window.requestAnimationFrame(function () { return _this._refresh(); }); - } - if (Browser.isLinux && isNewSelection) { - var selectionText = this.selectionText; - if (selectionText.length) { - this.emit('newselection', this.selectionText); - } - } - }; - SelectionManager.prototype._refresh = function () { - this._refreshAnimationFrame = null; - this.emit('refresh', { - start: this._model.finalSelectionStart, - end: this._model.finalSelectionEnd, - columnSelectMode: this._activeSelectionMode === 3 - }); - }; - SelectionManager.prototype.isClickInSelection = function (event) { - var coords = this._getMouseBufferCoords(event); - var start = this._model.finalSelectionStart; - var end = this._model.finalSelectionEnd; - if (!start || !end) { - return false; - } - return this._areCoordsInSelection(coords, start, end); - }; - SelectionManager.prototype._areCoordsInSelection = function (coords, start, end) { - return (coords[1] > start[1] && coords[1] < end[1]) || - (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) || - (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) || - (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]); - }; - SelectionManager.prototype.selectWordAtCursor = function (event) { - var coords = this._getMouseBufferCoords(event); - if (coords) { - this._selectWordAt(coords, false); - this._model.selectionEnd = null; - this.refresh(true); - } - }; - SelectionManager.prototype.selectAll = function () { - this._model.isSelectAllActive = true; - this.refresh(); - this._terminal.emit('selection'); - }; - SelectionManager.prototype.selectLines = function (start, end) { - this._model.clearSelection(); - start = Math.max(start, 0); - end = Math.min(end, this._terminal.buffer.lines.length - 1); - this._model.selectionStart = [0, start]; - this._model.selectionEnd = [this._terminal.cols, end]; - this.refresh(); - this._terminal.emit('selection'); - }; - SelectionManager.prototype._onTrim = function (amount) { - var needsRefresh = this._model.onTrim(amount); - if (needsRefresh) { - this.refresh(); - } - }; - SelectionManager.prototype._getMouseBufferCoords = function (event) { - var coords = this._terminal.mouseHelper.getCoords(event, this._terminal.screenElement, this._charMeasure, this._terminal.cols, this._terminal.rows, true); - if (!coords) { - return null; - } - coords[0]--; - coords[1]--; - coords[1] += this._terminal.buffer.ydisp; - return coords; - }; - SelectionManager.prototype._getMouseEventScrollAmount = function (event) { - var offset = MouseHelper_1.MouseHelper.getCoordsRelativeToElement(event, this._terminal.screenElement)[1]; - var terminalHeight = this._terminal.rows * Math.ceil(this._charMeasure.height * this._terminal.options.lineHeight); - if (offset >= 0 && offset <= terminalHeight) { - return 0; - } - if (offset > terminalHeight) { - offset -= terminalHeight; - } - offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD); - offset /= DRAG_SCROLL_MAX_THRESHOLD; - return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1)); - }; - SelectionManager.prototype.shouldForceSelection = function (event) { - if (Browser.isMac) { - return event.altKey && this._terminal.options.macOptionClickForcesSelection; - } - return event.shiftKey; - }; - SelectionManager.prototype.onMouseDown = function (event) { - this._mouseDownTimeStamp = event.timeStamp; - if (event.button === 2 && this.hasSelection) { - return; - } - if (event.button !== 0) { - return; - } - if (!this._enabled) { - if (!this.shouldForceSelection(event)) { - return; - } - event.stopPropagation(); - } - event.preventDefault(); - this._dragScrollAmount = 0; - if (this._enabled && event.shiftKey) { - this._onIncrementalClick(event); - } - else { - if (event.detail === 1) { - this._onSingleClick(event); - } - else if (event.detail === 2) { - this._onDoubleClick(event); - } - else if (event.detail === 3) { - this._onTripleClick(event); - } - } - this._addMouseDownListeners(); - this.refresh(true); - }; - SelectionManager.prototype._addMouseDownListeners = function () { - var _this = this; - this._terminal.element.ownerDocument.addEventListener('mousemove', this._mouseMoveListener); - this._terminal.element.ownerDocument.addEventListener('mouseup', this._mouseUpListener); - this._dragScrollIntervalTimer = setInterval(function () { return _this._dragScroll(); }, DRAG_SCROLL_INTERVAL); - }; - SelectionManager.prototype._removeMouseDownListeners = function () { - if (this._terminal.element.ownerDocument) { - this._terminal.element.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener); - this._terminal.element.ownerDocument.removeEventListener('mouseup', this._mouseUpListener); - } - clearInterval(this._dragScrollIntervalTimer); - this._dragScrollIntervalTimer = null; - }; - SelectionManager.prototype._onIncrementalClick = function (event) { - if (this._model.selectionStart) { - this._model.selectionEnd = this._getMouseBufferCoords(event); - } - }; - SelectionManager.prototype._onSingleClick = function (event) { - this._model.selectionStartLength = 0; - this._model.isSelectAllActive = false; - this._activeSelectionMode = this.shouldColumnSelect(event) ? 3 : 0; - this._model.selectionStart = this._getMouseBufferCoords(event); - if (!this._model.selectionStart) { - return; - } - this._model.selectionEnd = null; - var line = this._buffer.lines.get(this._model.selectionStart[1]); - if (!line) { - return; - } - if (line.length >= this._model.selectionStart[0]) { - return; - } - var char = line.get(this._model.selectionStart[0]); - if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - this._model.selectionStart[0]++; - } - }; - SelectionManager.prototype._onDoubleClick = function (event) { - var coords = this._getMouseBufferCoords(event); - if (coords) { - this._activeSelectionMode = 1; - this._selectWordAt(coords, true); - } - }; - SelectionManager.prototype._onTripleClick = function (event) { - var coords = this._getMouseBufferCoords(event); - if (coords) { - this._activeSelectionMode = 2; - this._selectLineAt(coords[1]); - } - }; - SelectionManager.prototype.shouldColumnSelect = function (event) { - return event.altKey && !(Browser.isMac && this._terminal.options.macOptionClickForcesSelection); - }; - SelectionManager.prototype._onMouseMove = function (event) { - event.stopImmediatePropagation(); - var previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null; - this._model.selectionEnd = this._getMouseBufferCoords(event); - if (!this._model.selectionEnd) { - this.refresh(true); - return; - } - if (this._activeSelectionMode === 2) { - if (this._model.selectionEnd[1] < this._model.selectionStart[1]) { - this._model.selectionEnd[0] = 0; - } - else { - this._model.selectionEnd[0] = this._terminal.cols; - } - } - else if (this._activeSelectionMode === 1) { - this._selectToWordAt(this._model.selectionEnd); - } - this._dragScrollAmount = this._getMouseEventScrollAmount(event); - if (this._activeSelectionMode !== 3) { - if (this._dragScrollAmount > 0) { - this._model.selectionEnd[0] = this._terminal.cols; - } - else if (this._dragScrollAmount < 0) { - this._model.selectionEnd[0] = 0; - } - } - if (this._model.selectionEnd[1] < this._buffer.lines.length) { - var char = this._buffer.lines.get(this._model.selectionEnd[1]).get(this._model.selectionEnd[0]); - if (char && char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - this._model.selectionEnd[0]++; - } - } - if (!previousSelectionEnd || - previousSelectionEnd[0] !== this._model.selectionEnd[0] || - previousSelectionEnd[1] !== this._model.selectionEnd[1]) { - this.refresh(true); - } - }; - SelectionManager.prototype._dragScroll = function () { - if (this._dragScrollAmount) { - this._terminal.scrollLines(this._dragScrollAmount, false); - if (this._dragScrollAmount > 0) { - if (this._activeSelectionMode !== 3) { - this._model.selectionEnd[0] = this._terminal.cols; - } - this._model.selectionEnd[1] = Math.min(this._terminal.buffer.ydisp + this._terminal.rows, this._terminal.buffer.lines.length - 1); - } - else { - if (this._activeSelectionMode !== 3) { - this._model.selectionEnd[0] = 0; - } - this._model.selectionEnd[1] = this._terminal.buffer.ydisp; - } - this.refresh(); - } - }; - SelectionManager.prototype._onMouseUp = function (event) { - var timeElapsed = event.timeStamp - this._mouseDownTimeStamp; - this._removeMouseDownListeners(); - if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME) { - (new AltClickHandler_1.AltClickHandler(event, this._terminal)).move(); - } - else if (this.hasSelection) { - this._terminal.emit('selection'); - } - }; - SelectionManager.prototype._onBufferActivate = function (e) { - this.clearSelection(); - e.inactiveBuffer.lines.off('trim', this._trimListener); - e.activeBuffer.lines.on('trim', this._trimListener); - }; - SelectionManager.prototype._convertViewportColToCharacterIndex = function (bufferLine, coords) { - var charIndex = coords[0]; - for (var i = 0; coords[0] >= i; i++) { - var char = bufferLine.get(i); - if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - charIndex--; - } - else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1 && coords[0] !== i) { - charIndex += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - } - } - return charIndex; - }; - SelectionManager.prototype.setSelection = function (col, row, length) { - this._model.clearSelection(); - this._removeMouseDownListeners(); - this._model.selectionStart = [col, row]; - this._model.selectionStartLength = length; - this.refresh(); - }; - SelectionManager.prototype._getWordAt = function (coords, allowWhitespaceOnlySelection, followWrappedLinesAbove, followWrappedLinesBelow) { - if (followWrappedLinesAbove === void 0) { followWrappedLinesAbove = true; } - if (followWrappedLinesBelow === void 0) { followWrappedLinesBelow = true; } - if (coords[0] >= this._terminal.cols) { - return null; - } - var bufferLine = this._buffer.lines.get(coords[1]); - if (!bufferLine) { - return null; - } - var line = this._buffer.translateBufferLineToString(coords[1], false); - var startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords); - var endIndex = startIndex; - var charOffset = coords[0] - startIndex; - var leftWideCharCount = 0; - var rightWideCharCount = 0; - var leftLongCharOffset = 0; - var rightLongCharOffset = 0; - if (line.charAt(startIndex) === ' ') { - while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') { - startIndex--; - } - while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') { - endIndex++; - } - } - else { - var startCol = coords[0]; - var endCol = coords[0]; - if (bufferLine.get(startCol)[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - leftWideCharCount++; - startCol--; - } - if (bufferLine.get(endCol)[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) { - rightWideCharCount++; - endCol++; - } - if (bufferLine.get(endCol)[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) { - rightLongCharOffset += bufferLine.get(endCol)[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - endIndex += bufferLine.get(endCol)[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - } - while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.get(startCol - 1))) { - var char = bufferLine.get(startCol - 1); - if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - leftWideCharCount++; - startCol--; - } - else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) { - leftLongCharOffset += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - startIndex -= char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - } - startIndex--; - startCol--; - } - while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.get(endCol + 1))) { - var char = bufferLine.get(endCol + 1); - if (char[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 2) { - rightWideCharCount++; - endCol++; - } - else if (char[Buffer_1.CHAR_DATA_CHAR_INDEX].length > 1) { - rightLongCharOffset += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - endIndex += char[Buffer_1.CHAR_DATA_CHAR_INDEX].length - 1; - } - endIndex++; - endCol++; - } - } - endIndex++; - var start = startIndex - + charOffset - - leftWideCharCount - + leftLongCharOffset; - var length = Math.min(this._terminal.cols, endIndex - - startIndex - + leftWideCharCount - + rightWideCharCount - - leftLongCharOffset - - rightLongCharOffset); - if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') { - return null; - } - if (followWrappedLinesAbove) { - if (start === 0 && bufferLine.get(0)[Buffer_1.CHAR_DATA_CODE_INDEX] !== 32) { - var previousBufferLine = this._buffer.lines.get(coords[1] - 1); - if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.get(this._terminal.cols - 1)[Buffer_1.CHAR_DATA_CODE_INDEX] !== 32) { - var previousLineWordPosition = this._getWordAt([this._terminal.cols - 1, coords[1] - 1], false, true, false); - if (previousLineWordPosition) { - var offset = this._terminal.cols - previousLineWordPosition.start; - start -= offset; - length += offset; - } - } - } - } - if (followWrappedLinesBelow) { - if (start + length === this._terminal.cols && bufferLine.get(this._terminal.cols - 1)[Buffer_1.CHAR_DATA_CODE_INDEX] !== 32) { - var nextBufferLine = this._buffer.lines.get(coords[1] + 1); - if (nextBufferLine && nextBufferLine.isWrapped && nextBufferLine.get(0)[Buffer_1.CHAR_DATA_CODE_INDEX] !== 32) { - var nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true); - if (nextLineWordPosition) { - length += nextLineWordPosition.length; - } - } - } - } - return { start: start, length: length }; - }; - SelectionManager.prototype._selectWordAt = function (coords, allowWhitespaceOnlySelection) { - var wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection); - if (wordPosition) { - while (wordPosition.start < 0) { - wordPosition.start += this._terminal.cols; - coords[1]--; - } - this._model.selectionStart = [wordPosition.start, coords[1]]; - this._model.selectionStartLength = wordPosition.length; - } - }; - SelectionManager.prototype._selectToWordAt = function (coords) { - var wordPosition = this._getWordAt(coords, true); - if (wordPosition) { - var endRow = coords[1]; - while (wordPosition.start < 0) { - wordPosition.start += this._terminal.cols; - endRow--; - } - if (!this._model.areSelectionValuesReversed()) { - while (wordPosition.start + wordPosition.length > this._terminal.cols) { - wordPosition.length -= this._terminal.cols; - endRow++; - } - } - this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow]; - } - }; - SelectionManager.prototype._isCharWordSeparator = function (charData) { - if (charData[Buffer_1.CHAR_DATA_WIDTH_INDEX] === 0) { - return false; - } - return WORD_SEPARATORS.indexOf(charData[Buffer_1.CHAR_DATA_CHAR_INDEX]) >= 0; - }; - SelectionManager.prototype._selectLineAt = function (line) { - var wrappedRange = this._buffer.getWrappedRangeForLine(line); - this._model.selectionStart = [0, wrappedRange.first]; - this._model.selectionEnd = [this._terminal.cols, wrappedRange.last]; - this._model.selectionStartLength = 0; - }; - return SelectionManager; -}(EventEmitter_1.EventEmitter)); -exports.SelectionManager = SelectionManager; - -},{"./Buffer":2,"./SelectionModel":11,"./common/EventEmitter":17,"./core/Platform":21,"./handlers/AltClickHandler":24,"./utils/MouseHelper":53}],11:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var SelectionModel = (function () { - function SelectionModel(_terminal) { - this._terminal = _terminal; - this.clearSelection(); - } - SelectionModel.prototype.clearSelection = function () { - this.selectionStart = null; - this.selectionEnd = null; - this.isSelectAllActive = false; - this.selectionStartLength = 0; - }; - Object.defineProperty(SelectionModel.prototype, "finalSelectionStart", { - get: function () { - if (this.isSelectAllActive) { - return [0, 0]; - } - if (!this.selectionEnd || !this.selectionStart) { - return this.selectionStart; - } - return this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(SelectionModel.prototype, "finalSelectionEnd", { - get: function () { - if (this.isSelectAllActive) { - return [this._terminal.cols, this._terminal.buffer.ybase + this._terminal.rows - 1]; - } - if (!this.selectionStart) { - return null; - } - if (!this.selectionEnd || this.areSelectionValuesReversed()) { - var startPlusLength = this.selectionStart[0] + this.selectionStartLength; - if (startPlusLength > this._terminal.cols) { - return [startPlusLength % this._terminal.cols, this.selectionStart[1] + Math.floor(startPlusLength / this._terminal.cols)]; - } - return [startPlusLength, this.selectionStart[1]]; - } - if (this.selectionStartLength) { - if (this.selectionEnd[1] === this.selectionStart[1]) { - return [Math.max(this.selectionStart[0] + this.selectionStartLength, this.selectionEnd[0]), this.selectionEnd[1]]; - } - } - return this.selectionEnd; - }, - enumerable: true, - configurable: true - }); - SelectionModel.prototype.areSelectionValuesReversed = function () { - var start = this.selectionStart; - var end = this.selectionEnd; - if (!start || !end) { - return false; - } - return start[1] > end[1] || (start[1] === end[1] && start[0] > end[0]); - }; - SelectionModel.prototype.onTrim = function (amount) { - if (this.selectionStart) { - this.selectionStart[1] -= amount; - } - if (this.selectionEnd) { - this.selectionEnd[1] -= amount; - } - if (this.selectionEnd && this.selectionEnd[1] < 0) { - this.clearSelection(); - return true; - } - if (this.selectionStart && this.selectionStart[1] < 0) { - this.selectionStart[1] = 0; - } - return false; - }; - return SelectionModel; -}()); -exports.SelectionModel = SelectionModel; - -},{}],12:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_BELL_SOUND = 'data:audio/wav;base64,UklGRigBAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQQBAADpAFgCwAMlBZoG/wdmCcoKRAypDQ8PbRDBEQQTOxRtFYcWlBePGIUZXhoiG88bcBz7HHIdzh0WHlMeZx51HmkeUx4WHs8dah0AHXwc3hs9G4saxRnyGBIYGBcQFv8U4RPAEoYRQBACD70NWwwHC6gJOwjWBloF7gOBAhABkf8b/qv8R/ve+Xf4Ife79W/0JfPZ8Z/wde9N7ijtE+wU6xvqM+lb6H7nw+YX5mrlxuQz5Mzje+Ma49fioeKD4nXiYeJy4pHitOL04j/jn+MN5IPkFOWs5U3mDefM55/ogOl36m7rdOyE7abuyu8D8Unyj/Pg9D/2qfcb+Yn6/vuK/Qj/lAAlAg=='; -var SoundManager = (function () { - function SoundManager(_terminal) { - this._terminal = _terminal; - } - Object.defineProperty(SoundManager, "audioContext", { - get: function () { - if (!SoundManager._audioContext) { - var audioContextCtor = window.AudioContext || window.webkitAudioContext; - if (!audioContextCtor) { - console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version'); - return null; - } - SoundManager._audioContext = new audioContextCtor(); - } - return SoundManager._audioContext; - }, - enumerable: true, - configurable: true - }); - SoundManager.prototype.playBellSound = function () { - var ctx = SoundManager.audioContext; - if (!ctx) { - return; - } - var bellAudioSource = ctx.createBufferSource(); - ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._terminal.options.bellSound)), function (buffer) { - bellAudioSource.buffer = buffer; - bellAudioSource.connect(ctx.destination); - bellAudioSource.start(0); - }); - }; - SoundManager.prototype._base64ToArrayBuffer = function (base64) { - var binaryString = window.atob(base64); - var len = binaryString.length; - var bytes = new Uint8Array(len); - for (var i = 0; i < len; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes.buffer; - }; - SoundManager.prototype._removeMimeType = function (dataURI) { - var splitUri = dataURI.split(','); - return splitUri[1]; - }; - return SoundManager; -}()); -exports.SoundManager = SoundManager; - -},{}],13:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.blankLine = 'Blank line'; -exports.promptLabel = 'Terminal input'; -exports.tooMuchOutput = 'Too much output to announce, navigate to rows manually to read'; - -},{}],14:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var BufferSet_1 = require("./BufferSet"); -var Buffer_1 = require("./Buffer"); -var CompositionHelper_1 = require("./CompositionHelper"); -var EventEmitter_1 = require("./common/EventEmitter"); -var Viewport_1 = require("./Viewport"); -var Clipboard_1 = require("./ui/Clipboard"); -var EscapeSequences_1 = require("./common/data/EscapeSequences"); -var InputHandler_1 = require("./InputHandler"); -var Renderer_1 = require("./renderer/Renderer"); -var Linkifier_1 = require("./Linkifier"); -var SelectionManager_1 = require("./SelectionManager"); -var CharMeasure_1 = require("./ui/CharMeasure"); -var Browser = require("./core/Platform"); -var Lifecycle_1 = require("./ui/Lifecycle"); -var Strings = require("./Strings"); -var MouseHelper_1 = require("./utils/MouseHelper"); -var Clone_1 = require("./utils/Clone"); -var SoundManager_1 = require("./SoundManager"); -var ColorManager_1 = require("./renderer/ColorManager"); -var MouseZoneManager_1 = require("./ui/MouseZoneManager"); -var AccessibilityManager_1 = require("./AccessibilityManager"); -var ScreenDprMonitor_1 = require("./ui/ScreenDprMonitor"); -var CharAtlasCache_1 = require("./renderer/atlas/CharAtlasCache"); -var DomRenderer_1 = require("./renderer/dom/DomRenderer"); -var Keyboard_1 = require("./core/input/Keyboard"); -var document = (typeof window !== 'undefined') ? window.document : null; -var WRITE_BUFFER_PAUSE_THRESHOLD = 5; -var WRITE_BATCH_SIZE = 300; -var CONSTRUCTOR_ONLY_OPTIONS = ['cols', 'rows']; -var DEFAULT_OPTIONS = { - cols: 80, - rows: 24, - convertEol: false, - termName: 'xterm', - cursorBlink: false, - cursorStyle: 'block', - bellSound: SoundManager_1.DEFAULT_BELL_SOUND, - bellStyle: 'none', - drawBoldTextInBrightColors: true, - enableBold: true, - experimentalCharAtlas: 'static', - fontFamily: 'courier-new, courier, monospace', - fontSize: 15, - fontWeight: 'normal', - fontWeightBold: 'bold', - lineHeight: 1.0, - letterSpacing: 0, - scrollback: 1000, - screenKeys: false, - screenReaderMode: false, - debug: false, - macOptionIsMeta: false, - macOptionClickForcesSelection: false, - cancelEvents: false, - disableStdin: false, - useFlowControl: false, - allowTransparency: false, - tabStopWidth: 8, - theme: null, - rightClickSelectsWord: Browser.isMac, - rendererType: 'canvas', - experimentalBufferLineImpl: 'TypedArray' -}; -var Terminal = (function (_super) { - __extends(Terminal, _super); - function Terminal(options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.browser = Browser; - _this._blankLine = null; - _this.options = Clone_1.clone(options); - _this._setup(); - return _this; - } - Terminal.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._customKeyEventHandler = null; - CharAtlasCache_1.removeTerminalFromCache(this); - this.handler = function () { }; - this.write = function () { }; - if (this.element && this.element.parentNode) { - this.element.parentNode.removeChild(this.element); - } - }; - Terminal.prototype.destroy = function () { - this.dispose(); - }; - Terminal.prototype._setup = function () { - var _this = this; - Object.keys(DEFAULT_OPTIONS).forEach(function (key) { - if (_this.options[key] === null || _this.options[key] === undefined) { - _this.options[key] = DEFAULT_OPTIONS[key]; - } - }); - this._parent = document ? document.body : null; - this.cols = this.options.cols; - this.rows = this.options.rows; - if (this.options.handler) { - this.on('data', this.options.handler); - } - this.cursorState = 0; - this.cursorHidden = false; - this._customKeyEventHandler = null; - this.applicationKeypad = false; - this.applicationCursor = false; - this.originMode = false; - this.insertMode = false; - this.wraparoundMode = true; - this.bracketedPasteMode = false; - this.charset = null; - this.gcharset = null; - this.glevel = 0; - this.charsets = [null]; - this.curAttr = Buffer_1.DEFAULT_ATTR; - this.params = []; - this.currentParam = 0; - this.writeBuffer = []; - this._writeInProgress = false; - this._xoffSentToCatchUp = false; - this._userScrolling = false; - this._inputHandler = new InputHandler_1.InputHandler(this); - this.register(this._inputHandler); - this.renderer = this.renderer || null; - this.selectionManager = this.selectionManager || null; - this.linkifier = this.linkifier || new Linkifier_1.Linkifier(this); - this._mouseZoneManager = this._mouseZoneManager || null; - this.soundManager = this.soundManager || new SoundManager_1.SoundManager(this); - this.buffers = new BufferSet_1.BufferSet(this); - if (this.selectionManager) { - this.selectionManager.clearSelection(); - this.selectionManager.initBuffersListeners(); - } - }; - Object.defineProperty(Terminal.prototype, "buffer", { - get: function () { - return this.buffers.active; - }, - enumerable: true, - configurable: true - }); - Terminal.prototype.eraseAttr = function () { - return (Buffer_1.DEFAULT_ATTR & ~0x1ff) | (this.curAttr & 0x1ff); - }; - Terminal.prototype.focus = function () { - if (this.textarea) { - this.textarea.focus(); - } - }; - Object.defineProperty(Terminal.prototype, "isFocused", { - get: function () { - return document.activeElement === this.textarea && document.hasFocus(); - }, - enumerable: true, - configurable: true - }); - Terminal.prototype.getOption = function (key) { - if (!(key in DEFAULT_OPTIONS)) { - throw new Error('No option with key "' + key + '"'); - } - return this.options[key]; - }; - Terminal.prototype.setOption = function (key, value) { - if (!(key in DEFAULT_OPTIONS)) { - throw new Error('No option with key "' + key + '"'); - } - if (CONSTRUCTOR_ONLY_OPTIONS.indexOf(key) !== -1) { - console.error("Option \"" + key + "\" can only be set in the constructor"); - } - if (this.options[key] === value) { - return; - } - switch (key) { - case 'bellStyle': - if (!value) { - value = 'none'; - } - break; - case 'cursorStyle': - if (!value) { - value = 'block'; - } - break; - case 'fontWeight': - if (!value) { - value = 'normal'; - } - break; - case 'fontWeightBold': - if (!value) { - value = 'bold'; - } - break; - case 'lineHeight': - if (value < 1) { - console.warn(key + " cannot be less than 1, value: " + value); - return; - } - case 'rendererType': - if (!value) { - value = 'canvas'; - } - break; - case 'tabStopWidth': - if (value < 1) { - console.warn(key + " cannot be less than 1, value: " + value); - return; - } - break; - case 'theme': - if (this.renderer) { - this._setTheme(value); - return; - } - break; - case 'scrollback': - value = Math.min(value, Buffer_1.MAX_BUFFER_SIZE); - if (value < 0) { - console.warn(key + " cannot be less than 0, value: " + value); - return; - } - if (this.options[key] !== value) { - var newBufferLength = this.rows + value; - if (this.buffer.lines.length > newBufferLength) { - var amountToTrim = this.buffer.lines.length - newBufferLength; - var needsRefresh = (this.buffer.ydisp - amountToTrim < 0); - this.buffer.lines.trimStart(amountToTrim); - this.buffer.ybase = Math.max(this.buffer.ybase - amountToTrim, 0); - this.buffer.ydisp = Math.max(this.buffer.ydisp - amountToTrim, 0); - if (needsRefresh) { - this.refresh(0, this.rows - 1); - } - } - } - break; - } - this.options[key] = value; - switch (key) { - case 'fontFamily': - case 'fontSize': - if (this.renderer) { - this.renderer.clear(); - this.charMeasure.measure(this.options); - } - break; - case 'drawBoldTextInBrightColors': - case 'experimentalCharAtlas': - case 'enableBold': - case 'letterSpacing': - case 'lineHeight': - case 'fontWeight': - case 'fontWeightBold': - if (this.renderer) { - this.renderer.clear(); - this.renderer.onResize(this.cols, this.rows); - this.refresh(0, this.rows - 1); - } - case 'rendererType': - if (this.renderer) { - this.unregister(this.renderer); - this.renderer.dispose(); - this.renderer = null; - } - this._setupRenderer(); - this.renderer.onCharSizeChanged(); - if (this._theme) { - this.renderer.setTheme(this._theme); - } - this.mouseHelper.setRenderer(this.renderer); - break; - case 'scrollback': - this.buffers.resize(this.cols, this.rows); - if (this.viewport) { - this.viewport.syncScrollArea(); - } - break; - case 'screenReaderMode': - if (value) { - if (!this._accessibilityManager) { - this._accessibilityManager = new AccessibilityManager_1.AccessibilityManager(this); - } - } - else { - if (this._accessibilityManager) { - this._accessibilityManager.dispose(); - this._accessibilityManager = null; - } - } - break; - case 'tabStopWidth': - this.buffers.setupTabStops(); - break; - case 'experimentalBufferLineImpl': - this.buffers.normal.setBufferLineFactory(value); - this.buffers.alt.setBufferLineFactory(value); - this._blankLine = null; - break; - } - if (this.renderer) { - this.renderer.onOptionsChanged(); - } - }; - Terminal.prototype._onTextAreaFocus = function (ev) { - if (this.sendFocus) { - this.handler(EscapeSequences_1.C0.ESC + '[I'); - } - this.updateCursorStyle(ev); - this.element.classList.add('focus'); - this.showCursor(); - this.emit('focus'); - }; - Terminal.prototype.blur = function () { - return this.textarea.blur(); - }; - Terminal.prototype._onTextAreaBlur = function () { - this.textarea.value = ''; - this.refresh(this.buffer.y, this.buffer.y); - if (this.sendFocus) { - this.handler(EscapeSequences_1.C0.ESC + '[O'); - } - this.element.classList.remove('focus'); - this.emit('blur'); - }; - Terminal.prototype._initGlobal = function () { - var _this = this; - this._bindKeys(); - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'copy', function (event) { - if (!_this.hasSelection()) { - return; - } - Clipboard_1.copyHandler(event, _this, _this.selectionManager); - })); - var pasteHandlerWrapper = function (event) { return Clipboard_1.pasteHandler(event, _this); }; - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'paste', pasteHandlerWrapper)); - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'paste', pasteHandlerWrapper)); - if (Browser.isFirefox) { - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'mousedown', function (event) { - if (event.button === 2) { - Clipboard_1.rightClickHandler(event, _this.textarea, _this.selectionManager, _this.options.rightClickSelectsWord); - } - })); - } - else { - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'contextmenu', function (event) { - Clipboard_1.rightClickHandler(event, _this.textarea, _this.selectionManager, _this.options.rightClickSelectsWord); - })); - } - if (Browser.isLinux) { - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'auxclick', function (event) { - if (event.button === 1) { - Clipboard_1.moveTextAreaUnderMouseCursor(event, _this.textarea); - } - })); - } - }; - Terminal.prototype._bindKeys = function () { - var _this = this; - var self = this; - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'keydown', function (ev) { - if (document.activeElement !== this) { - return; - } - self._keyDown(ev); - }, true)); - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'keypress', function (ev) { - if (document.activeElement !== this) { - return; - } - self._keyPress(ev); - }, true)); - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'keyup', function (ev) { - if (!wasModifierKeyOnlyEvent(ev)) { - _this.focus(); - } - self._keyUp(ev); - }, true)); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'keydown', function (ev) { return _this._keyDown(ev); }, true)); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'keypress', function (ev) { return _this._keyPress(ev); }, true)); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'compositionstart', function () { return _this._compositionHelper.compositionstart(); })); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'compositionupdate', function (e) { return _this._compositionHelper.compositionupdate(e); })); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'compositionend', function () { return _this._compositionHelper.compositionend(); })); - this.register(this.addDisposableListener('refresh', function () { return _this._compositionHelper.updateCompositionElements(); })); - this.register(this.addDisposableListener('refresh', function (data) { return _this._queueLinkification(data.start, data.end); })); - }; - Terminal.prototype.open = function (parent) { - var _this = this; - this._parent = parent || this._parent; - if (!this._parent) { - throw new Error('Terminal requires a parent element.'); - } - this._context = this._parent.ownerDocument.defaultView; - this._document = this._parent.ownerDocument; - this._screenDprMonitor = new ScreenDprMonitor_1.ScreenDprMonitor(); - this._screenDprMonitor.setListener(function () { return _this.emit('dprchange', window.devicePixelRatio); }); - this.register(this._screenDprMonitor); - this.element = this._document.createElement('div'); - this.element.dir = 'ltr'; - this.element.classList.add('terminal'); - this.element.classList.add('xterm'); - this.element.setAttribute('tabindex', '0'); - this._parent.appendChild(this.element); - var fragment = document.createDocumentFragment(); - this._viewportElement = document.createElement('div'); - this._viewportElement.classList.add('xterm-viewport'); - fragment.appendChild(this._viewportElement); - this._viewportScrollArea = document.createElement('div'); - this._viewportScrollArea.classList.add('xterm-scroll-area'); - this._viewportElement.appendChild(this._viewportScrollArea); - this.screenElement = document.createElement('div'); - this.screenElement.classList.add('xterm-screen'); - this._helperContainer = document.createElement('div'); - this._helperContainer.classList.add('xterm-helpers'); - this.screenElement.appendChild(this._helperContainer); - fragment.appendChild(this.screenElement); - this._mouseZoneManager = new MouseZoneManager_1.MouseZoneManager(this); - this.register(this._mouseZoneManager); - this.register(this.addDisposableListener('scroll', function () { return _this._mouseZoneManager.clearAll(); })); - this.linkifier.attachToDom(this._mouseZoneManager); - this.textarea = document.createElement('textarea'); - this.textarea.classList.add('xterm-helper-textarea'); - this.textarea.setAttribute('aria-label', Strings.promptLabel); - this.textarea.setAttribute('aria-multiline', 'false'); - this.textarea.setAttribute('autocorrect', 'off'); - this.textarea.setAttribute('autocapitalize', 'off'); - this.textarea.setAttribute('spellcheck', 'false'); - this.textarea.tabIndex = 0; - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'focus', function (ev) { return _this._onTextAreaFocus(ev); })); - this.register(Lifecycle_1.addDisposableDomListener(this.textarea, 'blur', function () { return _this._onTextAreaBlur(); })); - this._helperContainer.appendChild(this.textarea); - this._compositionView = document.createElement('div'); - this._compositionView.classList.add('composition-view'); - this._compositionHelper = new CompositionHelper_1.CompositionHelper(this.textarea, this._compositionView, this); - this._helperContainer.appendChild(this._compositionView); - this.charMeasure = new CharMeasure_1.CharMeasure(document, this._helperContainer); - this.element.appendChild(fragment); - this._setupRenderer(); - this._theme = this.options.theme; - this.options.theme = null; - this.viewport = new Viewport_1.Viewport(this, this._viewportElement, this._viewportScrollArea, this.charMeasure); - this.viewport.onThemeChanged(this.renderer.colorManager.colors); - this.register(this.viewport); - this.register(this.addDisposableListener('cursormove', function () { return _this.renderer.onCursorMove(); })); - this.register(this.addDisposableListener('resize', function () { return _this.renderer.onResize(_this.cols, _this.rows); })); - this.register(this.addDisposableListener('blur', function () { return _this.renderer.onBlur(); })); - this.register(this.addDisposableListener('focus', function () { return _this.renderer.onFocus(); })); - this.register(this.addDisposableListener('dprchange', function () { return _this.renderer.onWindowResize(window.devicePixelRatio); })); - this.register(Lifecycle_1.addDisposableDomListener(window, 'resize', function () { return _this.renderer.onWindowResize(window.devicePixelRatio); })); - this.register(this.charMeasure.addDisposableListener('charsizechanged', function () { return _this.renderer.onCharSizeChanged(); })); - this.register(this.renderer.addDisposableListener('resize', function (dimensions) { return _this.viewport.syncScrollArea(); })); - this.selectionManager = new SelectionManager_1.SelectionManager(this, this.charMeasure); - this.register(Lifecycle_1.addDisposableDomListener(this.element, 'mousedown', function (e) { return _this.selectionManager.onMouseDown(e); })); - this.register(this.selectionManager.addDisposableListener('refresh', function (data) { return _this.renderer.onSelectionChanged(data.start, data.end, data.columnSelectMode); })); - this.register(this.selectionManager.addDisposableListener('newselection', function (text) { - _this.textarea.value = text; - _this.textarea.focus(); - _this.textarea.select(); - })); - this.register(this.addDisposableListener('scroll', function () { - _this.viewport.syncScrollArea(); - _this.selectionManager.refresh(); - })); - this.register(Lifecycle_1.addDisposableDomListener(this._viewportElement, 'scroll', function () { return _this.selectionManager.refresh(); })); - this.mouseHelper = new MouseHelper_1.MouseHelper(this.renderer); - if (this.options.screenReaderMode) { - this._accessibilityManager = new AccessibilityManager_1.AccessibilityManager(this); - } - this.charMeasure.measure(this.options); - this.refresh(0, this.rows - 1); - this._initGlobal(); - this.bindMouse(); - }; - Terminal.prototype._setupRenderer = function () { - switch (this.options.rendererType) { - case 'canvas': - this.renderer = new Renderer_1.Renderer(this, this.options.theme); - break; - case 'dom': - this.renderer = new DomRenderer_1.DomRenderer(this, this.options.theme); - break; - default: throw new Error("Unrecognized rendererType \"" + this.options.rendererType + "\""); - } - this.register(this.renderer); - }; - Terminal.prototype._setTheme = function (theme) { - this._theme = theme; - var colors = this.renderer.setTheme(theme); - if (this.viewport) { - this.viewport.onThemeChanged(colors); - } - }; - Terminal.prototype.bindMouse = function () { - var _this = this; - var el = this.element; - var self = this; - var pressed = 32; - function sendButton(ev) { - var button; - var pos; - button = getButton(ev); - pos = self.mouseHelper.getRawByteCoords(ev, self.screenElement, self.charMeasure, self.cols, self.rows); - if (!pos) - return; - sendEvent(button, pos); - switch (ev.overrideType || ev.type) { - case 'mousedown': - pressed = button; - break; - case 'mouseup': - pressed = 32; - break; - case 'wheel': - break; - } - } - function sendMove(ev) { - var button = pressed; - var pos = self.mouseHelper.getRawByteCoords(ev, self.screenElement, self.charMeasure, self.cols, self.rows); - if (!pos) - return; - button += 32; - sendEvent(button, pos); - } - function encode(data, ch) { - if (!self.utfMouse) { - if (ch === 255) { - data.push(0); - return; - } - if (ch > 127) - ch = 127; - data.push(ch); - } - else { - if (ch === 2047) { - data.push(0); - return; - } - if (ch < 127) { - data.push(ch); - } - else { - if (ch > 2047) - ch = 2047; - data.push(0xC0 | (ch >> 6)); - data.push(0x80 | (ch & 0x3F)); - } - } - } - function sendEvent(button, pos) { - if (self._vt300Mouse) { - button &= 3; - pos.x -= 32; - pos.y -= 32; - var data_1 = EscapeSequences_1.C0.ESC + '[24'; - if (button === 0) - data_1 += '1'; - else if (button === 1) - data_1 += '3'; - else if (button === 2) - data_1 += '5'; - else if (button === 3) - return; - else - data_1 += '0'; - data_1 += '~[' + pos.x + ',' + pos.y + ']\r'; - self.handler(data_1); - return; - } - if (self._decLocator) { - button &= 3; - pos.x -= 32; - pos.y -= 32; - if (button === 0) - button = 2; - else if (button === 1) - button = 4; - else if (button === 2) - button = 6; - else if (button === 3) - button = 3; - self.handler(EscapeSequences_1.C0.ESC + '[' - + button - + ';' - + (button === 3 ? 4 : 0) - + ';' - + pos.y - + ';' - + pos.x - + ';' - + pos.page || 0 - + '&w'); - return; - } - if (self.urxvtMouse) { - pos.x -= 32; - pos.y -= 32; - pos.x++; - pos.y++; - self.handler(EscapeSequences_1.C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M'); - return; - } - if (self.sgrMouse) { - pos.x -= 32; - pos.y -= 32; - self.handler(EscapeSequences_1.C0.ESC + '[<' - + (((button & 3) === 3 ? button & ~3 : button) - 32) - + ';' - + pos.x - + ';' - + pos.y - + ((button & 3) === 3 ? 'm' : 'M')); - return; - } - var data = []; - encode(data, button); - encode(data, pos.x); - encode(data, pos.y); - self.handler(EscapeSequences_1.C0.ESC + '[M' + String.fromCharCode.apply(String, data)); - } - function getButton(ev) { - var button; - var shift; - var meta; - var ctrl; - var mod; - switch (ev.overrideType || ev.type) { - case 'mousedown': - button = ev.button !== null && ev.button !== undefined - ? +ev.button - : ev.which !== null && ev.which !== undefined - ? ev.which - 1 - : null; - if (Browser.isMSIE) { - button = button === 1 ? 0 : button === 4 ? 1 : button; - } - break; - case 'mouseup': - button = 3; - break; - case 'DOMMouseScroll': - button = ev.detail < 0 - ? 64 - : 65; - break; - case 'wheel': - button = ev.deltaY < 0 - ? 64 - : 65; - break; - } - shift = ev.shiftKey ? 4 : 0; - meta = ev.metaKey ? 8 : 0; - ctrl = ev.ctrlKey ? 16 : 0; - mod = shift | meta | ctrl; - if (self.vt200Mouse) { - mod &= ctrl; - } - else if (!self.normalMouse) { - mod = 0; - } - button = (32 + (mod << 2)) + button; - return button; - } - this.register(Lifecycle_1.addDisposableDomListener(el, 'mousedown', function (ev) { - ev.preventDefault(); - _this.focus(); - if (!_this.mouseEvents || _this.selectionManager.shouldForceSelection(ev)) { - return; - } - sendButton(ev); - if (_this.vt200Mouse) { - ev.overrideType = 'mouseup'; - sendButton(ev); - return _this.cancel(ev); - } - var moveHandler; - if (_this.normalMouse) { - moveHandler = function (event) { - if (!_this.normalMouse) { - return; - } - sendMove(event); - }; - _this._document.addEventListener('mousemove', moveHandler); - } - var handler = function (ev) { - if (_this.normalMouse && !_this.x10Mouse) { - sendButton(ev); - } - if (moveHandler) { - _this._document.removeEventListener('mousemove', moveHandler); - moveHandler = null; - } - _this._document.removeEventListener('mouseup', handler); - return _this.cancel(ev); - }; - _this._document.addEventListener('mouseup', handler); - return _this.cancel(ev); - })); - this.register(Lifecycle_1.addDisposableDomListener(el, 'wheel', function (ev) { - if (!_this.mouseEvents) { - if (!_this.buffer.hasScrollback) { - var amount = _this.viewport.getLinesScrolled(ev); - if (amount === 0) { - return; - } - var sequence = EscapeSequences_1.C0.ESC + (_this.applicationCursor ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B'); - var data = ''; - for (var i = 0; i < Math.abs(amount); i++) { - data += sequence; - } - _this.handler(data); - } - return; - } - if (_this.x10Mouse || _this._vt300Mouse || _this._decLocator) - return; - sendButton(ev); - ev.preventDefault(); - })); - this.register(Lifecycle_1.addDisposableDomListener(el, 'wheel', function (ev) { - if (_this.mouseEvents) - return; - _this.viewport.onWheel(ev); - return _this.cancel(ev); - })); - this.register(Lifecycle_1.addDisposableDomListener(el, 'touchstart', function (ev) { - if (_this.mouseEvents) - return; - _this.viewport.onTouchStart(ev); - return _this.cancel(ev); - })); - this.register(Lifecycle_1.addDisposableDomListener(el, 'touchmove', function (ev) { - if (_this.mouseEvents) - return; - _this.viewport.onTouchMove(ev); - return _this.cancel(ev); - })); - }; - Terminal.prototype.refresh = function (start, end) { - if (this.renderer) { - this.renderer.refreshRows(start, end); - } - }; - Terminal.prototype._queueLinkification = function (start, end) { - if (this.linkifier) { - this.linkifier.linkifyRows(start, end); - } - }; - Terminal.prototype.updateCursorStyle = function (ev) { - if (this.selectionManager && this.selectionManager.shouldColumnSelect(ev)) { - this.element.classList.add('column-select'); - } - else { - this.element.classList.remove('column-select'); - } - }; - Terminal.prototype.showCursor = function () { - if (!this.cursorState) { - this.cursorState = 1; - this.refresh(this.buffer.y, this.buffer.y); - } - }; - Terminal.prototype.scroll = function (isWrapped) { - if (isWrapped === void 0) { isWrapped = false; } - var newLine; - var useRecycling = this.options.experimentalBufferLineImpl !== 'JsArray'; - if (useRecycling) { - newLine = this._blankLine; - if (!newLine || newLine.length !== this.cols || newLine.get(0)[Buffer_1.CHAR_DATA_ATTR_INDEX] !== this.eraseAttr()) { - newLine = this.buffer.getBlankLine(this.eraseAttr(), isWrapped); - this._blankLine = newLine; - } - newLine.isWrapped = isWrapped; - } - else { - newLine = this.buffer.getBlankLine(this.eraseAttr(), isWrapped); - } - var topRow = this.buffer.ybase + this.buffer.scrollTop; - var bottomRow = this.buffer.ybase + this.buffer.scrollBottom; - if (this.buffer.scrollTop === 0) { - var willBufferBeTrimmed = this.buffer.lines.isFull; - if (bottomRow === this.buffer.lines.length - 1) { - if (useRecycling) { - if (willBufferBeTrimmed) { - this.buffer.lines.recycle().copyFrom(newLine); - } - else { - this.buffer.lines.push(newLine.clone()); - } - } - else { - this.buffer.lines.push(newLine); - } - } - else { - this.buffer.lines.splice(bottomRow + 1, 0, (useRecycling) ? newLine.clone() : newLine); - } - if (!willBufferBeTrimmed) { - this.buffer.ybase++; - if (!this._userScrolling) { - this.buffer.ydisp++; - } - } - else { - if (this._userScrolling) { - this.buffer.ydisp = Math.max(this.buffer.ydisp - 1, 0); - } - } - } - else { - var scrollRegionHeight = bottomRow - topRow + 1; - this.buffer.lines.shiftElements(topRow + 1, scrollRegionHeight - 1, -1); - this.buffer.lines.set(bottomRow, (useRecycling) ? newLine.clone() : newLine); - } - if (!this._userScrolling) { - this.buffer.ydisp = this.buffer.ybase; - } - this.updateRange(this.buffer.scrollTop); - this.updateRange(this.buffer.scrollBottom); - this.emit('scroll', this.buffer.ydisp); - }; - Terminal.prototype.scrollLines = function (disp, suppressScrollEvent) { - if (disp < 0) { - if (this.buffer.ydisp === 0) { - return; - } - this._userScrolling = true; - } - else if (disp + this.buffer.ydisp >= this.buffer.ybase) { - this._userScrolling = false; - } - var oldYdisp = this.buffer.ydisp; - this.buffer.ydisp = Math.max(Math.min(this.buffer.ydisp + disp, this.buffer.ybase), 0); - if (oldYdisp === this.buffer.ydisp) { - return; - } - if (!suppressScrollEvent) { - this.emit('scroll', this.buffer.ydisp); - } - this.refresh(0, this.rows - 1); - }; - Terminal.prototype.scrollPages = function (pageCount) { - this.scrollLines(pageCount * (this.rows - 1)); - }; - Terminal.prototype.scrollToTop = function () { - this.scrollLines(-this.buffer.ydisp); - }; - Terminal.prototype.scrollToBottom = function () { - this.scrollLines(this.buffer.ybase - this.buffer.ydisp); - }; - Terminal.prototype.scrollToLine = function (line) { - var scrollAmount = line - this.buffer.ydisp; - if (scrollAmount !== 0) { - this.scrollLines(scrollAmount); - } - }; - Terminal.prototype.write = function (data) { - var _this = this; - if (this._isDisposed) { - return; - } - if (!data) { - return; - } - this.writeBuffer.push(data); - if (this.options.useFlowControl && !this._xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) { - this.handler(EscapeSequences_1.C0.DC3); - this._xoffSentToCatchUp = true; - } - if (!this._writeInProgress && this.writeBuffer.length > 0) { - this._writeInProgress = true; - setTimeout(function () { - _this._innerWrite(); - }); - } - }; - Terminal.prototype._innerWrite = function () { - var _this = this; - if (this._isDisposed) { - this.writeBuffer = []; - } - var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE); - while (writeBatch.length > 0) { - var data = writeBatch.shift(); - if (this._xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) { - this.handler(EscapeSequences_1.C0.DC1); - this._xoffSentToCatchUp = false; - } - this._refreshStart = this.buffer.y; - this._refreshEnd = this.buffer.y; - this._inputHandler.parse(data); - this.updateRange(this.buffer.y); - this.refresh(this._refreshStart, this._refreshEnd); - } - if (this.writeBuffer.length > 0) { - setTimeout(function () { return _this._innerWrite(); }, 0); - } - else { - this._writeInProgress = false; - } - }; - Terminal.prototype.writeln = function (data) { - this.write(data + '\r\n'); - }; - Terminal.prototype.attachCustomKeyEventHandler = function (customKeyEventHandler) { - this._customKeyEventHandler = customKeyEventHandler; - }; - Terminal.prototype.registerLinkMatcher = function (regex, handler, options) { - var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options); - this.refresh(0, this.rows - 1); - return matcherId; - }; - Terminal.prototype.deregisterLinkMatcher = function (matcherId) { - if (this.linkifier.deregisterLinkMatcher(matcherId)) { - this.refresh(0, this.rows - 1); - } - }; - Terminal.prototype.registerCharacterJoiner = function (handler) { - var joinerId = this.renderer.registerCharacterJoiner(handler); - this.refresh(0, this.rows - 1); - return joinerId; - }; - Terminal.prototype.deregisterCharacterJoiner = function (joinerId) { - if (this.renderer.deregisterCharacterJoiner(joinerId)) { - this.refresh(0, this.rows - 1); - } - }; - Object.defineProperty(Terminal.prototype, "markers", { - get: function () { - return this.buffer.markers; - }, - enumerable: true, - configurable: true - }); - Terminal.prototype.addMarker = function (cursorYOffset) { - if (this.buffer !== this.buffers.normal) { - return; - } - return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset); - }; - Terminal.prototype.hasSelection = function () { - return this.selectionManager ? this.selectionManager.hasSelection : false; - }; - Terminal.prototype.getSelection = function () { - return this.selectionManager ? this.selectionManager.selectionText : ''; - }; - Terminal.prototype.clearSelection = function () { - if (this.selectionManager) { - this.selectionManager.clearSelection(); - } - }; - Terminal.prototype.selectAll = function () { - if (this.selectionManager) { - this.selectionManager.selectAll(); - } - }; - Terminal.prototype.selectLines = function (start, end) { - if (this.selectionManager) { - this.selectionManager.selectLines(start, end); - } - }; - Terminal.prototype._keyDown = function (event) { - if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) { - return false; - } - if (!this._compositionHelper.keydown(event)) { - if (this.buffer.ybase !== this.buffer.ydisp) { - this.scrollToBottom(); - } - return false; - } - var result = Keyboard_1.evaluateKeyboardEvent(event, this.applicationCursor, this.browser.isMac, this.options.macOptionIsMeta); - this.updateCursorStyle(event); - if (result.type === 3 || result.type === 2) { - var scrollCount = this.rows - 1; - this.scrollLines(result.type === 2 ? -scrollCount : scrollCount); - return this.cancel(event, true); - } - if (result.type === 1) { - this.selectAll(); - } - if (this._isThirdLevelShift(this.browser, event)) { - return true; - } - if (result.cancel) { - this.cancel(event, true); - } - if (!result.key) { - return true; - } - this.emit('keydown', event); - this.emit('key', result.key, event); - this.showCursor(); - this.handler(result.key); - return this.cancel(event, true); - }; - Terminal.prototype._isThirdLevelShift = function (browser, ev) { - var thirdLevelKey = (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) || - (browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey); - if (ev.type === 'keypress') { - return thirdLevelKey; - } - return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47); - }; - Terminal.prototype.setgLevel = function (g) { - this.glevel = g; - this.charset = this.charsets[g]; - }; - Terminal.prototype.setgCharset = function (g, charset) { - this.charsets[g] = charset; - if (this.glevel === g) { - this.charset = charset; - } - }; - Terminal.prototype._keyUp = function (ev) { - this.updateCursorStyle(ev); - }; - Terminal.prototype._keyPress = function (ev) { - var key; - if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) { - return false; - } - this.cancel(ev); - if (ev.charCode) { - key = ev.charCode; - } - else if (ev.which === null || ev.which === undefined) { - key = ev.keyCode; - } - else if (ev.which !== 0 && ev.charCode !== 0) { - key = ev.which; - } - else { - return false; - } - if (!key || ((ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev))) { - return false; - } - key = String.fromCharCode(key); - this.emit('keypress', key, ev); - this.emit('key', key, ev); - this.showCursor(); - this.handler(key); - return true; - }; - Terminal.prototype.bell = function () { - var _this = this; - this.emit('bell'); - if (this._soundBell()) { - this.soundManager.playBellSound(); - } - if (this._visualBell()) { - this.element.classList.add('visual-bell-active'); - clearTimeout(this._visualBellTimer); - this._visualBellTimer = window.setTimeout(function () { - _this.element.classList.remove('visual-bell-active'); - }, 200); - } - }; - Terminal.prototype.log = function (text, data) { - if (!this.options.debug) - return; - if (!this._context.console || !this._context.console.log) - return; - this._context.console.log(text, data); - }; - Terminal.prototype.error = function (text, data) { - if (!this.options.debug) - return; - if (!this._context.console || !this._context.console.error) - return; - this._context.console.error(text, data); - }; - Terminal.prototype.resize = function (x, y) { - if (isNaN(x) || isNaN(y)) { - return; - } - if (x === this.cols && y === this.rows) { - if (this.charMeasure && (!this.charMeasure.width || !this.charMeasure.height)) { - this.charMeasure.measure(this.options); - } - return; - } - if (x < 1) - x = 1; - if (y < 1) - y = 1; - this.buffers.resize(x, y); - this.cols = x; - this.rows = y; - this.buffers.setupTabStops(this.cols); - if (this.charMeasure) { - this.charMeasure.measure(this.options); - } - this.refresh(0, this.rows - 1); - this.emit('resize', { cols: x, rows: y }); - }; - Terminal.prototype.updateRange = function (y) { - if (y < this._refreshStart) - this._refreshStart = y; - if (y > this._refreshEnd) - this._refreshEnd = y; - }; - Terminal.prototype.maxRange = function () { - this._refreshStart = 0; - this._refreshEnd = this.rows - 1; - }; - Terminal.prototype.clear = function () { - if (this.buffer.ybase === 0 && this.buffer.y === 0) { - return; - } - this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)); - this.buffer.lines.length = 1; - this.buffer.ydisp = 0; - this.buffer.ybase = 0; - this.buffer.y = 0; - for (var i = 1; i < this.rows; i++) { - this.buffer.lines.push(this.buffer.getBlankLine(Buffer_1.DEFAULT_ATTR)); - } - this.refresh(0, this.rows - 1); - this.emit('scroll', this.buffer.ydisp); - }; - Terminal.prototype.ch = function (cur) { - if (cur) { - return [this.eraseAttr(), Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]; - } - return [Buffer_1.DEFAULT_ATTR, Buffer_1.NULL_CELL_CHAR, Buffer_1.NULL_CELL_WIDTH, Buffer_1.NULL_CELL_CODE]; - }; - Terminal.prototype.is = function (term) { - return (this.options.termName + '').indexOf(term) === 0; - }; - Terminal.prototype.handler = function (data) { - if (this.options.disableStdin) { - return; - } - if (this.selectionManager && this.selectionManager.hasSelection) { - this.selectionManager.clearSelection(); - } - if (this.buffer.ybase !== this.buffer.ydisp) { - this.scrollToBottom(); - } - this.emit('data', data); - }; - Terminal.prototype.handleTitle = function (title) { - this.emit('title', title); - }; - Terminal.prototype.index = function () { - this.buffer.y++; - if (this.buffer.y > this.buffer.scrollBottom) { - this.buffer.y--; - this.scroll(); - } - if (this.buffer.x >= this.cols) { - this.buffer.x--; - } - }; - Terminal.prototype.reverseIndex = function () { - if (this.buffer.y === this.buffer.scrollTop) { - var scrollRegionHeight = this.buffer.scrollBottom - this.buffer.scrollTop; - this.buffer.lines.shiftElements(this.buffer.y + this.buffer.ybase, scrollRegionHeight, 1); - this.buffer.lines.set(this.buffer.y + this.buffer.ybase, this.buffer.getBlankLine(this.eraseAttr())); - this.updateRange(this.buffer.scrollTop); - this.updateRange(this.buffer.scrollBottom); - } - else { - this.buffer.y--; - } - }; - Terminal.prototype.reset = function () { - this.options.rows = this.rows; - this.options.cols = this.cols; - var customKeyEventHandler = this._customKeyEventHandler; - var inputHandler = this._inputHandler; - var cursorState = this.cursorState; - this._setup(); - this._customKeyEventHandler = customKeyEventHandler; - this._inputHandler = inputHandler; - this.cursorState = cursorState; - this.refresh(0, this.rows - 1); - if (this.viewport) { - this.viewport.syncScrollArea(); - } - }; - Terminal.prototype.tabSet = function () { - this.buffer.tabs[this.buffer.x] = true; - }; - Terminal.prototype.cancel = function (ev, force) { - if (!this.options.cancelEvents && !force) { - return; - } - ev.preventDefault(); - ev.stopPropagation(); - return false; - }; - Terminal.prototype.matchColor = function (r1, g1, b1) { - var hash = (r1 << 16) | (g1 << 8) | b1; - if (matchColorCache[hash] !== null && matchColorCache[hash] !== undefined) { - return matchColorCache[hash]; - } - var ldiff = Infinity; - var li = -1; - var i = 0; - var c; - var r2; - var g2; - var b2; - var diff; - for (; i < ColorManager_1.DEFAULT_ANSI_COLORS.length; i++) { - c = ColorManager_1.DEFAULT_ANSI_COLORS[i].rgba; - r2 = c >>> 24; - g2 = c >>> 16 & 0xFF; - b2 = c >>> 8 & 0xFF; - diff = matchColorDistance(r1, g1, b1, r2, g2, b2); - if (diff === 0) { - li = i; - break; - } - if (diff < ldiff) { - ldiff = diff; - li = i; - } - } - return matchColorCache[hash] = li; - }; - Terminal.prototype._visualBell = function () { - return false; - }; - Terminal.prototype._soundBell = function () { - return this.options.bellStyle === 'sound'; - }; - return Terminal; -}(EventEmitter_1.EventEmitter)); -exports.Terminal = Terminal; -function wasModifierKeyOnlyEvent(ev) { - return ev.keyCode === 16 || - ev.keyCode === 17 || - ev.keyCode === 18; -} -var matchColorCache = {}; -function matchColorDistance(r1, g1, b1, r2, g2, b2) { - return Math.pow(30 * (r1 - r2), 2) - + Math.pow(59 * (g1 - g2), 2) - + Math.pow(11 * (b1 - b2), 2); -} - -},{"./AccessibilityManager":1,"./Buffer":2,"./BufferSet":4,"./CompositionHelper":6,"./InputHandler":8,"./Linkifier":9,"./SelectionManager":10,"./SoundManager":12,"./Strings":13,"./Viewport":15,"./common/EventEmitter":17,"./common/data/EscapeSequences":20,"./core/Platform":21,"./core/input/Keyboard":23,"./renderer/ColorManager":28,"./renderer/Renderer":32,"./renderer/atlas/CharAtlasCache":36,"./renderer/dom/DomRenderer":44,"./ui/CharMeasure":46,"./ui/Clipboard":47,"./ui/Lifecycle":48,"./ui/MouseZoneManager":49,"./ui/ScreenDprMonitor":51,"./utils/Clone":52,"./utils/MouseHelper":53}],15:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Lifecycle_1 = require("./common/Lifecycle"); -var Lifecycle_2 = require("./ui/Lifecycle"); -var FALLBACK_SCROLL_BAR_WIDTH = 15; -var Viewport = (function (_super) { - __extends(Viewport, _super); - function Viewport(_terminal, _viewportElement, _scrollArea, _charMeasure) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._viewportElement = _viewportElement; - _this._scrollArea = _scrollArea; - _this._charMeasure = _charMeasure; - _this.scrollBarWidth = 0; - _this._currentRowHeight = 0; - _this._lastRecordedBufferLength = 0; - _this._lastRecordedViewportHeight = 0; - _this._lastRecordedBufferHeight = 0; - _this._lastScrollTop = 0; - _this._wheelPartialScroll = 0; - _this._refreshAnimationFrame = null; - _this._ignoreNextScrollEvent = false; - _this.scrollBarWidth = (_this._viewportElement.offsetWidth - _this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH; - _this.register(Lifecycle_2.addDisposableDomListener(_this._viewportElement, 'scroll', _this._onScroll.bind(_this))); - setTimeout(function () { return _this.syncScrollArea(); }, 0); - return _this; - } - Viewport.prototype.onThemeChanged = function (colors) { - this._viewportElement.style.backgroundColor = colors.background.css; - }; - Viewport.prototype._refresh = function () { - var _this = this; - if (this._refreshAnimationFrame === null) { - this._refreshAnimationFrame = requestAnimationFrame(function () { return _this._innerRefresh(); }); - } - }; - Viewport.prototype._innerRefresh = function () { - if (this._charMeasure.height > 0) { - this._currentRowHeight = this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio; - this._lastRecordedViewportHeight = this._viewportElement.offsetHeight; - var newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._terminal.renderer.dimensions.canvasHeight); - if (this._lastRecordedBufferHeight !== newBufferHeight) { - this._lastRecordedBufferHeight = newBufferHeight; - this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px'; - } - } - var scrollTop = this._terminal.buffer.ydisp * this._currentRowHeight; - if (this._viewportElement.scrollTop !== scrollTop) { - this._ignoreNextScrollEvent = true; - this._viewportElement.scrollTop = scrollTop; - } - this._refreshAnimationFrame = null; - }; - Viewport.prototype.syncScrollArea = function () { - if (this._lastRecordedBufferLength !== this._terminal.buffer.lines.length) { - this._lastRecordedBufferLength = this._terminal.buffer.lines.length; - this._refresh(); - return; - } - if (this._lastRecordedViewportHeight !== this._terminal.renderer.dimensions.canvasHeight) { - this._refresh(); - return; - } - var newScrollTop = this._terminal.buffer.ydisp * this._currentRowHeight; - if (this._lastScrollTop !== newScrollTop) { - this._refresh(); - return; - } - if (this._lastScrollTop !== this._viewportElement.scrollTop) { - this._refresh(); - return; - } - if (this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) { - this._refresh(); - return; - } - }; - Viewport.prototype._onScroll = function (ev) { - this._lastScrollTop = this._viewportElement.scrollTop; - if (!this._viewportElement.offsetParent) { - return; - } - if (this._ignoreNextScrollEvent) { - this._ignoreNextScrollEvent = false; - return; - } - var newRow = Math.round(this._lastScrollTop / this._currentRowHeight); - var diff = newRow - this._terminal.buffer.ydisp; - this._terminal.scrollLines(diff, true); - }; - Viewport.prototype.onWheel = function (ev) { - var amount = this._getPixelsScrolled(ev); - if (amount === 0) { - return; - } - this._viewportElement.scrollTop += amount; - ev.preventDefault(); - }; - Viewport.prototype._getPixelsScrolled = function (ev) { - if (ev.deltaY === 0) { - return 0; - } - var amount = ev.deltaY; - if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) { - amount *= this._currentRowHeight; - } - else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) { - amount *= this._currentRowHeight * this._terminal.rows; - } - return amount; - }; - Viewport.prototype.getLinesScrolled = function (ev) { - if (ev.deltaY === 0) { - return 0; - } - var amount = ev.deltaY; - if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) { - amount /= this._currentRowHeight + 0.0; - this._wheelPartialScroll += amount; - amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1); - this._wheelPartialScroll %= 1; - } - else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) { - amount *= this._terminal.rows; - } - return amount; - }; - Viewport.prototype.onTouchStart = function (ev) { - this._lastTouchY = ev.touches[0].pageY; - }; - Viewport.prototype.onTouchMove = function (ev) { - var deltaY = this._lastTouchY - ev.touches[0].pageY; - this._lastTouchY = ev.touches[0].pageY; - if (deltaY === 0) { - return; - } - this._viewportElement.scrollTop += deltaY; - ev.preventDefault(); - }; - return Viewport; -}(Lifecycle_1.Disposable)); -exports.Viewport = Viewport; - -},{"./common/Lifecycle":18,"./ui/Lifecycle":48}],16:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var EventEmitter_1 = require("./EventEmitter"); -var CircularList = (function (_super) { - __extends(CircularList, _super); - function CircularList(_maxLength) { - var _this = _super.call(this) || this; - _this._maxLength = _maxLength; - _this._array = new Array(_this._maxLength); - _this._startIndex = 0; - _this._length = 0; - return _this; - } - Object.defineProperty(CircularList.prototype, "maxLength", { - get: function () { - return this._maxLength; - }, - set: function (newMaxLength) { - if (this._maxLength === newMaxLength) { - return; - } - var newArray = new Array(newMaxLength); - for (var i = 0; i < Math.min(newMaxLength, this.length); i++) { - newArray[i] = this._array[this._getCyclicIndex(i)]; - } - this._array = newArray; - this._maxLength = newMaxLength; - this._startIndex = 0; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CircularList.prototype, "length", { - get: function () { - return this._length; - }, - set: function (newLength) { - if (newLength > this._length) { - for (var i = this._length; i < newLength; i++) { - this._array[i] = undefined; - } - } - this._length = newLength; - }, - enumerable: true, - configurable: true - }); - CircularList.prototype.get = function (index) { - return this._array[this._getCyclicIndex(index)]; - }; - CircularList.prototype.set = function (index, value) { - this._array[this._getCyclicIndex(index)] = value; - }; - CircularList.prototype.push = function (value) { - this._array[this._getCyclicIndex(this._length)] = value; - if (this._length === this._maxLength) { - this._startIndex = ++this._startIndex % this._maxLength; - this.emit('trim', 1); - } - else { - this._length++; - } - }; - CircularList.prototype.recycle = function () { - if (this._length !== this._maxLength) { - throw new Error('Can only recycle when the buffer is full'); - } - this._startIndex = ++this._startIndex % this._maxLength; - this.emit('trim', 1); - return this._array[this._getCyclicIndex(this._length - 1)]; - }; - Object.defineProperty(CircularList.prototype, "isFull", { - get: function () { - return this._length === this._maxLength; - }, - enumerable: true, - configurable: true - }); - CircularList.prototype.pop = function () { - return this._array[this._getCyclicIndex(this._length-- - 1)]; - }; - CircularList.prototype.splice = function (start, deleteCount) { - var items = []; - for (var _i = 2; _i < arguments.length; _i++) { - items[_i - 2] = arguments[_i]; - } - if (deleteCount) { - for (var i = start; i < this._length - deleteCount; i++) { - this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)]; - } - this._length -= deleteCount; - } - if (items && items.length) { - for (var i = this._length - 1; i >= start; i--) { - this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)]; - } - for (var i = 0; i < items.length; i++) { - this._array[this._getCyclicIndex(start + i)] = items[i]; - } - if (this._length + items.length > this._maxLength) { - var countToTrim = (this._length + items.length) - this._maxLength; - this._startIndex += countToTrim; - this._length = this._maxLength; - this.emit('trim', countToTrim); - } - else { - this._length += items.length; - } - } - }; - CircularList.prototype.trimStart = function (count) { - if (count > this._length) { - count = this._length; - } - this._startIndex += count; - this._length -= count; - this.emit('trim', count); - }; - CircularList.prototype.shiftElements = function (start, count, offset) { - if (count <= 0) { - return; - } - if (start < 0 || start >= this._length) { - throw new Error('start argument out of range'); - } - if (start + offset < 0) { - throw new Error('Cannot shift elements in list beyond index 0'); - } - if (offset > 0) { - for (var i = count - 1; i >= 0; i--) { - this.set(start + i + offset, this.get(start + i)); - } - var expandListBy = (start + count + offset) - this._length; - if (expandListBy > 0) { - this._length += expandListBy; - while (this._length > this._maxLength) { - this._length--; - this._startIndex++; - this.emit('trim', 1); - } - } - } - else { - for (var i = 0; i < count; i++) { - this.set(start + i + offset, this.get(start + i)); - } - } - }; - CircularList.prototype._getCyclicIndex = function (index) { - return (this._startIndex + index) % this._maxLength; - }; - return CircularList; -}(EventEmitter_1.EventEmitter)); -exports.CircularList = CircularList; - -},{"./EventEmitter":17}],17:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Lifecycle_1 = require("./Lifecycle"); -var EventEmitter = (function (_super) { - __extends(EventEmitter, _super); - function EventEmitter() { - var _this = _super.call(this) || this; - _this._events = _this._events || {}; - return _this; - } - EventEmitter.prototype.on = function (type, listener) { - this._events[type] = this._events[type] || []; - this._events[type].push(listener); - }; - EventEmitter.prototype.addDisposableListener = function (type, handler) { - var _this = this; - this.on(type, handler); - var disposed = false; - return { - dispose: function () { - if (disposed) { - return; - } - _this.off(type, handler); - disposed = true; - } - }; - }; - EventEmitter.prototype.off = function (type, listener) { - if (!this._events[type]) { - return; - } - var obj = this._events[type]; - var i = obj.length; - while (i--) { - if (obj[i] === listener) { - obj.splice(i, 1); - return; - } - } - }; - EventEmitter.prototype.removeAllListeners = function (type) { - if (this._events[type]) { - delete this._events[type]; - } - }; - EventEmitter.prototype.emit = function (type) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - if (!this._events[type]) { - return; - } - var obj = this._events[type]; - for (var i = 0; i < obj.length; i++) { - obj[i].apply(this, args); - } - }; - EventEmitter.prototype.listeners = function (type) { - return this._events[type] || []; - }; - EventEmitter.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._events = {}; - }; - return EventEmitter; -}(Lifecycle_1.Disposable)); -exports.EventEmitter = EventEmitter; - -},{"./Lifecycle":18}],18:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Disposable = (function () { - function Disposable() { - this._disposables = []; - this._isDisposed = false; - } - Disposable.prototype.dispose = function () { - this._isDisposed = true; - this._disposables.forEach(function (d) { return d.dispose(); }); - this._disposables.length = 0; - }; - Disposable.prototype.register = function (d) { - this._disposables.push(d); - }; - Disposable.prototype.unregister = function (d) { - var index = this._disposables.indexOf(d); - if (index !== -1) { - this._disposables.splice(index, 1); - } - }; - return Disposable; -}()); -exports.Disposable = Disposable; - -},{}],19:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function fill(array, value, start, end) { - if (array.fill) { - return array.fill(value, start, end); - } - return fillFallback(array, value, start, end); -} -exports.fill = fill; -function fillFallback(array, value, start, end) { - if (start === void 0) { start = 0; } - if (end === void 0) { end = array.length; } - if (start >= array.length) { - return array; - } - start = (array.length + start) % array.length; - if (end >= array.length) { - end = array.length; - } - else { - end = (array.length + end) % array.length; - } - for (var i = start; i < end; ++i) { - array[i] = value; - } - return array; -} -exports.fillFallback = fillFallback; - -},{}],20:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var C0; -(function (C0) { - C0.NUL = '\x00'; - C0.SOH = '\x01'; - C0.STX = '\x02'; - C0.ETX = '\x03'; - C0.EOT = '\x04'; - C0.ENQ = '\x05'; - C0.ACK = '\x06'; - C0.BEL = '\x07'; - C0.BS = '\x08'; - C0.HT = '\x09'; - C0.LF = '\x0a'; - C0.VT = '\x0b'; - C0.FF = '\x0c'; - C0.CR = '\x0d'; - C0.SO = '\x0e'; - C0.SI = '\x0f'; - C0.DLE = '\x10'; - C0.DC1 = '\x11'; - C0.DC2 = '\x12'; - C0.DC3 = '\x13'; - C0.DC4 = '\x14'; - C0.NAK = '\x15'; - C0.SYN = '\x16'; - C0.ETB = '\x17'; - C0.CAN = '\x18'; - C0.EM = '\x19'; - C0.SUB = '\x1a'; - C0.ESC = '\x1b'; - C0.FS = '\x1c'; - C0.GS = '\x1d'; - C0.RS = '\x1e'; - C0.US = '\x1f'; - C0.SP = '\x20'; - C0.DEL = '\x7f'; -})(C0 = exports.C0 || (exports.C0 = {})); -var C1; -(function (C1) { - C1.PAD = '\x80'; - C1.HOP = '\x81'; - C1.BPH = '\x82'; - C1.NBH = '\x83'; - C1.IND = '\x84'; - C1.NEL = '\x85'; - C1.SSA = '\x86'; - C1.ESA = '\x87'; - C1.HTS = '\x88'; - C1.HTJ = '\x89'; - C1.VTS = '\x8a'; - C1.PLD = '\x8b'; - C1.PLU = '\x8c'; - C1.RI = '\x8d'; - C1.SS2 = '\x8e'; - C1.SS3 = '\x8f'; - C1.DCS = '\x90'; - C1.PU1 = '\x91'; - C1.PU2 = '\x92'; - C1.STS = '\x93'; - C1.CCH = '\x94'; - C1.MW = '\x95'; - C1.SPA = '\x96'; - C1.EPA = '\x97'; - C1.SOS = '\x98'; - C1.SGCI = '\x99'; - C1.SCI = '\x9a'; - C1.CSI = '\x9b'; - C1.ST = '\x9c'; - C1.OSC = '\x9d'; - C1.PM = '\x9e'; - C1.APC = '\x9f'; -})(C1 = exports.C1 || (exports.C1 = {})); - -},{}],21:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var isNode = (typeof navigator === 'undefined') ? true : false; -var userAgent = (isNode) ? 'node' : navigator.userAgent; -var platform = (isNode) ? 'node' : navigator.platform; -exports.isFirefox = !!~userAgent.indexOf('Firefox'); -exports.isSafari = /^((?!chrome|android).)*safari/i.test(userAgent); -exports.isMSIE = !!~userAgent.indexOf('MSIE') || !!~userAgent.indexOf('Trident'); -exports.isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform); -exports.isIpad = platform === 'iPad'; -exports.isIphone = platform === 'iPhone'; -exports.isMSWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform); -exports.isLinux = platform.indexOf('Linux') >= 0; -function contains(arr, el) { - return arr.indexOf(el) >= 0; -} - -},{}],22:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CHARSETS = {}; -exports.DEFAULT_CHARSET = exports.CHARSETS['B']; -exports.CHARSETS['0'] = { - '`': '\u25c6', - 'a': '\u2592', - 'b': '\u0009', - 'c': '\u000c', - 'd': '\u000d', - 'e': '\u000a', - 'f': '\u00b0', - 'g': '\u00b1', - 'h': '\u2424', - 'i': '\u000b', - 'j': '\u2518', - 'k': '\u2510', - 'l': '\u250c', - 'm': '\u2514', - 'n': '\u253c', - 'o': '\u23ba', - 'p': '\u23bb', - 'q': '\u2500', - 'r': '\u23bc', - 's': '\u23bd', - 't': '\u251c', - 'u': '\u2524', - 'v': '\u2534', - 'w': '\u252c', - 'x': '\u2502', - 'y': '\u2264', - 'z': '\u2265', - '{': '\u03c0', - '|': '\u2260', - '}': '\u00a3', - '~': '\u00b7' -}; -exports.CHARSETS['A'] = { - '#': '£' -}; -exports.CHARSETS['B'] = null; -exports.CHARSETS['4'] = { - '#': '£', - '@': '¾', - '[': 'ij', - '\\': '½', - ']': '|', - '{': '¨', - '|': 'f', - '}': '¼', - '~': '´' -}; -exports.CHARSETS['C'] = - exports.CHARSETS['5'] = { - '[': 'Ä', - '\\': 'Ö', - ']': 'Å', - '^': 'Ü', - '`': 'é', - '{': 'ä', - '|': 'ö', - '}': 'å', - '~': 'ü' - }; -exports.CHARSETS['R'] = { - '#': '£', - '@': 'à', - '[': '°', - '\\': 'ç', - ']': '§', - '{': 'é', - '|': 'ù', - '}': 'è', - '~': '¨' -}; -exports.CHARSETS['Q'] = { - '@': 'à', - '[': 'â', - '\\': 'ç', - ']': 'ê', - '^': 'î', - '`': 'ô', - '{': 'é', - '|': 'ù', - '}': 'è', - '~': 'û' -}; -exports.CHARSETS['K'] = { - '@': '§', - '[': 'Ä', - '\\': 'Ö', - ']': 'Ü', - '{': 'ä', - '|': 'ö', - '}': 'ü', - '~': 'ß' -}; -exports.CHARSETS['Y'] = { - '#': '£', - '@': '§', - '[': '°', - '\\': 'ç', - ']': 'é', - '`': 'ù', - '{': 'à', - '|': 'ò', - '}': 'è', - '~': 'ì' -}; -exports.CHARSETS['E'] = - exports.CHARSETS['6'] = { - '@': 'Ä', - '[': 'Æ', - '\\': 'Ø', - ']': 'Å', - '^': 'Ü', - '`': 'ä', - '{': 'æ', - '|': 'ø', - '}': 'å', - '~': 'ü' - }; -exports.CHARSETS['Z'] = { - '#': '£', - '@': '§', - '[': '¡', - '\\': 'Ñ', - ']': '¿', - '{': '°', - '|': 'ñ', - '}': 'ç' -}; -exports.CHARSETS['H'] = - exports.CHARSETS['7'] = { - '@': 'É', - '[': 'Ä', - '\\': 'Ö', - ']': 'Å', - '^': 'Ü', - '`': 'é', - '{': 'ä', - '|': 'ö', - '}': 'å', - '~': 'ü' - }; -exports.CHARSETS['='] = { - '#': 'ù', - '@': 'à', - '[': 'é', - '\\': 'ç', - ']': 'ê', - '^': 'î', - '_': 'è', - '`': 'ô', - '{': 'ä', - '|': 'ö', - '}': 'ü', - '~': 'û' -}; - -},{}],23:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var EscapeSequences_1 = require("../../common/data/EscapeSequences"); -var KEYCODE_KEY_MAPPINGS = { - 48: ['0', ')'], - 49: ['1', '!'], - 50: ['2', '@'], - 51: ['3', '#'], - 52: ['4', '$'], - 53: ['5', '%'], - 54: ['6', '^'], - 55: ['7', '&'], - 56: ['8', '*'], - 57: ['9', '('], - 186: [';', ':'], - 187: ['=', '+'], - 188: [',', '<'], - 189: ['-', '_'], - 190: ['.', '>'], - 191: ['/', '?'], - 192: ['`', '~'], - 219: ['[', '{'], - 220: ['\\', '|'], - 221: [']', '}'], - 222: ['\'', '"'] -}; -function evaluateKeyboardEvent(ev, applicationCursorMode, isMac, macOptionIsMeta) { - var result = { - type: 0, - cancel: false, - key: undefined - }; - var modifiers = (ev.shiftKey ? 1 : 0) | (ev.altKey ? 2 : 0) | (ev.ctrlKey ? 4 : 0) | (ev.metaKey ? 8 : 0); - switch (ev.keyCode) { - case 0: - if (ev.key === 'UIKeyInputUpArrow') { - if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OA'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[A'; - } - } - else if (ev.key === 'UIKeyInputLeftArrow') { - if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OD'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[D'; - } - } - else if (ev.key === 'UIKeyInputRightArrow') { - if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OC'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[C'; - } - } - else if (ev.key === 'UIKeyInputDownArrow') { - if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OB'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[B'; - } - } - break; - case 8: - if (ev.shiftKey) { - result.key = EscapeSequences_1.C0.BS; - break; - } - else if (ev.altKey) { - result.key = EscapeSequences_1.C0.ESC + EscapeSequences_1.C0.DEL; - break; - } - result.key = EscapeSequences_1.C0.DEL; - break; - case 9: - if (ev.shiftKey) { - result.key = EscapeSequences_1.C0.ESC + '[Z'; - break; - } - result.key = EscapeSequences_1.C0.HT; - result.cancel = true; - break; - case 13: - result.key = EscapeSequences_1.C0.CR; - result.cancel = true; - break; - case 27: - result.key = EscapeSequences_1.C0.ESC; - result.cancel = true; - break; - case 37: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'D'; - if (result.key === EscapeSequences_1.C0.ESC + '[1;3D') { - result.key = isMac ? EscapeSequences_1.C0.ESC + 'b' : EscapeSequences_1.C0.ESC + '[1;5D'; - } - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OD'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[D'; - } - break; - case 39: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'C'; - if (result.key === EscapeSequences_1.C0.ESC + '[1;3C') { - result.key = isMac ? EscapeSequences_1.C0.ESC + 'f' : EscapeSequences_1.C0.ESC + '[1;5C'; - } - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OC'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[C'; - } - break; - case 38: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'A'; - if (result.key === EscapeSequences_1.C0.ESC + '[1;3A') { - result.key = EscapeSequences_1.C0.ESC + '[1;5A'; - } - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OA'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[A'; - } - break; - case 40: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'B'; - if (result.key === EscapeSequences_1.C0.ESC + '[1;3B') { - result.key = EscapeSequences_1.C0.ESC + '[1;5B'; - } - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OB'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[B'; - } - break; - case 45: - if (!ev.shiftKey && !ev.ctrlKey) { - result.key = EscapeSequences_1.C0.ESC + '[2~'; - } - break; - case 46: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[3;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[3~'; - } - break; - case 36: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'H'; - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OH'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[H'; - } - break; - case 35: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'F'; - } - else if (applicationCursorMode) { - result.key = EscapeSequences_1.C0.ESC + 'OF'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[F'; - } - break; - case 33: - if (ev.shiftKey) { - result.type = 2; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[5~'; - } - break; - case 34: - if (ev.shiftKey) { - result.type = 3; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[6~'; - } - break; - case 112: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'P'; - } - else { - result.key = EscapeSequences_1.C0.ESC + 'OP'; - } - break; - case 113: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'Q'; - } - else { - result.key = EscapeSequences_1.C0.ESC + 'OQ'; - } - break; - case 114: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'R'; - } - else { - result.key = EscapeSequences_1.C0.ESC + 'OR'; - } - break; - case 115: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[1;' + (modifiers + 1) + 'S'; - } - else { - result.key = EscapeSequences_1.C0.ESC + 'OS'; - } - break; - case 116: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[15;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[15~'; - } - break; - case 117: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[17;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[17~'; - } - break; - case 118: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[18;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[18~'; - } - break; - case 119: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[19;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[19~'; - } - break; - case 120: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[20;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[20~'; - } - break; - case 121: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[21;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[21~'; - } - break; - case 122: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[23;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[23~'; - } - break; - case 123: - if (modifiers) { - result.key = EscapeSequences_1.C0.ESC + '[24;' + (modifiers + 1) + '~'; - } - else { - result.key = EscapeSequences_1.C0.ESC + '[24~'; - } - break; - default: - if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) { - if (ev.keyCode >= 65 && ev.keyCode <= 90) { - result.key = String.fromCharCode(ev.keyCode - 64); - } - else if (ev.keyCode === 32) { - result.key = String.fromCharCode(0); - } - else if (ev.keyCode >= 51 && ev.keyCode <= 55) { - result.key = String.fromCharCode(ev.keyCode - 51 + 27); - } - else if (ev.keyCode === 56) { - result.key = String.fromCharCode(127); - } - else if (ev.keyCode === 219) { - result.key = String.fromCharCode(27); - } - else if (ev.keyCode === 220) { - result.key = String.fromCharCode(28); - } - else if (ev.keyCode === 221) { - result.key = String.fromCharCode(29); - } - } - else if ((!isMac || macOptionIsMeta) && ev.altKey && !ev.metaKey) { - var keyMapping = KEYCODE_KEY_MAPPINGS[ev.keyCode]; - var key = keyMapping && keyMapping[!ev.shiftKey ? 0 : 1]; - if (key) { - result.key = EscapeSequences_1.C0.ESC + key; - } - else if (ev.keyCode >= 65 && ev.keyCode <= 90) { - var keyCode = ev.ctrlKey ? ev.keyCode - 64 : ev.keyCode + 32; - result.key = EscapeSequences_1.C0.ESC + String.fromCharCode(keyCode); - } - } - else if (isMac && !ev.altKey && !ev.ctrlKey && ev.metaKey) { - if (ev.keyCode === 65) { - result.type = 1; - } - } - break; - } - return result; -} -exports.evaluateKeyboardEvent = evaluateKeyboardEvent; - -},{"../../common/data/EscapeSequences":20}],24:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var EscapeSequences_1 = require("../common/data/EscapeSequences"); -var AltClickHandler = (function () { - function AltClickHandler(_mouseEvent, _terminal) { - var _a; - this._mouseEvent = _mouseEvent; - this._terminal = _terminal; - this._lines = this._terminal.buffer.lines; - this._startCol = this._terminal.buffer.x; - this._startRow = this._terminal.buffer.y; - var coordinates = this._terminal.mouseHelper.getCoords(this._mouseEvent, this._terminal.element, this._terminal.charMeasure, this._terminal.cols, this._terminal.rows, false); - if (coordinates) { - _a = coordinates.map(function (coordinate) { - return coordinate - 1; - }), this._endCol = _a[0], this._endRow = _a[1]; - } - } - AltClickHandler.prototype.move = function () { - if (this._mouseEvent.altKey && this._endCol !== undefined && this._endRow !== undefined) { - this._terminal.handler(this._arrowSequences()); - } - }; - AltClickHandler.prototype._arrowSequences = function () { - if (!this._terminal.buffer.hasScrollback) { - return this._resetStartingRow() + this._moveToRequestedRow() + this._moveToRequestedCol(); - } - return this._moveHorizontallyOnly(); - }; - AltClickHandler.prototype._resetStartingRow = function () { - if (this._moveToRequestedRow().length === 0) { - return ''; - } - return repeat(this._bufferLine(this._startCol, this._startRow, this._startCol, this._startRow - this._wrappedRowsForRow(this._startRow), false).length, this._sequence("D")); - }; - AltClickHandler.prototype._moveToRequestedRow = function () { - var startRow = this._startRow - this._wrappedRowsForRow(this._startRow); - var endRow = this._endRow - this._wrappedRowsForRow(this._endRow); - var rowsToMove = Math.abs(startRow - endRow) - this._wrappedRowsCount(); - return repeat(rowsToMove, this._sequence(this._verticalDirection())); - }; - AltClickHandler.prototype._moveToRequestedCol = function () { - var startRow; - if (this._moveToRequestedRow().length > 0) { - startRow = this._endRow - this._wrappedRowsForRow(this._endRow); - } - else { - startRow = this._startRow; - } - var endRow = this._endRow; - var direction = this._horizontalDirection(); - return repeat(this._bufferLine(this._startCol, startRow, this._endCol, endRow, direction === "C").length, this._sequence(direction)); - }; - AltClickHandler.prototype._moveHorizontallyOnly = function () { - var direction = this._horizontalDirection(); - return repeat(Math.abs(this._startCol - this._endCol), this._sequence(direction)); - }; - AltClickHandler.prototype._wrappedRowsCount = function () { - var wrappedRows = 0; - var startRow = this._startRow - this._wrappedRowsForRow(this._startRow); - var endRow = this._endRow - this._wrappedRowsForRow(this._endRow); - for (var i = 0; i < Math.abs(startRow - endRow); i++) { - var direction = this._verticalDirection() === "A" ? -1 : 1; - if (this._lines.get(startRow + (direction * i)).isWrapped) { - wrappedRows++; - } - } - return wrappedRows; - }; - AltClickHandler.prototype._wrappedRowsForRow = function (currentRow) { - var rowCount = 0; - var lineWraps = this._lines.get(currentRow).isWrapped; - while (lineWraps && currentRow >= 0 && currentRow < this._terminal.rows) { - rowCount++; - currentRow--; - lineWraps = this._lines.get(currentRow).isWrapped; - } - return rowCount; - }; - AltClickHandler.prototype._horizontalDirection = function () { - var startRow; - if (this._moveToRequestedRow().length > 0) { - startRow = this._endRow - this._wrappedRowsForRow(this._endRow); - } - else { - startRow = this._startRow; - } - if ((this._startCol < this._endCol && - startRow <= this._endRow) || - (this._startCol >= this._endCol && - startRow < this._endRow)) { - return "C"; - } - return "D"; - }; - AltClickHandler.prototype._verticalDirection = function () { - if (this._startRow > this._endRow) { - return "A"; - } - return "B"; - }; - AltClickHandler.prototype._bufferLine = function (startCol, startRow, endCol, endRow, forward) { - var currentCol = startCol; - var currentRow = startRow; - var bufferStr = ''; - while (currentCol !== endCol || currentRow !== endRow) { - currentCol += forward ? 1 : -1; - if (forward && currentCol > this._terminal.cols - 1) { - bufferStr += this._terminal.buffer.translateBufferLineToString(currentRow, false, startCol, currentCol); - currentCol = 0; - startCol = 0; - currentRow++; - } - else if (!forward && currentCol < 0) { - bufferStr += this._terminal.buffer.translateBufferLineToString(currentRow, false, 0, startCol + 1); - currentCol = this._terminal.cols - 1; - startCol = currentCol; - currentRow--; - } - } - return bufferStr + this._terminal.buffer.translateBufferLineToString(currentRow, false, startCol, currentCol); - }; - AltClickHandler.prototype._sequence = function (direction) { - var mod = this._terminal.applicationCursor ? 'O' : '['; - return EscapeSequences_1.C0.ESC + mod + direction; - }; - return AltClickHandler; -}()); -exports.AltClickHandler = AltClickHandler; -function repeat(count, str) { - count = Math.floor(count); - var rpt = ''; - for (var i = 0; i < count; i++) { - rpt += str; - } - return rpt; -} - -},{"../common/data/EscapeSequences":20}],25:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Terminal_1 = require("../Terminal"); -var Strings = require("../Strings"); -var Terminal = (function () { - function Terminal(options) { - this._core = new Terminal_1.Terminal(options); - } - Object.defineProperty(Terminal.prototype, "element", { - get: function () { return this._core.element; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Terminal.prototype, "textarea", { - get: function () { return this._core.textarea; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Terminal.prototype, "rows", { - get: function () { return this._core.rows; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Terminal.prototype, "cols", { - get: function () { return this._core.cols; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Terminal.prototype, "markers", { - get: function () { return this._core.markers; }, - enumerable: true, - configurable: true - }); - Terminal.prototype.blur = function () { - this._core.blur(); - }; - Terminal.prototype.focus = function () { - this._core.focus(); - }; - Terminal.prototype.on = function (type, listener) { - this._core.on(type, listener); - }; - Terminal.prototype.off = function (type, listener) { - this._core.off(type, listener); - }; - Terminal.prototype.emit = function (type, data) { - this._core.emit(type, data); - }; - Terminal.prototype.addDisposableListener = function (type, handler) { - return this._core.addDisposableListener(type, handler); - }; - Terminal.prototype.resize = function (columns, rows) { - this._core.resize(columns, rows); - }; - Terminal.prototype.writeln = function (data) { - this._core.writeln(data); - }; - Terminal.prototype.open = function (parent) { - this._core.open(parent); - }; - Terminal.prototype.attachCustomKeyEventHandler = function (customKeyEventHandler) { - this._core.attachCustomKeyEventHandler(customKeyEventHandler); - }; - Terminal.prototype.registerLinkMatcher = function (regex, handler, options) { - return this._core.registerLinkMatcher(regex, handler, options); - }; - Terminal.prototype.deregisterLinkMatcher = function (matcherId) { - this._core.deregisterLinkMatcher(matcherId); - }; - Terminal.prototype.registerCharacterJoiner = function (handler) { - return this._core.registerCharacterJoiner(handler); - }; - Terminal.prototype.deregisterCharacterJoiner = function (joinerId) { - this._core.deregisterCharacterJoiner(joinerId); - }; - Terminal.prototype.addMarker = function (cursorYOffset) { - return this._core.addMarker(cursorYOffset); - }; - Terminal.prototype.hasSelection = function () { - return this._core.hasSelection(); - }; - Terminal.prototype.getSelection = function () { - return this._core.getSelection(); - }; - Terminal.prototype.clearSelection = function () { - this._core.clearSelection(); - }; - Terminal.prototype.selectAll = function () { - this._core.selectAll(); - }; - Terminal.prototype.selectLines = function (start, end) { - this._core.selectLines(start, end); - }; - Terminal.prototype.dispose = function () { - this._core.dispose(); - }; - Terminal.prototype.destroy = function () { - this._core.destroy(); - }; - Terminal.prototype.scrollLines = function (amount) { - this._core.scrollLines(amount); - }; - Terminal.prototype.scrollPages = function (pageCount) { - this._core.scrollPages(pageCount); - }; - Terminal.prototype.scrollToTop = function () { - this._core.scrollToTop(); - }; - Terminal.prototype.scrollToBottom = function () { - this._core.scrollToBottom(); - }; - Terminal.prototype.scrollToLine = function (line) { - this._core.scrollToLine(line); - }; - Terminal.prototype.clear = function () { - this._core.clear(); - }; - Terminal.prototype.write = function (data) { - this._core.write(data); - }; - Terminal.prototype.getOption = function (key) { - return this._core.getOption(key); - }; - Terminal.prototype.setOption = function (key, value) { - this._core.setOption(key, value); - }; - Terminal.prototype.refresh = function (start, end) { - this._core.refresh(start, end); - }; - Terminal.prototype.reset = function () { - this._core.reset(); - }; - Terminal.applyAddon = function (addon) { - addon.apply(Terminal); - }; - Object.defineProperty(Terminal, "strings", { - get: function () { - return Strings; - }, - enumerable: true, - configurable: true - }); - return Terminal; -}()); -exports.Terminal = Terminal; - -},{"../Strings":13,"../Terminal":14}],26:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Types_1 = require("./atlas/Types"); -var CharAtlasCache_1 = require("./atlas/CharAtlasCache"); -var Buffer_1 = require("../Buffer"); -var CharAtlasUtils_1 = require("./atlas/CharAtlasUtils"); -var BaseRenderLayer = (function () { - function BaseRenderLayer(_container, id, zIndex, _alpha, _colors) { - this._container = _container; - this._alpha = _alpha; - this._colors = _colors; - this._scaledCharWidth = 0; - this._scaledCharHeight = 0; - this._scaledCellWidth = 0; - this._scaledCellHeight = 0; - this._scaledCharLeft = 0; - this._scaledCharTop = 0; - this._currentGlyphIdentifier = { - chars: '', - code: 0, - bg: 0, - fg: 0, - bold: false, - dim: false, - italic: false - }; - this._canvas = document.createElement('canvas'); - this._canvas.classList.add("xterm-" + id + "-layer"); - this._canvas.style.zIndex = zIndex.toString(); - this._initCanvas(); - this._container.appendChild(this._canvas); - } - BaseRenderLayer.prototype.dispose = function () { - this._container.removeChild(this._canvas); - if (this._charAtlas) { - this._charAtlas.dispose(); - } - }; - BaseRenderLayer.prototype._initCanvas = function () { - this._ctx = this._canvas.getContext('2d', { alpha: this._alpha }); - if (!this._alpha) { - this.clearAll(); - } - }; - BaseRenderLayer.prototype.onOptionsChanged = function (terminal) { }; - BaseRenderLayer.prototype.onBlur = function (terminal) { }; - BaseRenderLayer.prototype.onFocus = function (terminal) { }; - BaseRenderLayer.prototype.onCursorMove = function (terminal) { }; - BaseRenderLayer.prototype.onGridChanged = function (terminal, startRow, endRow) { }; - BaseRenderLayer.prototype.onSelectionChanged = function (terminal, start, end, columnSelectMode) { - if (columnSelectMode === void 0) { columnSelectMode = false; } - }; - BaseRenderLayer.prototype.onThemeChanged = function (terminal, colorSet) { - this._refreshCharAtlas(terminal, colorSet); - }; - BaseRenderLayer.prototype.setTransparency = function (terminal, alpha) { - if (alpha === this._alpha) { - return; - } - var oldCanvas = this._canvas; - this._alpha = alpha; - this._canvas = this._canvas.cloneNode(); - this._initCanvas(); - this._container.replaceChild(this._canvas, oldCanvas); - this._refreshCharAtlas(terminal, this._colors); - this.onGridChanged(terminal, 0, terminal.rows - 1); - }; - BaseRenderLayer.prototype._refreshCharAtlas = function (terminal, colorSet) { - if (this._scaledCharWidth <= 0 && this._scaledCharHeight <= 0) { - return; - } - this._charAtlas = CharAtlasCache_1.acquireCharAtlas(terminal, colorSet, this._scaledCharWidth, this._scaledCharHeight); - this._charAtlas.warmUp(); - }; - BaseRenderLayer.prototype.resize = function (terminal, dim) { - this._scaledCellWidth = dim.scaledCellWidth; - this._scaledCellHeight = dim.scaledCellHeight; - this._scaledCharWidth = dim.scaledCharWidth; - this._scaledCharHeight = dim.scaledCharHeight; - this._scaledCharLeft = dim.scaledCharLeft; - this._scaledCharTop = dim.scaledCharTop; - this._canvas.width = dim.scaledCanvasWidth; - this._canvas.height = dim.scaledCanvasHeight; - this._canvas.style.width = dim.canvasWidth + "px"; - this._canvas.style.height = dim.canvasHeight + "px"; - if (!this._alpha) { - this.clearAll(); - } - this._refreshCharAtlas(terminal, this._colors); - }; - BaseRenderLayer.prototype.fillCells = function (x, y, width, height) { - this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight); - }; - BaseRenderLayer.prototype.fillBottomLineAtCells = function (x, y, width) { - if (width === void 0) { width = 1; } - this._ctx.fillRect(x * this._scaledCellWidth, (y + 1) * this._scaledCellHeight - window.devicePixelRatio - 1, width * this._scaledCellWidth, window.devicePixelRatio); - }; - BaseRenderLayer.prototype.fillLeftLineAtCell = function (x, y) { - this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, window.devicePixelRatio, this._scaledCellHeight); - }; - BaseRenderLayer.prototype.strokeRectAtCell = function (x, y, width, height) { - this._ctx.lineWidth = window.devicePixelRatio; - this._ctx.strokeRect(x * this._scaledCellWidth + window.devicePixelRatio / 2, y * this._scaledCellHeight + (window.devicePixelRatio / 2), width * this._scaledCellWidth - window.devicePixelRatio, (height * this._scaledCellHeight) - window.devicePixelRatio); - }; - BaseRenderLayer.prototype.clearAll = function () { - if (this._alpha) { - this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); - } - else { - this._ctx.fillStyle = this._colors.background.css; - this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height); - } - }; - BaseRenderLayer.prototype.clearCells = function (x, y, width, height) { - if (this._alpha) { - this._ctx.clearRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight); - } - else { - this._ctx.fillStyle = this._colors.background.css; - this._ctx.fillRect(x * this._scaledCellWidth, y * this._scaledCellHeight, width * this._scaledCellWidth, height * this._scaledCellHeight); - } - }; - BaseRenderLayer.prototype.fillCharTrueColor = function (terminal, charData, x, y) { - this._ctx.font = this._getFont(terminal, false, false); - this._ctx.textBaseline = 'top'; - this._clipRow(terminal, y); - this._ctx.fillText(charData[Buffer_1.CHAR_DATA_CHAR_INDEX], x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop); - }; - BaseRenderLayer.prototype.drawChars = function (terminal, chars, code, width, x, y, fg, bg, bold, dim, italic) { - var drawInBrightColor = terminal.options.drawBoldTextInBrightColors && bold && fg < 8 && fg !== Types_1.INVERTED_DEFAULT_COLOR; - fg += drawInBrightColor ? 8 : 0; - this._currentGlyphIdentifier.chars = chars; - this._currentGlyphIdentifier.code = code; - this._currentGlyphIdentifier.bg = bg; - this._currentGlyphIdentifier.fg = fg; - this._currentGlyphIdentifier.bold = bold && terminal.options.enableBold; - this._currentGlyphIdentifier.dim = dim; - this._currentGlyphIdentifier.italic = italic; - var atlasDidDraw = this._charAtlas && this._charAtlas.draw(this._ctx, this._currentGlyphIdentifier, x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop); - if (!atlasDidDraw) { - this._drawUncachedChars(terminal, chars, width, fg, x, y, bold && terminal.options.enableBold, dim, italic); - } - }; - BaseRenderLayer.prototype._drawUncachedChars = function (terminal, chars, width, fg, x, y, bold, dim, italic) { - this._ctx.save(); - this._ctx.font = this._getFont(terminal, bold, italic); - this._ctx.textBaseline = 'top'; - if (fg === Types_1.INVERTED_DEFAULT_COLOR) { - this._ctx.fillStyle = this._colors.background.css; - } - else if (CharAtlasUtils_1.is256Color(fg)) { - this._ctx.fillStyle = this._colors.ansi[fg].css; - } - else { - this._ctx.fillStyle = this._colors.foreground.css; - } - this._clipRow(terminal, y); - if (dim) { - this._ctx.globalAlpha = Types_1.DIM_OPACITY; - } - this._ctx.fillText(chars, x * this._scaledCellWidth + this._scaledCharLeft, y * this._scaledCellHeight + this._scaledCharTop); - this._ctx.restore(); - }; - BaseRenderLayer.prototype._clipRow = function (terminal, y) { - this._ctx.beginPath(); - this._ctx.rect(0, y * this._scaledCellHeight, terminal.cols * this._scaledCellWidth, this._scaledCellHeight); - this._ctx.clip(); - }; - BaseRenderLayer.prototype._getFont = function (terminal, isBold, isItalic) { - var fontWeight = isBold ? terminal.options.fontWeightBold : terminal.options.fontWeight; - var fontStyle = isItalic ? 'italic' : ''; - return fontStyle + " " + fontWeight + " " + terminal.options.fontSize * window.devicePixelRatio + "px " + terminal.options.fontFamily; - }; - return BaseRenderLayer; -}()); -exports.BaseRenderLayer = BaseRenderLayer; - -},{"../Buffer":2,"./atlas/CharAtlasCache":36,"./atlas/CharAtlasUtils":38,"./atlas/Types":43}],27:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("../Buffer"); -var CharacterJoinerRegistry = (function () { - function CharacterJoinerRegistry(_terminal) { - this._terminal = _terminal; - this._characterJoiners = []; - this._nextCharacterJoinerId = 0; - } - CharacterJoinerRegistry.prototype.registerCharacterJoiner = function (handler) { - var joiner = { - id: this._nextCharacterJoinerId++, - handler: handler - }; - this._characterJoiners.push(joiner); - return joiner.id; - }; - CharacterJoinerRegistry.prototype.deregisterCharacterJoiner = function (joinerId) { - for (var i = 0; i < this._characterJoiners.length; i++) { - if (this._characterJoiners[i].id === joinerId) { - this._characterJoiners.splice(i, 1); - return true; - } - } - return false; - }; - CharacterJoinerRegistry.prototype.getJoinedCharacters = function (row) { - if (this._characterJoiners.length === 0) { - return []; - } - var line = this._terminal.buffer.lines.get(row); - if (line.length === 0) { - return []; - } - var ranges = []; - var lineStr = this._terminal.buffer.translateBufferLineToString(row, true); - var rangeStartColumn = 0; - var currentStringIndex = 0; - var rangeStartStringIndex = 0; - var rangeAttr = line.get(0)[Buffer_1.CHAR_DATA_ATTR_INDEX] >> 9; - for (var x = 0; x < this._terminal.cols; x++) { - var charData = line.get(x); - var chars = charData[Buffer_1.CHAR_DATA_CHAR_INDEX]; - var width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - var attr = charData[Buffer_1.CHAR_DATA_ATTR_INDEX] >> 9; - if (width === 0) { - continue; - } - if (attr !== rangeAttr) { - if (x - rangeStartColumn > 1) { - var joinedRanges = this._getJoinedRanges(lineStr, rangeStartStringIndex, currentStringIndex, line, rangeStartColumn); - for (var i = 0; i < joinedRanges.length; i++) { - ranges.push(joinedRanges[i]); - } - } - rangeStartColumn = x; - rangeStartStringIndex = currentStringIndex; - rangeAttr = attr; - } - currentStringIndex += chars.length; - } - if (this._terminal.cols - rangeStartColumn > 1) { - var joinedRanges = this._getJoinedRanges(lineStr, rangeStartStringIndex, currentStringIndex, line, rangeStartColumn); - for (var i = 0; i < joinedRanges.length; i++) { - ranges.push(joinedRanges[i]); - } - } - return ranges; - }; - CharacterJoinerRegistry.prototype._getJoinedRanges = function (line, startIndex, endIndex, lineData, startCol) { - var text = line.substring(startIndex, endIndex); - var joinedRanges = this._characterJoiners[0].handler(text); - for (var i = 1; i < this._characterJoiners.length; i++) { - var joinerRanges = this._characterJoiners[i].handler(text); - for (var j = 0; j < joinerRanges.length; j++) { - CharacterJoinerRegistry._mergeRanges(joinedRanges, joinerRanges[j]); - } - } - this._stringRangesToCellRanges(joinedRanges, lineData, startCol); - return joinedRanges; - }; - CharacterJoinerRegistry.prototype._stringRangesToCellRanges = function (ranges, line, startCol) { - var currentRangeIndex = 0; - var currentRangeStarted = false; - var currentStringIndex = 0; - var currentRange = ranges[currentRangeIndex]; - if (!currentRange) { - return; - } - for (var x = startCol; x < this._terminal.cols; x++) { - var charData = line.get(x); - var width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - var length_1 = charData[Buffer_1.CHAR_DATA_CHAR_INDEX].length; - if (width === 0) { - continue; - } - if (!currentRangeStarted && currentRange[0] <= currentStringIndex) { - currentRange[0] = x; - currentRangeStarted = true; - } - if (currentRange[1] <= currentStringIndex) { - currentRange[1] = x; - currentRange = ranges[++currentRangeIndex]; - if (!currentRange) { - break; - } - if (currentRange[0] <= currentStringIndex) { - currentRange[0] = x; - currentRangeStarted = true; - } - else { - currentRangeStarted = false; - } - } - currentStringIndex += length_1; - } - if (currentRange) { - currentRange[1] = this._terminal.cols; - } - }; - CharacterJoinerRegistry._mergeRanges = function (ranges, newRange) { - var inRange = false; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!inRange) { - if (newRange[1] <= range[0]) { - ranges.splice(i, 0, newRange); - return ranges; - } - if (newRange[1] <= range[1]) { - range[0] = Math.min(newRange[0], range[0]); - return ranges; - } - if (newRange[0] < range[1]) { - range[0] = Math.min(newRange[0], range[0]); - inRange = true; - } - continue; - } - else { - if (newRange[1] <= range[0]) { - ranges[i - 1][1] = newRange[1]; - return ranges; - } - if (newRange[1] <= range[1]) { - ranges[i - 1][1] = Math.max(newRange[1], range[1]); - ranges.splice(i, 1); - inRange = false; - return ranges; - } - ranges.splice(i, 1); - i--; - } - } - if (inRange) { - ranges[ranges.length - 1][1] = newRange[1]; - } - else { - ranges.push(newRange); - } - return ranges; - }; - return CharacterJoinerRegistry; -}()); -exports.CharacterJoinerRegistry = CharacterJoinerRegistry; - -},{"../Buffer":2}],28:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var DEFAULT_FOREGROUND = fromHex('#ffffff'); -var DEFAULT_BACKGROUND = fromHex('#000000'); -var DEFAULT_CURSOR = fromHex('#ffffff'); -var DEFAULT_CURSOR_ACCENT = fromHex('#000000'); -var DEFAULT_SELECTION = { - css: 'rgba(255, 255, 255, 0.3)', - rgba: 0xFFFFFF77 -}; -exports.DEFAULT_ANSI_COLORS = (function () { - var colors = [ - fromHex('#2e3436'), - fromHex('#cc0000'), - fromHex('#4e9a06'), - fromHex('#c4a000'), - fromHex('#3465a4'), - fromHex('#75507b'), - fromHex('#06989a'), - fromHex('#d3d7cf'), - fromHex('#555753'), - fromHex('#ef2929'), - fromHex('#8ae234'), - fromHex('#fce94f'), - fromHex('#729fcf'), - fromHex('#ad7fa8'), - fromHex('#34e2e2'), - fromHex('#eeeeec') - ]; - var v = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]; - for (var i = 0; i < 216; i++) { - var r = v[(i / 36) % 6 | 0]; - var g = v[(i / 6) % 6 | 0]; - var b = v[i % 6]; - colors.push({ - css: "#" + toPaddedHex(r) + toPaddedHex(g) + toPaddedHex(b), - rgba: ((r << 24) | (g << 16) | (b << 8) | 0xFF) >>> 0 - }); - } - for (var i = 0; i < 24; i++) { - var c = 8 + i * 10; - var ch = toPaddedHex(c); - colors.push({ - css: "#" + ch + ch + ch, - rgba: ((c << 24) | (c << 16) | (c << 8) | 0xFF) >>> 0 - }); - } - return colors; -})(); -function fromHex(css) { - return { - css: css, - rgba: parseInt(css.slice(1), 16) << 8 | 0xFF - }; -} -function toPaddedHex(c) { - var s = c.toString(16); - return s.length < 2 ? '0' + s : s; -} -var ColorManager = (function () { - function ColorManager(document, allowTransparency) { - this.allowTransparency = allowTransparency; - var canvas = document.createElement('canvas'); - canvas.width = 1; - canvas.height = 1; - this._ctx = canvas.getContext('2d'); - this._ctx.globalCompositeOperation = 'copy'; - this._litmusColor = this._ctx.createLinearGradient(0, 0, 1, 1); - this.colors = { - foreground: DEFAULT_FOREGROUND, - background: DEFAULT_BACKGROUND, - cursor: DEFAULT_CURSOR, - cursorAccent: DEFAULT_CURSOR_ACCENT, - selection: DEFAULT_SELECTION, - ansi: exports.DEFAULT_ANSI_COLORS.slice() - }; - } - ColorManager.prototype.setTheme = function (theme) { - this.colors.foreground = this._parseColor(theme.foreground, DEFAULT_FOREGROUND); - this.colors.background = this._parseColor(theme.background, DEFAULT_BACKGROUND); - this.colors.cursor = this._parseColor(theme.cursor, DEFAULT_CURSOR, true); - this.colors.cursorAccent = this._parseColor(theme.cursorAccent, DEFAULT_CURSOR_ACCENT, true); - this.colors.selection = this._parseColor(theme.selection, DEFAULT_SELECTION, true); - this.colors.ansi[0] = this._parseColor(theme.black, exports.DEFAULT_ANSI_COLORS[0]); - this.colors.ansi[1] = this._parseColor(theme.red, exports.DEFAULT_ANSI_COLORS[1]); - this.colors.ansi[2] = this._parseColor(theme.green, exports.DEFAULT_ANSI_COLORS[2]); - this.colors.ansi[3] = this._parseColor(theme.yellow, exports.DEFAULT_ANSI_COLORS[3]); - this.colors.ansi[4] = this._parseColor(theme.blue, exports.DEFAULT_ANSI_COLORS[4]); - this.colors.ansi[5] = this._parseColor(theme.magenta, exports.DEFAULT_ANSI_COLORS[5]); - this.colors.ansi[6] = this._parseColor(theme.cyan, exports.DEFAULT_ANSI_COLORS[6]); - this.colors.ansi[7] = this._parseColor(theme.white, exports.DEFAULT_ANSI_COLORS[7]); - this.colors.ansi[8] = this._parseColor(theme.brightBlack, exports.DEFAULT_ANSI_COLORS[8]); - this.colors.ansi[9] = this._parseColor(theme.brightRed, exports.DEFAULT_ANSI_COLORS[9]); - this.colors.ansi[10] = this._parseColor(theme.brightGreen, exports.DEFAULT_ANSI_COLORS[10]); - this.colors.ansi[11] = this._parseColor(theme.brightYellow, exports.DEFAULT_ANSI_COLORS[11]); - this.colors.ansi[12] = this._parseColor(theme.brightBlue, exports.DEFAULT_ANSI_COLORS[12]); - this.colors.ansi[13] = this._parseColor(theme.brightMagenta, exports.DEFAULT_ANSI_COLORS[13]); - this.colors.ansi[14] = this._parseColor(theme.brightCyan, exports.DEFAULT_ANSI_COLORS[14]); - this.colors.ansi[15] = this._parseColor(theme.brightWhite, exports.DEFAULT_ANSI_COLORS[15]); - }; - ColorManager.prototype._parseColor = function (css, fallback, allowTransparency) { - if (allowTransparency === void 0) { allowTransparency = this.allowTransparency; } - if (!css) { - return fallback; - } - this._ctx.fillStyle = this._litmusColor; - this._ctx.fillStyle = css; - if (typeof this._ctx.fillStyle !== 'string') { - console.warn("Color: " + css + " is invalid using fallback " + fallback.css); - return fallback; - } - this._ctx.fillRect(0, 0, 1, 1); - var data = this._ctx.getImageData(0, 0, 1, 1).data; - if (!allowTransparency && data[3] !== 0xFF) { - console.warn("Color: " + css + " is using transparency, but allowTransparency is false. " + - ("Using fallback " + fallback.css + ".")); - return fallback; - } - return { - css: css, - rgba: (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >>> 0 - }; - }; - return ColorManager; -}()); -exports.ColorManager = ColorManager; - -},{}],29:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("../Buffer"); -var BaseRenderLayer_1 = require("./BaseRenderLayer"); -var BLINK_INTERVAL = 600; -var CursorRenderLayer = (function (_super) { - __extends(CursorRenderLayer, _super); - function CursorRenderLayer(container, zIndex, colors) { - var _this = _super.call(this, container, 'cursor', zIndex, true, colors) || this; - _this._state = { - x: null, - y: null, - isFocused: null, - style: null, - width: null - }; - _this._cursorRenderers = { - 'bar': _this._renderBarCursor.bind(_this), - 'block': _this._renderBlockCursor.bind(_this), - 'underline': _this._renderUnderlineCursor.bind(_this) - }; - return _this; - } - CursorRenderLayer.prototype.resize = function (terminal, dim) { - _super.prototype.resize.call(this, terminal, dim); - this._state = { - x: null, - y: null, - isFocused: null, - style: null, - width: null - }; - }; - CursorRenderLayer.prototype.reset = function (terminal) { - this._clearCursor(); - if (this._cursorBlinkStateManager) { - this._cursorBlinkStateManager.dispose(); - this._cursorBlinkStateManager = null; - this.onOptionsChanged(terminal); - } - }; - CursorRenderLayer.prototype.onBlur = function (terminal) { - if (this._cursorBlinkStateManager) { - this._cursorBlinkStateManager.pause(); - } - terminal.refresh(terminal.buffer.y, terminal.buffer.y); - }; - CursorRenderLayer.prototype.onFocus = function (terminal) { - if (this._cursorBlinkStateManager) { - this._cursorBlinkStateManager.resume(terminal); - } - else { - terminal.refresh(terminal.buffer.y, terminal.buffer.y); - } - }; - CursorRenderLayer.prototype.onOptionsChanged = function (terminal) { - var _this = this; - if (terminal.options.cursorBlink) { - if (!this._cursorBlinkStateManager) { - this._cursorBlinkStateManager = new CursorBlinkStateManager(terminal, function () { - _this._render(terminal, true); - }); - } - } - else { - if (this._cursorBlinkStateManager) { - this._cursorBlinkStateManager.dispose(); - this._cursorBlinkStateManager = null; - } - terminal.refresh(terminal.buffer.y, terminal.buffer.y); - } - }; - CursorRenderLayer.prototype.onCursorMove = function (terminal) { - if (this._cursorBlinkStateManager) { - this._cursorBlinkStateManager.restartBlinkAnimation(terminal); - } - }; - CursorRenderLayer.prototype.onGridChanged = function (terminal, startRow, endRow) { - if (!this._cursorBlinkStateManager || this._cursorBlinkStateManager.isPaused) { - this._render(terminal, false); - } - else { - this._cursorBlinkStateManager.restartBlinkAnimation(terminal); - } - }; - CursorRenderLayer.prototype._render = function (terminal, triggeredByAnimationFrame) { - if (!terminal.cursorState || terminal.cursorHidden) { - this._clearCursor(); - return; - } - var cursorY = terminal.buffer.ybase + terminal.buffer.y; - var viewportRelativeCursorY = cursorY - terminal.buffer.ydisp; - if (viewportRelativeCursorY < 0 || viewportRelativeCursorY >= terminal.rows) { - this._clearCursor(); - return; - } - var charData = terminal.buffer.lines.get(cursorY).get(terminal.buffer.x); - if (!charData) { - return; - } - if (!terminal.isFocused) { - this._clearCursor(); - this._ctx.save(); - this._ctx.fillStyle = this._colors.cursor.css; - this._renderBlurCursor(terminal, terminal.buffer.x, viewportRelativeCursorY, charData); - this._ctx.restore(); - this._state.x = terminal.buffer.x; - this._state.y = viewportRelativeCursorY; - this._state.isFocused = false; - this._state.style = terminal.options.cursorStyle; - this._state.width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - return; - } - if (this._cursorBlinkStateManager && !this._cursorBlinkStateManager.isCursorVisible) { - this._clearCursor(); - return; - } - if (this._state) { - if (this._state.x === terminal.buffer.x && - this._state.y === viewportRelativeCursorY && - this._state.isFocused === terminal.isFocused && - this._state.style === terminal.options.cursorStyle && - this._state.width === charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]) { - return; - } - this._clearCursor(); - } - this._ctx.save(); - this._cursorRenderers[terminal.options.cursorStyle || 'block'](terminal, terminal.buffer.x, viewportRelativeCursorY, charData); - this._ctx.restore(); - this._state.x = terminal.buffer.x; - this._state.y = viewportRelativeCursorY; - this._state.isFocused = false; - this._state.style = terminal.options.cursorStyle; - this._state.width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - }; - CursorRenderLayer.prototype._clearCursor = function () { - if (this._state) { - this.clearCells(this._state.x, this._state.y, this._state.width, 1); - this._state = { - x: null, - y: null, - isFocused: null, - style: null, - width: null - }; - } - }; - CursorRenderLayer.prototype._renderBarCursor = function (terminal, x, y, charData) { - this._ctx.save(); - this._ctx.fillStyle = this._colors.cursor.css; - this.fillLeftLineAtCell(x, y); - this._ctx.restore(); - }; - CursorRenderLayer.prototype._renderBlockCursor = function (terminal, x, y, charData) { - this._ctx.save(); - this._ctx.fillStyle = this._colors.cursor.css; - this.fillCells(x, y, charData[Buffer_1.CHAR_DATA_WIDTH_INDEX], 1); - this._ctx.fillStyle = this._colors.cursorAccent.css; - this.fillCharTrueColor(terminal, charData, x, y); - this._ctx.restore(); - }; - CursorRenderLayer.prototype._renderUnderlineCursor = function (terminal, x, y, charData) { - this._ctx.save(); - this._ctx.fillStyle = this._colors.cursor.css; - this.fillBottomLineAtCells(x, y); - this._ctx.restore(); - }; - CursorRenderLayer.prototype._renderBlurCursor = function (terminal, x, y, charData) { - this._ctx.save(); - this._ctx.strokeStyle = this._colors.cursor.css; - this.strokeRectAtCell(x, y, charData[Buffer_1.CHAR_DATA_WIDTH_INDEX], 1); - this._ctx.restore(); - }; - return CursorRenderLayer; -}(BaseRenderLayer_1.BaseRenderLayer)); -exports.CursorRenderLayer = CursorRenderLayer; -var CursorBlinkStateManager = (function () { - function CursorBlinkStateManager(terminal, _renderCallback) { - this._renderCallback = _renderCallback; - this.isCursorVisible = true; - if (terminal.isFocused) { - this._restartInterval(); - } - } - Object.defineProperty(CursorBlinkStateManager.prototype, "isPaused", { - get: function () { return !(this._blinkStartTimeout || this._blinkInterval); }, - enumerable: true, - configurable: true - }); - CursorBlinkStateManager.prototype.dispose = function () { - if (this._blinkInterval) { - window.clearInterval(this._blinkInterval); - this._blinkInterval = null; - } - if (this._blinkStartTimeout) { - window.clearTimeout(this._blinkStartTimeout); - this._blinkStartTimeout = null; - } - if (this._animationFrame) { - window.cancelAnimationFrame(this._animationFrame); - this._animationFrame = null; - } - }; - CursorBlinkStateManager.prototype.restartBlinkAnimation = function (terminal) { - var _this = this; - if (this.isPaused) { - return; - } - this._animationTimeRestarted = Date.now(); - this.isCursorVisible = true; - if (!this._animationFrame) { - this._animationFrame = window.requestAnimationFrame(function () { - _this._renderCallback(); - _this._animationFrame = null; - }); - } - }; - CursorBlinkStateManager.prototype._restartInterval = function (timeToStart) { - var _this = this; - if (timeToStart === void 0) { timeToStart = BLINK_INTERVAL; } - if (this._blinkInterval) { - window.clearInterval(this._blinkInterval); - } - this._blinkStartTimeout = setTimeout(function () { - if (_this._animationTimeRestarted) { - var time = BLINK_INTERVAL - (Date.now() - _this._animationTimeRestarted); - _this._animationTimeRestarted = null; - if (time > 0) { - _this._restartInterval(time); - return; - } - } - _this.isCursorVisible = false; - _this._animationFrame = window.requestAnimationFrame(function () { - _this._renderCallback(); - _this._animationFrame = null; - }); - _this._blinkInterval = setInterval(function () { - if (_this._animationTimeRestarted) { - var time = BLINK_INTERVAL - (Date.now() - _this._animationTimeRestarted); - _this._animationTimeRestarted = null; - _this._restartInterval(time); - return; - } - _this.isCursorVisible = !_this.isCursorVisible; - _this._animationFrame = window.requestAnimationFrame(function () { - _this._renderCallback(); - _this._animationFrame = null; - }); - }, BLINK_INTERVAL); - }, timeToStart); - }; - CursorBlinkStateManager.prototype.pause = function () { - this.isCursorVisible = true; - if (this._blinkInterval) { - window.clearInterval(this._blinkInterval); - this._blinkInterval = null; - } - if (this._blinkStartTimeout) { - window.clearTimeout(this._blinkStartTimeout); - this._blinkStartTimeout = null; - } - if (this._animationFrame) { - window.cancelAnimationFrame(this._animationFrame); - this._animationFrame = null; - } - }; - CursorBlinkStateManager.prototype.resume = function (terminal) { - this._animationTimeRestarted = null; - this._restartInterval(); - this.restartBlinkAnimation(terminal); - }; - return CursorBlinkStateManager; -}()); - -},{"../Buffer":2,"./BaseRenderLayer":26}],30:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var GridCache = (function () { - function GridCache() { - this.cache = []; - } - GridCache.prototype.resize = function (width, height) { - for (var x = 0; x < width; x++) { - if (this.cache.length <= x) { - this.cache.push([]); - } - for (var y = this.cache[x].length; y < height; y++) { - this.cache[x].push(null); - } - this.cache[x].length = height; - } - this.cache.length = width; - }; - GridCache.prototype.clear = function () { - for (var x = 0; x < this.cache.length; x++) { - for (var y = 0; y < this.cache[x].length; y++) { - this.cache[x][y] = null; - } - } - }; - return GridCache; -}()); -exports.GridCache = GridCache; - -},{}],31:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var BaseRenderLayer_1 = require("./BaseRenderLayer"); -var Types_1 = require("./atlas/Types"); -var CharAtlasUtils_1 = require("./atlas/CharAtlasUtils"); -var LinkRenderLayer = (function (_super) { - __extends(LinkRenderLayer, _super); - function LinkRenderLayer(container, zIndex, colors, terminal) { - var _this = _super.call(this, container, 'link', zIndex, true, colors) || this; - _this._state = null; - terminal.linkifier.on("linkhover", function (e) { return _this._onLinkHover(e); }); - terminal.linkifier.on("linkleave", function (e) { return _this._onLinkLeave(e); }); - return _this; - } - LinkRenderLayer.prototype.resize = function (terminal, dim) { - _super.prototype.resize.call(this, terminal, dim); - this._state = null; - }; - LinkRenderLayer.prototype.reset = function (terminal) { - this._clearCurrentLink(); - }; - LinkRenderLayer.prototype._clearCurrentLink = function () { - if (this._state) { - this.clearCells(this._state.x1, this._state.y1, this._state.cols - this._state.x1, 1); - var middleRowCount = this._state.y2 - this._state.y1 - 1; - if (middleRowCount > 0) { - this.clearCells(0, this._state.y1 + 1, this._state.cols, middleRowCount); - } - this.clearCells(0, this._state.y2, this._state.x2, 1); - this._state = null; - } - }; - LinkRenderLayer.prototype._onLinkHover = function (e) { - if (e.fg === Types_1.INVERTED_DEFAULT_COLOR) { - this._ctx.fillStyle = this._colors.background.css; - } - else if (CharAtlasUtils_1.is256Color(e.fg)) { - this._ctx.fillStyle = this._colors.ansi[e.fg].css; - } - else { - this._ctx.fillStyle = this._colors.foreground.css; - } - if (e.y1 === e.y2) { - this.fillBottomLineAtCells(e.x1, e.y1, e.x2 - e.x1); - } - else { - this.fillBottomLineAtCells(e.x1, e.y1, e.cols - e.x1); - for (var y = e.y1 + 1; y < e.y2; y++) { - this.fillBottomLineAtCells(0, y, e.cols); - } - this.fillBottomLineAtCells(0, e.y2, e.x2); - } - this._state = e; - }; - LinkRenderLayer.prototype._onLinkLeave = function (e) { - this._clearCurrentLink(); - }; - return LinkRenderLayer; -}(BaseRenderLayer_1.BaseRenderLayer)); -exports.LinkRenderLayer = LinkRenderLayer; - -},{"./BaseRenderLayer":26,"./atlas/CharAtlasUtils":38,"./atlas/Types":43}],32:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var TextRenderLayer_1 = require("./TextRenderLayer"); -var SelectionRenderLayer_1 = require("./SelectionRenderLayer"); -var CursorRenderLayer_1 = require("./CursorRenderLayer"); -var ColorManager_1 = require("./ColorManager"); -var LinkRenderLayer_1 = require("./LinkRenderLayer"); -var EventEmitter_1 = require("../common/EventEmitter"); -var RenderDebouncer_1 = require("../ui/RenderDebouncer"); -var ScreenDprMonitor_1 = require("../ui/ScreenDprMonitor"); -var CharacterJoinerRegistry_1 = require("../renderer/CharacterJoinerRegistry"); -var Renderer = (function (_super) { - __extends(Renderer, _super); - function Renderer(_terminal, theme) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._isPaused = false; - _this._needsFullRefresh = false; - var allowTransparency = _this._terminal.options.allowTransparency; - _this.colorManager = new ColorManager_1.ColorManager(document, allowTransparency); - _this._characterJoinerRegistry = new CharacterJoinerRegistry_1.CharacterJoinerRegistry(_terminal); - if (theme) { - _this.colorManager.setTheme(theme); - } - _this._renderLayers = [ - new TextRenderLayer_1.TextRenderLayer(_this._terminal.screenElement, 0, _this.colorManager.colors, _this._characterJoinerRegistry, allowTransparency), - new SelectionRenderLayer_1.SelectionRenderLayer(_this._terminal.screenElement, 1, _this.colorManager.colors), - new LinkRenderLayer_1.LinkRenderLayer(_this._terminal.screenElement, 2, _this.colorManager.colors, _this._terminal), - new CursorRenderLayer_1.CursorRenderLayer(_this._terminal.screenElement, 3, _this.colorManager.colors) - ]; - _this.dimensions = { - scaledCharWidth: null, - scaledCharHeight: null, - scaledCellWidth: null, - scaledCellHeight: null, - scaledCharLeft: null, - scaledCharTop: null, - scaledCanvasWidth: null, - scaledCanvasHeight: null, - canvasWidth: null, - canvasHeight: null, - actualCellWidth: null, - actualCellHeight: null - }; - _this._devicePixelRatio = window.devicePixelRatio; - _this._updateDimensions(); - _this.onOptionsChanged(); - _this._renderDebouncer = new RenderDebouncer_1.RenderDebouncer(_this._terminal, _this._renderRows.bind(_this)); - _this._screenDprMonitor = new ScreenDprMonitor_1.ScreenDprMonitor(); - _this._screenDprMonitor.setListener(function () { return _this.onWindowResize(window.devicePixelRatio); }); - _this.register(_this._screenDprMonitor); - if ('IntersectionObserver' in window) { - var observer_1 = new IntersectionObserver(function (e) { return _this.onIntersectionChange(e[0]); }, { threshold: 0 }); - observer_1.observe(_this._terminal.element); - _this.register({ dispose: function () { return observer_1.disconnect(); } }); - } - return _this; - } - Renderer.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._renderLayers.forEach(function (l) { return l.dispose(); }); - }; - Renderer.prototype.onIntersectionChange = function (entry) { - this._isPaused = entry.intersectionRatio === 0; - if (!this._isPaused && this._needsFullRefresh) { - this._terminal.refresh(0, this._terminal.rows - 1); - } - }; - Renderer.prototype.onWindowResize = function (devicePixelRatio) { - if (this._devicePixelRatio !== devicePixelRatio) { - this._devicePixelRatio = devicePixelRatio; - this.onResize(this._terminal.cols, this._terminal.rows); - } - }; - Renderer.prototype.setTheme = function (theme) { - var _this = this; - this.colorManager.setTheme(theme); - this._renderLayers.forEach(function (l) { - l.onThemeChanged(_this._terminal, _this.colorManager.colors); - l.reset(_this._terminal); - }); - if (this._isPaused) { - this._needsFullRefresh = true; - } - else { - this._terminal.refresh(0, this._terminal.rows - 1); - } - return this.colorManager.colors; - }; - Renderer.prototype.onResize = function (cols, rows) { - var _this = this; - this._updateDimensions(); - this._renderLayers.forEach(function (l) { return l.resize(_this._terminal, _this.dimensions); }); - if (this._isPaused) { - this._needsFullRefresh = true; - } - else { - this._terminal.refresh(0, this._terminal.rows - 1); - } - this._terminal.screenElement.style.width = this.dimensions.canvasWidth + "px"; - this._terminal.screenElement.style.height = this.dimensions.canvasHeight + "px"; - this.emit('resize', { - width: this.dimensions.canvasWidth, - height: this.dimensions.canvasHeight - }); - }; - Renderer.prototype.onCharSizeChanged = function () { - this.onResize(this._terminal.cols, this._terminal.rows); - }; - Renderer.prototype.onBlur = function () { - var _this = this; - this._runOperation(function (l) { return l.onBlur(_this._terminal); }); - }; - Renderer.prototype.onFocus = function () { - var _this = this; - this._runOperation(function (l) { return l.onFocus(_this._terminal); }); - }; - Renderer.prototype.onSelectionChanged = function (start, end, columnSelectMode) { - var _this = this; - if (columnSelectMode === void 0) { columnSelectMode = false; } - this._runOperation(function (l) { return l.onSelectionChanged(_this._terminal, start, end, columnSelectMode); }); - }; - Renderer.prototype.onCursorMove = function () { - var _this = this; - this._runOperation(function (l) { return l.onCursorMove(_this._terminal); }); - }; - Renderer.prototype.onOptionsChanged = function () { - var _this = this; - this.colorManager.allowTransparency = this._terminal.options.allowTransparency; - this._runOperation(function (l) { return l.onOptionsChanged(_this._terminal); }); - }; - Renderer.prototype.clear = function () { - var _this = this; - this._runOperation(function (l) { return l.reset(_this._terminal); }); - }; - Renderer.prototype._runOperation = function (operation) { - if (this._isPaused) { - this._needsFullRefresh = true; - } - else { - this._renderLayers.forEach(function (l) { return operation(l); }); - } - }; - Renderer.prototype.refreshRows = function (start, end) { - if (this._isPaused) { - this._needsFullRefresh = true; - return; - } - this._renderDebouncer.refresh(start, end); - }; - Renderer.prototype._renderRows = function (start, end) { - var _this = this; - this._renderLayers.forEach(function (l) { return l.onGridChanged(_this._terminal, start, end); }); - this._terminal.emit('refresh', { start: start, end: end }); - }; - Renderer.prototype._updateDimensions = function () { - if (!this._terminal.charMeasure.width || !this._terminal.charMeasure.height) { - return; - } - this.dimensions.scaledCharWidth = Math.floor(this._terminal.charMeasure.width * window.devicePixelRatio); - this.dimensions.scaledCharHeight = Math.ceil(this._terminal.charMeasure.height * window.devicePixelRatio); - this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight); - this.dimensions.scaledCharTop = this._terminal.options.lineHeight === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2); - this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing); - this.dimensions.scaledCharLeft = Math.floor(this._terminal.options.letterSpacing / 2); - this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight; - this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth; - this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio); - this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio); - this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows; - this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols; - }; - Renderer.prototype.registerCharacterJoiner = function (handler) { - return this._characterJoinerRegistry.registerCharacterJoiner(handler); - }; - Renderer.prototype.deregisterCharacterJoiner = function (joinerId) { - return this._characterJoinerRegistry.deregisterCharacterJoiner(joinerId); - }; - return Renderer; -}(EventEmitter_1.EventEmitter)); -exports.Renderer = Renderer; - -},{"../common/EventEmitter":17,"../renderer/CharacterJoinerRegistry":27,"../ui/RenderDebouncer":50,"../ui/ScreenDprMonitor":51,"./ColorManager":28,"./CursorRenderLayer":29,"./LinkRenderLayer":31,"./SelectionRenderLayer":33,"./TextRenderLayer":34}],33:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var BaseRenderLayer_1 = require("./BaseRenderLayer"); -var SelectionRenderLayer = (function (_super) { - __extends(SelectionRenderLayer, _super); - function SelectionRenderLayer(container, zIndex, colors) { - var _this = _super.call(this, container, 'selection', zIndex, true, colors) || this; - _this._clearState(); - return _this; - } - SelectionRenderLayer.prototype._clearState = function () { - this._state = { - start: null, - end: null, - columnSelectMode: null, - ydisp: null - }; - }; - SelectionRenderLayer.prototype.resize = function (terminal, dim) { - _super.prototype.resize.call(this, terminal, dim); - this._clearState(); - }; - SelectionRenderLayer.prototype.reset = function (terminal) { - if (this._state.start && this._state.end) { - this._clearState(); - this.clearAll(); - } - }; - SelectionRenderLayer.prototype.onSelectionChanged = function (terminal, start, end, columnSelectMode) { - if (!this._didStateChange(start, end, columnSelectMode, terminal.buffer.ydisp)) { - return; - } - this.clearAll(); - if (!start || !end) { - return; - } - var viewportStartRow = start[1] - terminal.buffer.ydisp; - var viewportEndRow = end[1] - terminal.buffer.ydisp; - var viewportCappedStartRow = Math.max(viewportStartRow, 0); - var viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1); - if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) { - return; - } - this._ctx.fillStyle = this._colors.selection.css; - if (columnSelectMode) { - var startCol = start[0]; - var width = end[0] - startCol; - var height = viewportCappedEndRow - viewportCappedStartRow + 1; - this.fillCells(startCol, viewportCappedStartRow, width, height); - } - else { - var startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0; - var startRowEndCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : terminal.cols; - this.fillCells(startCol, viewportCappedStartRow, startRowEndCol - startCol, 1); - var middleRowsCount = Math.max(viewportCappedEndRow - viewportCappedStartRow - 1, 0); - this.fillCells(0, viewportCappedStartRow + 1, terminal.cols, middleRowsCount); - if (viewportCappedStartRow !== viewportCappedEndRow) { - var endCol = viewportEndRow === viewportCappedEndRow ? end[0] : terminal.cols; - this.fillCells(0, viewportCappedEndRow, endCol, 1); - } - } - this._state.start = [start[0], start[1]]; - this._state.end = [end[0], end[1]]; - this._state.columnSelectMode = columnSelectMode; - this._state.ydisp = terminal.buffer.ydisp; - }; - SelectionRenderLayer.prototype._didStateChange = function (start, end, columnSelectMode, ydisp) { - return !this._areCoordinatesEqual(start, this._state.start) || - !this._areCoordinatesEqual(end, this._state.end) || - columnSelectMode !== this._state.columnSelectMode || - ydisp !== this._state.ydisp; - }; - SelectionRenderLayer.prototype._areCoordinatesEqual = function (coord1, coord2) { - if (!coord1 || !coord2) { - return false; - } - return coord1[0] === coord2[0] && coord1[1] === coord2[1]; - }; - return SelectionRenderLayer; -}(BaseRenderLayer_1.BaseRenderLayer)); -exports.SelectionRenderLayer = SelectionRenderLayer; - -},{"./BaseRenderLayer":26}],34:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("../Buffer"); -var Types_1 = require("./atlas/Types"); -var GridCache_1 = require("./GridCache"); -var BaseRenderLayer_1 = require("./BaseRenderLayer"); -var CharAtlasUtils_1 = require("./atlas/CharAtlasUtils"); -var TextRenderLayer = (function (_super) { - __extends(TextRenderLayer, _super); - function TextRenderLayer(container, zIndex, colors, characterJoinerRegistry, alpha) { - var _this = _super.call(this, container, 'text', zIndex, alpha, colors) || this; - _this._characterOverlapCache = {}; - _this._state = new GridCache_1.GridCache(); - _this._characterJoinerRegistry = characterJoinerRegistry; - return _this; - } - TextRenderLayer.prototype.resize = function (terminal, dim) { - _super.prototype.resize.call(this, terminal, dim); - var terminalFont = this._getFont(terminal, false, false); - if (this._characterWidth !== dim.scaledCharWidth || this._characterFont !== terminalFont) { - this._characterWidth = dim.scaledCharWidth; - this._characterFont = terminalFont; - this._characterOverlapCache = {}; - } - this._state.clear(); - this._state.resize(terminal.cols, terminal.rows); - }; - TextRenderLayer.prototype.reset = function (terminal) { - this._state.clear(); - this.clearAll(); - }; - TextRenderLayer.prototype._forEachCell = function (terminal, firstRow, lastRow, joinerRegistry, callback) { - for (var y = firstRow; y <= lastRow; y++) { - var row = y + terminal.buffer.ydisp; - var line = terminal.buffer.lines.get(row); - var joinedRanges = joinerRegistry ? joinerRegistry.getJoinedCharacters(row) : []; - for (var x = 0; x < terminal.cols; x++) { - var charData = line.get(x); - var code = charData[Buffer_1.CHAR_DATA_CODE_INDEX]; - var chars = charData[Buffer_1.CHAR_DATA_CHAR_INDEX]; - var attr = charData[Buffer_1.CHAR_DATA_ATTR_INDEX]; - var width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - var isJoined = false; - var lastCharX = x; - if (width === 0) { - continue; - } - if (joinedRanges.length > 0 && x === joinedRanges[0][0]) { - isJoined = true; - var range = joinedRanges.shift(); - chars = terminal.buffer.translateBufferLineToString(row, true, range[0], range[1]); - width = range[1] - range[0]; - code = Infinity; - lastCharX = range[1] - 1; - } - if (!isJoined && this._isOverlapping(charData)) { - if (lastCharX < line.length - 1 && line.get(lastCharX + 1)[Buffer_1.CHAR_DATA_CODE_INDEX] === Buffer_1.NULL_CELL_CODE) { - width = 2; - } - } - var flags = attr >> 18; - var bg = attr & 0x1ff; - var fg = (attr >> 9) & 0x1ff; - if (flags & 8) { - var temp = bg; - bg = fg; - fg = temp; - if (fg === Types_1.DEFAULT_COLOR) { - fg = Types_1.INVERTED_DEFAULT_COLOR; - } - if (bg === Types_1.DEFAULT_COLOR) { - bg = Types_1.INVERTED_DEFAULT_COLOR; - } - } - callback(code, chars, width, x, y, fg, bg, flags); - x = lastCharX; - } - } - }; - TextRenderLayer.prototype._drawBackground = function (terminal, firstRow, lastRow) { - var _this = this; - var ctx = this._ctx; - var cols = terminal.cols; - var startX = 0; - var startY = 0; - var prevFillStyle = null; - ctx.save(); - this._forEachCell(terminal, firstRow, lastRow, null, function (code, chars, width, x, y, fg, bg, flags) { - var nextFillStyle = null; - if (bg === Types_1.INVERTED_DEFAULT_COLOR) { - nextFillStyle = _this._colors.foreground.css; - } - else if (CharAtlasUtils_1.is256Color(bg)) { - nextFillStyle = _this._colors.ansi[bg].css; - } - if (prevFillStyle === null) { - startX = x; - startY = y; - } - if (y !== startY) { - ctx.fillStyle = prevFillStyle; - _this.fillCells(startX, startY, cols - startX, 1); - startX = x; - startY = y; - } - else if (prevFillStyle !== nextFillStyle) { - ctx.fillStyle = prevFillStyle; - _this.fillCells(startX, startY, x - startX, 1); - startX = x; - startY = y; - } - prevFillStyle = nextFillStyle; - }); - if (prevFillStyle !== null) { - ctx.fillStyle = prevFillStyle; - this.fillCells(startX, startY, cols - startX, 1); - } - ctx.restore(); - }; - TextRenderLayer.prototype._drawForeground = function (terminal, firstRow, lastRow) { - var _this = this; - this._forEachCell(terminal, firstRow, lastRow, this._characterJoinerRegistry, function (code, chars, width, x, y, fg, bg, flags) { - if (flags & 16) { - return; - } - if (flags & 2) { - _this._ctx.save(); - if (fg === Types_1.INVERTED_DEFAULT_COLOR) { - _this._ctx.fillStyle = _this._colors.background.css; - } - else if (CharAtlasUtils_1.is256Color(fg)) { - _this._ctx.fillStyle = _this._colors.ansi[fg].css; - } - else { - _this._ctx.fillStyle = _this._colors.foreground.css; - } - _this.fillBottomLineAtCells(x, y, width); - _this._ctx.restore(); - } - _this.drawChars(terminal, chars, code, width, x, y, fg, bg, !!(flags & 1), !!(flags & 32), !!(flags & 64)); - }); - }; - TextRenderLayer.prototype.onGridChanged = function (terminal, firstRow, lastRow) { - if (this._state.cache.length === 0) { - return; - } - if (this._charAtlas) { - this._charAtlas.beginFrame(); - } - this.clearCells(0, firstRow, terminal.cols, lastRow - firstRow + 1); - this._drawBackground(terminal, firstRow, lastRow); - this._drawForeground(terminal, firstRow, lastRow); - }; - TextRenderLayer.prototype.onOptionsChanged = function (terminal) { - this.setTransparency(terminal, terminal.options.allowTransparency); - }; - TextRenderLayer.prototype._isOverlapping = function (charData) { - if (charData[Buffer_1.CHAR_DATA_WIDTH_INDEX] !== 1) { - return false; - } - var code = charData[Buffer_1.CHAR_DATA_CODE_INDEX]; - if (code < 256) { - return false; - } - var char = charData[Buffer_1.CHAR_DATA_CHAR_INDEX]; - if (this._characterOverlapCache.hasOwnProperty(char)) { - return this._characterOverlapCache[char]; - } - this._ctx.save(); - this._ctx.font = this._characterFont; - var overlaps = Math.floor(this._ctx.measureText(char).width) > this._characterWidth; - this._ctx.restore(); - this._characterOverlapCache[char] = overlaps; - return overlaps; - }; - return TextRenderLayer; -}(BaseRenderLayer_1.BaseRenderLayer)); -exports.TextRenderLayer = TextRenderLayer; - -},{"../Buffer":2,"./BaseRenderLayer":26,"./GridCache":30,"./atlas/CharAtlasUtils":38,"./atlas/Types":43}],35:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var BaseCharAtlas = (function () { - function BaseCharAtlas() { - this._didWarmUp = false; - } - BaseCharAtlas.prototype.dispose = function () { }; - BaseCharAtlas.prototype.warmUp = function () { - if (!this._didWarmUp) { - this._doWarmUp(); - this._didWarmUp = true; - } - }; - BaseCharAtlas.prototype._doWarmUp = function () { }; - BaseCharAtlas.prototype.beginFrame = function () { }; - return BaseCharAtlas; -}()); -exports.default = BaseCharAtlas; - -},{}],36:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var CharAtlasUtils_1 = require("./CharAtlasUtils"); -var DynamicCharAtlas_1 = require("./DynamicCharAtlas"); -var NoneCharAtlas_1 = require("./NoneCharAtlas"); -var StaticCharAtlas_1 = require("./StaticCharAtlas"); -var charAtlasImplementations = { - 'none': NoneCharAtlas_1.default, - 'static': StaticCharAtlas_1.default, - 'dynamic': DynamicCharAtlas_1.default -}; -var charAtlasCache = []; -function acquireCharAtlas(terminal, colors, scaledCharWidth, scaledCharHeight) { - var newConfig = CharAtlasUtils_1.generateConfig(scaledCharWidth, scaledCharHeight, terminal, colors); - for (var i = 0; i < charAtlasCache.length; i++) { - var entry = charAtlasCache[i]; - var ownedByIndex = entry.ownedBy.indexOf(terminal); - if (ownedByIndex >= 0) { - if (CharAtlasUtils_1.configEquals(entry.config, newConfig)) { - return entry.atlas; - } - if (entry.ownedBy.length === 1) { - charAtlasCache.splice(i, 1); - } - else { - entry.ownedBy.splice(ownedByIndex, 1); - } - break; - } - } - for (var i = 0; i < charAtlasCache.length; i++) { - var entry = charAtlasCache[i]; - if (CharAtlasUtils_1.configEquals(entry.config, newConfig)) { - entry.ownedBy.push(terminal); - return entry.atlas; - } - } - var newEntry = { - atlas: new charAtlasImplementations[terminal.options.experimentalCharAtlas](document, newConfig), - config: newConfig, - ownedBy: [terminal] - }; - charAtlasCache.push(newEntry); - return newEntry.atlas; -} -exports.acquireCharAtlas = acquireCharAtlas; -function removeTerminalFromCache(terminal) { - for (var i = 0; i < charAtlasCache.length; i++) { - var index = charAtlasCache[i].ownedBy.indexOf(terminal); - if (index !== -1) { - if (charAtlasCache[i].ownedBy.length === 1) { - charAtlasCache.splice(i, 1); - } - else { - charAtlasCache[i].ownedBy.splice(index, 1); - } - break; - } - } -} -exports.removeTerminalFromCache = removeTerminalFromCache; - -},{"./CharAtlasUtils":38,"./DynamicCharAtlas":39,"./NoneCharAtlas":41,"./StaticCharAtlas":42}],37:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Platform_1 = require("../../core/Platform"); -var Types_1 = require("./Types"); -function generateStaticCharAtlasTexture(context, canvasFactory, config) { - var cellWidth = config.scaledCharWidth + Types_1.CHAR_ATLAS_CELL_SPACING; - var cellHeight = config.scaledCharHeight + Types_1.CHAR_ATLAS_CELL_SPACING; - var canvas = canvasFactory(255 * cellWidth, (2 + 16 + 16) * cellHeight); - var ctx = canvas.getContext('2d', { alpha: config.allowTransparency }); - ctx.fillStyle = config.colors.background.css; - ctx.fillRect(0, 0, canvas.width, canvas.height); - ctx.save(); - ctx.fillStyle = config.colors.foreground.css; - ctx.font = getFont(config.fontWeight, config); - ctx.textBaseline = 'top'; - for (var i = 0; i < 256; i++) { - ctx.save(); - ctx.beginPath(); - ctx.rect(i * cellWidth, 0, cellWidth, cellHeight); - ctx.clip(); - ctx.fillText(String.fromCharCode(i), i * cellWidth, 0); - ctx.restore(); - } - ctx.save(); - ctx.font = getFont(config.fontWeightBold, config); - for (var i = 0; i < 256; i++) { - ctx.save(); - ctx.beginPath(); - ctx.rect(i * cellWidth, cellHeight, cellWidth, cellHeight); - ctx.clip(); - ctx.fillText(String.fromCharCode(i), i * cellWidth, cellHeight); - ctx.restore(); - } - ctx.restore(); - ctx.font = getFont(config.fontWeight, config); - for (var colorIndex = 0; colorIndex < 16; colorIndex++) { - var y = (colorIndex + 2) * cellHeight; - for (var i = 0; i < 256; i++) { - ctx.save(); - ctx.beginPath(); - ctx.rect(i * cellWidth, y, cellWidth, cellHeight); - ctx.clip(); - ctx.fillStyle = config.colors.ansi[colorIndex].css; - ctx.fillText(String.fromCharCode(i), i * cellWidth, y); - ctx.restore(); - } - } - ctx.font = getFont(config.fontWeightBold, config); - for (var colorIndex = 0; colorIndex < 16; colorIndex++) { - var y = (colorIndex + 2 + 16) * cellHeight; - for (var i = 0; i < 256; i++) { - ctx.save(); - ctx.beginPath(); - ctx.rect(i * cellWidth, y, cellWidth, cellHeight); - ctx.clip(); - ctx.fillStyle = config.colors.ansi[colorIndex].css; - ctx.fillText(String.fromCharCode(i), i * cellWidth, y); - ctx.restore(); - } - } - ctx.restore(); - if (!('createImageBitmap' in context) || Platform_1.isFirefox || Platform_1.isSafari) { - return canvas; - } - var charAtlasImageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - clearColor(charAtlasImageData, config.colors.background); - return context.createImageBitmap(charAtlasImageData); -} -exports.generateStaticCharAtlasTexture = generateStaticCharAtlasTexture; -function clearColor(imageData, color) { - var isEmpty = true; - var r = color.rgba >>> 24; - var g = color.rgba >>> 16 & 0xFF; - var b = color.rgba >>> 8 & 0xFF; - for (var offset = 0; offset < imageData.data.length; offset += 4) { - if (imageData.data[offset] === r && - imageData.data[offset + 1] === g && - imageData.data[offset + 2] === b) { - imageData.data[offset + 3] = 0; - } - else { - isEmpty = false; - } - } - return isEmpty; -} -exports.clearColor = clearColor; -function getFont(fontWeight, config) { - return fontWeight + " " + config.fontSize * config.devicePixelRatio + "px " + config.fontFamily; -} - -},{"../../core/Platform":21,"./Types":43}],38:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Types_1 = require("./Types"); -function generateConfig(scaledCharWidth, scaledCharHeight, terminal, colors) { - var clonedColors = { - foreground: colors.foreground, - background: colors.background, - cursor: null, - cursorAccent: null, - selection: null, - ansi: colors.ansi.slice(0, 16) - }; - return { - type: terminal.options.experimentalCharAtlas, - devicePixelRatio: window.devicePixelRatio, - scaledCharWidth: scaledCharWidth, - scaledCharHeight: scaledCharHeight, - fontFamily: terminal.options.fontFamily, - fontSize: terminal.options.fontSize, - fontWeight: terminal.options.fontWeight, - fontWeightBold: terminal.options.fontWeightBold, - allowTransparency: terminal.options.allowTransparency, - colors: clonedColors - }; -} -exports.generateConfig = generateConfig; -function configEquals(a, b) { - for (var i = 0; i < a.colors.ansi.length; i++) { - if (a.colors.ansi[i].rgba !== b.colors.ansi[i].rgba) { - return false; - } - } - return a.type === b.type && - a.devicePixelRatio === b.devicePixelRatio && - a.fontFamily === b.fontFamily && - a.fontSize === b.fontSize && - a.fontWeight === b.fontWeight && - a.fontWeightBold === b.fontWeightBold && - a.allowTransparency === b.allowTransparency && - a.scaledCharWidth === b.scaledCharWidth && - a.scaledCharHeight === b.scaledCharHeight && - a.colors.foreground === b.colors.foreground && - a.colors.background === b.colors.background; -} -exports.configEquals = configEquals; -function is256Color(colorCode) { - return colorCode < Types_1.DEFAULT_COLOR; -} -exports.is256Color = is256Color; - -},{"./Types":43}],39:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Types_1 = require("./Types"); -var BaseCharAtlas_1 = require("./BaseCharAtlas"); -var ColorManager_1 = require("../ColorManager"); -var CharAtlasGenerator_1 = require("./CharAtlasGenerator"); -var LRUMap_1 = require("./LRUMap"); -var Platform_1 = require("../../core/Platform"); -var TEXTURE_WIDTH = 1024; -var TEXTURE_HEIGHT = 1024; -var TRANSPARENT_COLOR = { - css: 'rgba(0, 0, 0, 0)', - rgba: 0 -}; -var FRAME_CACHE_DRAW_LIMIT = 100; -var GLYPH_BITMAP_COMMIT_DELAY = 100; -function getGlyphCacheKey(glyph) { - return glyph.code << 21 | glyph.bg << 12 | glyph.fg << 3 | (glyph.bold ? 0 : 4) + (glyph.dim ? 0 : 2) + (glyph.italic ? 0 : 1); -} -exports.getGlyphCacheKey = getGlyphCacheKey; -var DynamicCharAtlas = (function (_super) { - __extends(DynamicCharAtlas, _super); - function DynamicCharAtlas(document, _config) { - var _this = _super.call(this) || this; - _this._config = _config; - _this._drawToCacheCount = 0; - _this._glyphsWaitingOnBitmap = []; - _this._bitmapCommitTimeout = null; - _this._bitmap = null; - _this._cacheCanvas = document.createElement('canvas'); - _this._cacheCanvas.width = TEXTURE_WIDTH; - _this._cacheCanvas.height = TEXTURE_HEIGHT; - _this._cacheCtx = _this._cacheCanvas.getContext('2d', { alpha: true }); - var tmpCanvas = document.createElement('canvas'); - tmpCanvas.width = _this._config.scaledCharWidth; - tmpCanvas.height = _this._config.scaledCharHeight; - _this._tmpCtx = tmpCanvas.getContext('2d', { alpha: _this._config.allowTransparency }); - _this._width = Math.floor(TEXTURE_WIDTH / _this._config.scaledCharWidth); - _this._height = Math.floor(TEXTURE_HEIGHT / _this._config.scaledCharHeight); - var capacity = _this._width * _this._height; - _this._cacheMap = new LRUMap_1.default(capacity); - _this._cacheMap.prealloc(capacity); - return _this; - } - DynamicCharAtlas.prototype.dispose = function () { - if (this._bitmapCommitTimeout !== null) { - window.clearTimeout(this._bitmapCommitTimeout); - this._bitmapCommitTimeout = null; - } - }; - DynamicCharAtlas.prototype.beginFrame = function () { - this._drawToCacheCount = 0; - }; - DynamicCharAtlas.prototype.draw = function (ctx, glyph, x, y) { - if (glyph.code === 32) { - return true; - } - if (!this._canCache(glyph)) { - return false; - } - var glyphKey = getGlyphCacheKey(glyph); - var cacheValue = this._cacheMap.get(glyphKey); - if (cacheValue !== null && cacheValue !== undefined) { - this._drawFromCache(ctx, cacheValue, x, y); - return true; - } - else if (this._drawToCacheCount < FRAME_CACHE_DRAW_LIMIT) { - var index = void 0; - if (this._cacheMap.size < this._cacheMap.capacity) { - index = this._cacheMap.size; - } - else { - index = this._cacheMap.peek().index; - } - var cacheValue_1 = this._drawToCache(glyph, index); - this._cacheMap.set(glyphKey, cacheValue_1); - this._drawFromCache(ctx, cacheValue_1, x, y); - return true; - } - return false; - }; - DynamicCharAtlas.prototype._canCache = function (glyph) { - return glyph.code < 256; - }; - DynamicCharAtlas.prototype._toCoordinateX = function (index) { - return (index % this._width) * this._config.scaledCharWidth; - }; - DynamicCharAtlas.prototype._toCoordinateY = function (index) { - return Math.floor(index / this._width) * this._config.scaledCharHeight; - }; - DynamicCharAtlas.prototype._drawFromCache = function (ctx, cacheValue, x, y) { - if (cacheValue.isEmpty) { - return; - } - var cacheX = this._toCoordinateX(cacheValue.index); - var cacheY = this._toCoordinateY(cacheValue.index); - ctx.drawImage(cacheValue.inBitmap ? this._bitmap : this._cacheCanvas, cacheX, cacheY, this._config.scaledCharWidth, this._config.scaledCharHeight, x, y, this._config.scaledCharWidth, this._config.scaledCharHeight); - }; - DynamicCharAtlas.prototype._getColorFromAnsiIndex = function (idx) { - if (idx < this._config.colors.ansi.length) { - return this._config.colors.ansi[idx]; - } - return ColorManager_1.DEFAULT_ANSI_COLORS[idx]; - }; - DynamicCharAtlas.prototype._getBackgroundColor = function (glyph) { - if (this._config.allowTransparency) { - return TRANSPARENT_COLOR; - } - else if (glyph.bg === Types_1.INVERTED_DEFAULT_COLOR) { - return this._config.colors.foreground; - } - else if (glyph.bg < 256) { - return this._getColorFromAnsiIndex(glyph.bg); - } - return this._config.colors.background; - }; - DynamicCharAtlas.prototype._getForegroundColor = function (glyph) { - if (glyph.fg === Types_1.INVERTED_DEFAULT_COLOR) { - return this._config.colors.background; - } - else if (glyph.fg < 256) { - return this._getColorFromAnsiIndex(glyph.fg); - } - return this._config.colors.foreground; - }; - DynamicCharAtlas.prototype._drawToCache = function (glyph, index) { - this._drawToCacheCount++; - this._tmpCtx.save(); - var backgroundColor = this._getBackgroundColor(glyph); - this._tmpCtx.globalCompositeOperation = 'copy'; - this._tmpCtx.fillStyle = backgroundColor.css; - this._tmpCtx.fillRect(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight); - this._tmpCtx.globalCompositeOperation = 'source-over'; - var fontWeight = glyph.bold ? this._config.fontWeightBold : this._config.fontWeight; - var fontStyle = glyph.italic ? 'italic' : ''; - this._tmpCtx.font = - fontStyle + " " + fontWeight + " " + this._config.fontSize * this._config.devicePixelRatio + "px " + this._config.fontFamily; - this._tmpCtx.textBaseline = 'top'; - this._tmpCtx.fillStyle = this._getForegroundColor(glyph).css; - if (glyph.dim) { - this._tmpCtx.globalAlpha = Types_1.DIM_OPACITY; - } - this._tmpCtx.fillText(glyph.chars, 0, 0); - this._tmpCtx.restore(); - var imageData = this._tmpCtx.getImageData(0, 0, this._config.scaledCharWidth, this._config.scaledCharHeight); - var isEmpty = false; - if (!this._config.allowTransparency) { - isEmpty = CharAtlasGenerator_1.clearColor(imageData, backgroundColor); - } - var x = this._toCoordinateX(index); - var y = this._toCoordinateY(index); - this._cacheCtx.putImageData(imageData, x, y); - var cacheValue = { - index: index, - isEmpty: isEmpty, - inBitmap: false - }; - this._addGlyphToBitmap(cacheValue); - return cacheValue; - }; - DynamicCharAtlas.prototype._addGlyphToBitmap = function (cacheValue) { - var _this = this; - if (!('createImageBitmap' in window) || Platform_1.isFirefox || Platform_1.isSafari) { - return; - } - this._glyphsWaitingOnBitmap.push(cacheValue); - if (this._bitmapCommitTimeout !== null) { - return; - } - this._bitmapCommitTimeout = window.setTimeout(function () { return _this._generateBitmap(); }, GLYPH_BITMAP_COMMIT_DELAY); - }; - DynamicCharAtlas.prototype._generateBitmap = function () { - var _this = this; - var glyphsMovingToBitmap = this._glyphsWaitingOnBitmap; - this._glyphsWaitingOnBitmap = []; - window.createImageBitmap(this._cacheCanvas).then(function (bitmap) { - _this._bitmap = bitmap; - for (var i = 0; i < glyphsMovingToBitmap.length; i++) { - var value = glyphsMovingToBitmap[i]; - value.inBitmap = true; - } - }); - this._bitmapCommitTimeout = null; - }; - return DynamicCharAtlas; -}(BaseCharAtlas_1.default)); -exports.default = DynamicCharAtlas; - -},{"../../core/Platform":21,"../ColorManager":28,"./BaseCharAtlas":35,"./CharAtlasGenerator":37,"./LRUMap":40,"./Types":43}],40:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var LRUMap = (function () { - function LRUMap(capacity) { - this.capacity = capacity; - this._map = {}; - this._head = null; - this._tail = null; - this._nodePool = []; - this.size = 0; - } - LRUMap.prototype._unlinkNode = function (node) { - var prev = node.prev; - var next = node.next; - if (node === this._head) { - this._head = next; - } - if (node === this._tail) { - this._tail = prev; - } - if (prev !== null) { - prev.next = next; - } - if (next !== null) { - next.prev = prev; - } - }; - LRUMap.prototype._appendNode = function (node) { - var tail = this._tail; - if (tail !== null) { - tail.next = node; - } - node.prev = tail; - node.next = null; - this._tail = node; - if (this._head === null) { - this._head = node; - } - }; - LRUMap.prototype.prealloc = function (count) { - var nodePool = this._nodePool; - for (var i = 0; i < count; i++) { - nodePool.push({ - prev: null, - next: null, - key: null, - value: null - }); - } - }; - LRUMap.prototype.get = function (key) { - var node = this._map[key]; - if (node !== undefined) { - this._unlinkNode(node); - this._appendNode(node); - return node.value; - } - return null; - }; - LRUMap.prototype.peekValue = function (key) { - var node = this._map[key]; - if (node !== undefined) { - return node.value; - } - return null; - }; - LRUMap.prototype.peek = function () { - var head = this._head; - return head === null ? null : head.value; - }; - LRUMap.prototype.set = function (key, value) { - var node = this._map[key]; - if (node !== undefined) { - node = this._map[key]; - this._unlinkNode(node); - node.value = value; - } - else if (this.size >= this.capacity) { - node = this._head; - this._unlinkNode(node); - delete this._map[node.key]; - node.key = key; - node.value = value; - this._map[key] = node; - } - else { - var nodePool = this._nodePool; - if (nodePool.length > 0) { - node = nodePool.pop(); - node.key = key; - node.value = value; - } - else { - node = { - prev: null, - next: null, - key: key, - value: value - }; - } - this._map[key] = node; - this.size++; - } - this._appendNode(node); - }; - return LRUMap; -}()); -exports.default = LRUMap; - -},{}],41:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var BaseCharAtlas_1 = require("./BaseCharAtlas"); -var NoneCharAtlas = (function (_super) { - __extends(NoneCharAtlas, _super); - function NoneCharAtlas(document, config) { - return _super.call(this) || this; - } - NoneCharAtlas.prototype.draw = function (ctx, glyph, x, y) { - return false; - }; - return NoneCharAtlas; -}(BaseCharAtlas_1.default)); -exports.default = NoneCharAtlas; - -},{"./BaseCharAtlas":35}],42:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Types_1 = require("./Types"); -var CharAtlasGenerator_1 = require("./CharAtlasGenerator"); -var BaseCharAtlas_1 = require("./BaseCharAtlas"); -var CharAtlasUtils_1 = require("./CharAtlasUtils"); -var StaticCharAtlas = (function (_super) { - __extends(StaticCharAtlas, _super); - function StaticCharAtlas(_document, _config) { - var _this = _super.call(this) || this; - _this._document = _document; - _this._config = _config; - _this._canvasFactory = function (width, height) { - var canvas = _this._document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - return canvas; - }; - return _this; - } - StaticCharAtlas.prototype._doWarmUp = function () { - var _this = this; - var result = CharAtlasGenerator_1.generateStaticCharAtlasTexture(window, this._canvasFactory, this._config); - if (result instanceof HTMLCanvasElement) { - this._texture = result; - } - else { - result.then(function (texture) { - _this._texture = texture; - }); - } - }; - StaticCharAtlas.prototype._isCached = function (glyph, colorIndex) { - var isAscii = glyph.code < 256; - var isBasicColor = glyph.fg < 16; - var isDefaultColor = glyph.fg === Types_1.DEFAULT_COLOR; - var isDefaultBackground = glyph.bg === Types_1.DEFAULT_COLOR; - return isAscii && (isBasicColor || isDefaultColor) && isDefaultBackground && !glyph.italic; - }; - StaticCharAtlas.prototype.draw = function (ctx, glyph, x, y) { - if (this._texture === null || this._texture === undefined) { - return false; - } - var colorIndex = 0; - if (CharAtlasUtils_1.is256Color(glyph.fg)) { - colorIndex = 2 + glyph.fg + (glyph.bold ? 16 : 0); - } - else if (glyph.fg === Types_1.DEFAULT_COLOR) { - if (glyph.bold) { - colorIndex = 1; - } - } - if (!this._isCached(glyph, colorIndex)) { - return false; - } - ctx.save(); - var charAtlasCellWidth = this._config.scaledCharWidth + Types_1.CHAR_ATLAS_CELL_SPACING; - var charAtlasCellHeight = this._config.scaledCharHeight + Types_1.CHAR_ATLAS_CELL_SPACING; - if (glyph.dim) { - ctx.globalAlpha = Types_1.DIM_OPACITY; - } - ctx.drawImage(this._texture, glyph.code * charAtlasCellWidth, colorIndex * charAtlasCellHeight, charAtlasCellWidth, this._config.scaledCharHeight, x, y, charAtlasCellWidth, this._config.scaledCharHeight); - ctx.restore(); - return true; - }; - return StaticCharAtlas; -}(BaseCharAtlas_1.default)); -exports.default = StaticCharAtlas; - -},{"./BaseCharAtlas":35,"./CharAtlasGenerator":37,"./CharAtlasUtils":38,"./Types":43}],43:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_COLOR = 256; -exports.INVERTED_DEFAULT_COLOR = 257; -exports.DIM_OPACITY = 0.5; -exports.CHAR_ATLAS_CELL_SPACING = 1; - -},{}],44:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var EventEmitter_1 = require("../../common/EventEmitter"); -var ColorManager_1 = require("../ColorManager"); -var RenderDebouncer_1 = require("../../ui/RenderDebouncer"); -var DomRendererRowFactory_1 = require("./DomRendererRowFactory"); -var Types_1 = require("../atlas/Types"); -var TERMINAL_CLASS_PREFIX = 'xterm-dom-renderer-owner-'; -var ROW_CONTAINER_CLASS = 'xterm-rows'; -var FG_CLASS_PREFIX = 'xterm-fg-'; -var BG_CLASS_PREFIX = 'xterm-bg-'; -var FOCUS_CLASS = 'xterm-focus'; -var SELECTION_CLASS = 'xterm-selection'; -var nextTerminalId = 1; -var DomRenderer = (function (_super) { - __extends(DomRenderer, _super); - function DomRenderer(_terminal, theme) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._terminalClass = nextTerminalId++; - _this._rowElements = []; - var allowTransparency = _this._terminal.options.allowTransparency; - _this.colorManager = new ColorManager_1.ColorManager(document, allowTransparency); - _this.setTheme(theme); - _this._rowContainer = document.createElement('div'); - _this._rowContainer.classList.add(ROW_CONTAINER_CLASS); - _this._rowContainer.style.lineHeight = 'normal'; - _this._rowContainer.setAttribute('aria-hidden', 'true'); - _this._refreshRowElements(_this._terminal.cols, _this._terminal.rows); - _this._selectionContainer = document.createElement('div'); - _this._selectionContainer.classList.add(SELECTION_CLASS); - _this._selectionContainer.setAttribute('aria-hidden', 'true'); - _this.dimensions = { - scaledCharWidth: null, - scaledCharHeight: null, - scaledCellWidth: null, - scaledCellHeight: null, - scaledCharLeft: null, - scaledCharTop: null, - scaledCanvasWidth: null, - scaledCanvasHeight: null, - canvasWidth: null, - canvasHeight: null, - actualCellWidth: null, - actualCellHeight: null - }; - _this._updateDimensions(); - _this._renderDebouncer = new RenderDebouncer_1.RenderDebouncer(_this._terminal, _this._renderRows.bind(_this)); - _this._rowFactory = new DomRendererRowFactory_1.DomRendererRowFactory(document); - _this._terminal.element.classList.add(TERMINAL_CLASS_PREFIX + _this._terminalClass); - _this._terminal.screenElement.appendChild(_this._rowContainer); - _this._terminal.screenElement.appendChild(_this._selectionContainer); - _this._terminal.linkifier.on("linkhover", function (e) { return _this._onLinkHover(e); }); - _this._terminal.linkifier.on("linkleave", function (e) { return _this._onLinkLeave(e); }); - return _this; - } - DomRenderer.prototype.dispose = function () { - this._terminal.element.classList.remove(TERMINAL_CLASS_PREFIX + this._terminalClass); - this._terminal.screenElement.removeChild(this._rowContainer); - this._terminal.screenElement.removeChild(this._selectionContainer); - this._terminal.screenElement.removeChild(this._themeStyleElement); - this._terminal.screenElement.removeChild(this._dimensionsStyleElement); - _super.prototype.dispose.call(this); - }; - DomRenderer.prototype._updateDimensions = function () { - var _this = this; - this.dimensions.scaledCharWidth = Math.floor(this._terminal.charMeasure.width * window.devicePixelRatio); - this.dimensions.scaledCharHeight = Math.ceil(this._terminal.charMeasure.height * window.devicePixelRatio); - this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.options.letterSpacing); - this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.options.lineHeight); - this.dimensions.scaledCharLeft = 0; - this.dimensions.scaledCharTop = 0; - this.dimensions.scaledCanvasWidth = this.dimensions.scaledCellWidth * this._terminal.cols; - this.dimensions.scaledCanvasHeight = this.dimensions.scaledCellHeight * this._terminal.rows; - this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / window.devicePixelRatio); - this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / window.devicePixelRatio); - this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols; - this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows; - this._rowElements.forEach(function (element) { - element.style.width = _this.dimensions.canvasWidth + "px"; - element.style.height = _this.dimensions.actualCellHeight + "px"; - element.style.lineHeight = _this.dimensions.actualCellHeight + "px"; - element.style.overflow = 'hidden'; - }); - if (!this._dimensionsStyleElement) { - this._dimensionsStyleElement = document.createElement('style'); - this._terminal.screenElement.appendChild(this._dimensionsStyleElement); - } - var styles = this._terminalSelector + " ." + ROW_CONTAINER_CLASS + " span {" + - " display: inline-block;" + - " height: 100%;" + - " vertical-align: top;" + - (" width: " + this.dimensions.actualCellWidth + "px") + - "}"; - this._dimensionsStyleElement.innerHTML = styles; - this._selectionContainer.style.height = this._terminal._viewportElement.style.height; - this._terminal.screenElement.style.width = this.dimensions.canvasWidth + "px"; - this._terminal.screenElement.style.height = this.dimensions.canvasHeight + "px"; - }; - DomRenderer.prototype.setTheme = function (theme) { - var _this = this; - if (theme) { - this.colorManager.setTheme(theme); - } - if (!this._themeStyleElement) { - this._themeStyleElement = document.createElement('style'); - this._terminal.screenElement.appendChild(this._themeStyleElement); - } - var styles = this._terminalSelector + " ." + ROW_CONTAINER_CLASS + " {" + - (" color: " + this.colorManager.colors.foreground.css + ";") + - (" background-color: " + this.colorManager.colors.background.css + ";") + - (" font-family: " + this._terminal.getOption('fontFamily') + ";") + - (" font-size: " + this._terminal.getOption('fontSize') + "px;") + - "}"; - styles += - this._terminalSelector + " span:not(." + DomRendererRowFactory_1.BOLD_CLASS + ") {" + - (" font-weight: " + this._terminal.options.fontWeight + ";") + - "}" + - (this._terminalSelector + " span." + DomRendererRowFactory_1.BOLD_CLASS + " {") + - (" font-weight: " + this._terminal.options.fontWeightBold + ";") + - "}" + - (this._terminalSelector + " span." + DomRendererRowFactory_1.ITALIC_CLASS + " {") + - " font-style: italic;" + - "}"; - styles += - this._terminalSelector + " ." + ROW_CONTAINER_CLASS + ":not(." + FOCUS_CLASS + ") ." + DomRendererRowFactory_1.CURSOR_CLASS + " {" + - (" outline: 1px solid " + this.colorManager.colors.cursor.css + ";") + - " outline-offset: -1px;" + - "}" + - (this._terminalSelector + " ." + ROW_CONTAINER_CLASS + "." + FOCUS_CLASS + " ." + DomRendererRowFactory_1.CURSOR_CLASS + "." + DomRendererRowFactory_1.CURSOR_STYLE_BLOCK_CLASS + " {") + - (" background-color: " + this.colorManager.colors.cursor.css + ";") + - (" color: " + this.colorManager.colors.cursorAccent.css + ";") + - "}" + - (this._terminalSelector + " ." + ROW_CONTAINER_CLASS + "." + FOCUS_CLASS + " ." + DomRendererRowFactory_1.CURSOR_CLASS + "." + DomRendererRowFactory_1.CURSOR_STYLE_BAR_CLASS + " {") + - (" box-shadow: 1px 0 0 " + this.colorManager.colors.cursor.css + " inset;") + - "}" + - (this._terminalSelector + " ." + ROW_CONTAINER_CLASS + "." + FOCUS_CLASS + " ." + DomRendererRowFactory_1.CURSOR_CLASS + "." + DomRendererRowFactory_1.CURSOR_STYLE_UNDERLINE_CLASS + " {") + - (" box-shadow: 0 -1px 0 " + this.colorManager.colors.cursor.css + " inset;") + - "}"; - styles += - this._terminalSelector + " ." + SELECTION_CLASS + " {" + - " position: absolute;" + - " top: 0;" + - " left: 0;" + - " z-index: 1;" + - " pointer-events: none;" + - "}" + - (this._terminalSelector + " ." + SELECTION_CLASS + " div {") + - " position: absolute;" + - (" background-color: " + this.colorManager.colors.selection.css + ";") + - "}"; - this.colorManager.colors.ansi.forEach(function (c, i) { - styles += - _this._terminalSelector + " ." + FG_CLASS_PREFIX + i + " { color: " + c.css + "; }" + - (_this._terminalSelector + " ." + BG_CLASS_PREFIX + i + " { background-color: " + c.css + "; }"); - }); - styles += - this._terminalSelector + " ." + FG_CLASS_PREFIX + Types_1.INVERTED_DEFAULT_COLOR + " { color: " + this.colorManager.colors.background.css + "; }" + - (this._terminalSelector + " ." + BG_CLASS_PREFIX + Types_1.INVERTED_DEFAULT_COLOR + " { background-color: " + this.colorManager.colors.foreground.css + "; }"); - this._themeStyleElement.innerHTML = styles; - return this.colorManager.colors; - }; - DomRenderer.prototype.onWindowResize = function (devicePixelRatio) { - this._updateDimensions(); - }; - DomRenderer.prototype._refreshRowElements = function (cols, rows) { - for (var i = this._rowElements.length; i <= rows; i++) { - var row = document.createElement('div'); - this._rowContainer.appendChild(row); - this._rowElements.push(row); - } - while (this._rowElements.length > rows) { - this._rowContainer.removeChild(this._rowElements.pop()); - } - }; - DomRenderer.prototype.onResize = function (cols, rows) { - this._refreshRowElements(cols, rows); - this._updateDimensions(); - }; - DomRenderer.prototype.onCharSizeChanged = function () { - this._updateDimensions(); - }; - DomRenderer.prototype.onBlur = function () { - this._rowContainer.classList.remove(FOCUS_CLASS); - }; - DomRenderer.prototype.onFocus = function () { - this._rowContainer.classList.add(FOCUS_CLASS); - }; - DomRenderer.prototype.onSelectionChanged = function (start, end, columnSelectMode) { - while (this._selectionContainer.children.length) { - this._selectionContainer.removeChild(this._selectionContainer.children[0]); - } - if (!start || !end) { - return; - } - var viewportStartRow = start[1] - this._terminal.buffer.ydisp; - var viewportEndRow = end[1] - this._terminal.buffer.ydisp; - var viewportCappedStartRow = Math.max(viewportStartRow, 0); - var viewportCappedEndRow = Math.min(viewportEndRow, this._terminal.rows - 1); - if (viewportCappedStartRow >= this._terminal.rows || viewportCappedEndRow < 0) { - return; - } - var documentFragment = document.createDocumentFragment(); - if (columnSelectMode) { - documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, start[0], end[0], viewportCappedEndRow - viewportCappedStartRow + 1)); - } - else { - var startCol = viewportStartRow === viewportCappedStartRow ? start[0] : 0; - var endCol = viewportCappedStartRow === viewportCappedEndRow ? end[0] : this._terminal.cols; - documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow, startCol, endCol)); - var middleRowsCount = viewportCappedEndRow - viewportCappedStartRow - 1; - documentFragment.appendChild(this._createSelectionElement(viewportCappedStartRow + 1, 0, this._terminal.cols, middleRowsCount)); - if (viewportCappedStartRow !== viewportCappedEndRow) { - var endCol_1 = viewportEndRow === viewportCappedEndRow ? end[0] : this._terminal.cols; - documentFragment.appendChild(this._createSelectionElement(viewportCappedEndRow, 0, endCol_1)); - } - } - this._selectionContainer.appendChild(documentFragment); - }; - DomRenderer.prototype._createSelectionElement = function (row, colStart, colEnd, rowCount) { - if (rowCount === void 0) { rowCount = 1; } - var element = document.createElement('div'); - element.style.height = rowCount * this.dimensions.actualCellHeight + "px"; - element.style.top = row * this.dimensions.actualCellHeight + "px"; - element.style.left = colStart * this.dimensions.actualCellWidth + "px"; - element.style.width = this.dimensions.actualCellWidth * (colEnd - colStart) + "px"; - return element; - }; - DomRenderer.prototype.onCursorMove = function () { - }; - DomRenderer.prototype.onOptionsChanged = function () { - this._updateDimensions(); - this.setTheme(undefined); - this._terminal.refresh(0, this._terminal.rows - 1); - }; - DomRenderer.prototype.clear = function () { - this._rowElements.forEach(function (e) { return e.innerHTML = ''; }); - }; - DomRenderer.prototype.refreshRows = function (start, end) { - this._renderDebouncer.refresh(start, end); - }; - DomRenderer.prototype._renderRows = function (start, end) { - var terminal = this._terminal; - var cursorAbsoluteY = terminal.buffer.ybase + terminal.buffer.y; - var cursorX = this._terminal.buffer.x; - for (var y = start; y <= end; y++) { - var rowElement = this._rowElements[y]; - rowElement.innerHTML = ''; - var row = y + terminal.buffer.ydisp; - var lineData = terminal.buffer.lines.get(row); - var cursorStyle = terminal.options.cursorStyle; - rowElement.appendChild(this._rowFactory.createRow(lineData, row === cursorAbsoluteY, cursorStyle, cursorX, this.dimensions.actualCellWidth, terminal.cols)); - } - this._terminal.emit('refresh', { start: start, end: end }); - }; - Object.defineProperty(DomRenderer.prototype, "_terminalSelector", { - get: function () { - return "." + TERMINAL_CLASS_PREFIX + this._terminalClass; - }, - enumerable: true, - configurable: true - }); - DomRenderer.prototype.registerCharacterJoiner = function (handler) { return -1; }; - DomRenderer.prototype.deregisterCharacterJoiner = function (joinerId) { return false; }; - DomRenderer.prototype._onLinkHover = function (e) { - this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true); - }; - DomRenderer.prototype._onLinkLeave = function (e) { - this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false); - }; - DomRenderer.prototype._setCellUnderline = function (x, x2, y, y2, cols, enabled) { - while (x !== x2 || y !== y2) { - var row = this._rowElements[y]; - if (!row) { - return; - } - var span = row.children[x]; - span.style.textDecoration = enabled ? 'underline' : 'none'; - x = (x + 1) % cols; - if (x === 0) { - y++; - } - } - }; - return DomRenderer; -}(EventEmitter_1.EventEmitter)); -exports.DomRenderer = DomRenderer; - -},{"../../common/EventEmitter":17,"../../ui/RenderDebouncer":50,"../ColorManager":28,"../atlas/Types":43,"./DomRendererRowFactory":45}],45:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Buffer_1 = require("../../Buffer"); -var Types_1 = require("../atlas/Types"); -exports.BOLD_CLASS = 'xterm-bold'; -exports.ITALIC_CLASS = 'xterm-italic'; -exports.CURSOR_CLASS = 'xterm-cursor'; -exports.CURSOR_STYLE_BLOCK_CLASS = 'xterm-cursor-block'; -exports.CURSOR_STYLE_BAR_CLASS = 'xterm-cursor-bar'; -exports.CURSOR_STYLE_UNDERLINE_CLASS = 'xterm-cursor-underline'; -var DomRendererRowFactory = (function () { - function DomRendererRowFactory(_document) { - this._document = _document; - } - DomRendererRowFactory.prototype.createRow = function (lineData, isCursorRow, cursorStyle, cursorX, cellWidth, cols) { - var fragment = this._document.createDocumentFragment(); - var lineLength = 0; - for (var x = Math.min(lineData.length, cols) - 1; x >= 0; x--) { - var charData = lineData.get(x); - var code = charData[Buffer_1.CHAR_DATA_CODE_INDEX]; - if (code !== Buffer_1.NULL_CELL_CODE || (isCursorRow && x === cursorX)) { - lineLength = x + 1; - break; - } - } - for (var x = 0; x < lineLength; x++) { - var charData = lineData.get(x); - var char = charData[Buffer_1.CHAR_DATA_CHAR_INDEX]; - var attr = charData[Buffer_1.CHAR_DATA_ATTR_INDEX]; - var width = charData[Buffer_1.CHAR_DATA_WIDTH_INDEX]; - if (width === 0) { - continue; - } - var charElement = this._document.createElement('span'); - if (width > 1) { - charElement.style.width = cellWidth * width + "px"; - } - var flags = attr >> 18; - var bg = attr & 0x1ff; - var fg = (attr >> 9) & 0x1ff; - if (isCursorRow && x === cursorX) { - charElement.classList.add(exports.CURSOR_CLASS); - switch (cursorStyle) { - case 'bar': - charElement.classList.add(exports.CURSOR_STYLE_BAR_CLASS); - break; - case 'underline': - charElement.classList.add(exports.CURSOR_STYLE_UNDERLINE_CLASS); - break; - default: - charElement.classList.add(exports.CURSOR_STYLE_BLOCK_CLASS); - break; - } - } - if (flags & 8) { - var temp = bg; - bg = fg; - fg = temp; - if (fg === Types_1.DEFAULT_COLOR) { - fg = Types_1.INVERTED_DEFAULT_COLOR; - } - if (bg === Types_1.DEFAULT_COLOR) { - bg = Types_1.INVERTED_DEFAULT_COLOR; - } - } - if (flags & 1) { - if (fg < 8) { - fg += 8; - } - charElement.classList.add(exports.BOLD_CLASS); - } - if (flags & 64) { - charElement.classList.add(exports.ITALIC_CLASS); - } - charElement.textContent = char; - if (fg !== Types_1.DEFAULT_COLOR) { - charElement.classList.add("xterm-fg-" + fg); - } - if (bg !== Types_1.DEFAULT_COLOR) { - charElement.classList.add("xterm-bg-" + bg); - } - fragment.appendChild(charElement); - } - return fragment; - }; - return DomRendererRowFactory; -}()); -exports.DomRendererRowFactory = DomRendererRowFactory; - -},{"../../Buffer":2,"../atlas/Types":43}],46:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var EventEmitter_1 = require("../common/EventEmitter"); -var CharMeasure = (function (_super) { - __extends(CharMeasure, _super); - function CharMeasure(document, parentElement) { - var _this = _super.call(this) || this; - _this._document = document; - _this._parentElement = parentElement; - _this._measureElement = _this._document.createElement('span'); - _this._measureElement.classList.add('xterm-char-measure-element'); - _this._measureElement.textContent = 'W'; - _this._measureElement.setAttribute('aria-hidden', 'true'); - _this._parentElement.appendChild(_this._measureElement); - return _this; - } - Object.defineProperty(CharMeasure.prototype, "width", { - get: function () { - return this._width; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CharMeasure.prototype, "height", { - get: function () { - return this._height; - }, - enumerable: true, - configurable: true - }); - CharMeasure.prototype.measure = function (options) { - this._measureElement.style.fontFamily = options.fontFamily; - this._measureElement.style.fontSize = options.fontSize + "px"; - var geometry = this._measureElement.getBoundingClientRect(); - if (geometry.width === 0 || geometry.height === 0) { - return; - } - if (this._width !== geometry.width || this._height !== geometry.height) { - this._width = geometry.width; - this._height = Math.ceil(geometry.height); - this.emit('charsizechanged'); - } - }; - return CharMeasure; -}(EventEmitter_1.EventEmitter)); -exports.CharMeasure = CharMeasure; - -},{"../common/EventEmitter":17}],47:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function prepareTextForTerminal(text) { - return text.replace(/\r?\n/g, '\r'); -} -exports.prepareTextForTerminal = prepareTextForTerminal; -function bracketTextForPaste(text, bracketedPasteMode) { - if (bracketedPasteMode) { - return '\x1b[200~' + text + '\x1b[201~'; - } - return text; -} -exports.bracketTextForPaste = bracketTextForPaste; -function copyHandler(ev, term, selectionManager) { - if (term.browser.isMSIE) { - window.clipboardData.setData('Text', selectionManager.selectionText); - } - else { - ev.clipboardData.setData('text/plain', selectionManager.selectionText); - } - ev.preventDefault(); -} -exports.copyHandler = copyHandler; -function pasteHandler(ev, term) { - ev.stopPropagation(); - var text; - var dispatchPaste = function (text) { - text = prepareTextForTerminal(text); - text = bracketTextForPaste(text, term.bracketedPasteMode); - term.handler(text); - term.textarea.value = ''; - term.emit('paste', text); - term.cancel(ev); - }; - if (term.browser.isMSIE) { - if (window.clipboardData) { - text = window.clipboardData.getData('Text'); - dispatchPaste(text); - } - } - else { - if (ev.clipboardData) { - text = ev.clipboardData.getData('text/plain'); - dispatchPaste(text); - } - } -} -exports.pasteHandler = pasteHandler; -function moveTextAreaUnderMouseCursor(ev, textarea) { - textarea.style.position = 'fixed'; - textarea.style.width = '20px'; - textarea.style.height = '20px'; - textarea.style.left = (ev.clientX - 10) + 'px'; - textarea.style.top = (ev.clientY - 10) + 'px'; - textarea.style.zIndex = '1000'; - textarea.focus(); - setTimeout(function () { - textarea.style.position = null; - textarea.style.width = null; - textarea.style.height = null; - textarea.style.left = null; - textarea.style.top = null; - textarea.style.zIndex = null; - }, 200); -} -exports.moveTextAreaUnderMouseCursor = moveTextAreaUnderMouseCursor; -function rightClickHandler(ev, textarea, selectionManager, shouldSelectWord) { - moveTextAreaUnderMouseCursor(ev, textarea); - if (shouldSelectWord && !selectionManager.isClickInSelection(ev)) { - selectionManager.selectWordAtCursor(ev); - } - textarea.value = selectionManager.selectionText; - textarea.select(); -} -exports.rightClickHandler = rightClickHandler; - -},{}],48:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function addDisposableDomListener(node, type, handler, useCapture) { - node.addEventListener(type, handler, useCapture); - return { - dispose: function () { - if (!handler) { - return; - } - node.removeEventListener(type, handler, useCapture); - node = null; - handler = null; - } - }; -} -exports.addDisposableDomListener = addDisposableDomListener; - -},{}],49:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Lifecycle_1 = require("../common/Lifecycle"); -var Lifecycle_2 = require("./Lifecycle"); -var HOVER_DURATION = 500; -var MouseZoneManager = (function (_super) { - __extends(MouseZoneManager, _super); - function MouseZoneManager(_terminal) { - var _this = _super.call(this) || this; - _this._terminal = _terminal; - _this._zones = []; - _this._areZonesActive = false; - _this._tooltipTimeout = null; - _this._currentZone = null; - _this._lastHoverCoords = [null, null]; - _this.register(Lifecycle_2.addDisposableDomListener(_this._terminal.element, 'mousedown', function (e) { return _this._onMouseDown(e); })); - _this._mouseMoveListener = function (e) { return _this._onMouseMove(e); }; - _this._clickListener = function (e) { return _this._onClick(e); }; - return _this; - } - MouseZoneManager.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this._deactivate(); - }; - MouseZoneManager.prototype.add = function (zone) { - this._zones.push(zone); - if (this._zones.length === 1) { - this._activate(); - } - }; - MouseZoneManager.prototype.clearAll = function (start, end) { - if (this._zones.length === 0) { - return; - } - if (!end) { - start = 0; - end = this._terminal.rows - 1; - } - for (var i = 0; i < this._zones.length; i++) { - var zone = this._zones[i]; - if ((zone.y1 > start && zone.y1 <= end + 1) || - (zone.y2 > start && zone.y2 <= end + 1) || - (zone.y1 < start && zone.y2 > end + 1)) { - if (this._currentZone && this._currentZone === zone) { - this._currentZone.leaveCallback(); - this._currentZone = null; - } - this._zones.splice(i--, 1); - } - } - if (this._zones.length === 0) { - this._deactivate(); - } - }; - MouseZoneManager.prototype._activate = function () { - if (!this._areZonesActive) { - this._areZonesActive = true; - this._terminal.element.addEventListener('mousemove', this._mouseMoveListener); - this._terminal.element.addEventListener('click', this._clickListener); - } - }; - MouseZoneManager.prototype._deactivate = function () { - if (this._areZonesActive) { - this._areZonesActive = false; - this._terminal.element.removeEventListener('mousemove', this._mouseMoveListener); - this._terminal.element.removeEventListener('click', this._clickListener); - } - }; - MouseZoneManager.prototype._onMouseMove = function (e) { - if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) { - this._onHover(e); - this._lastHoverCoords = [e.pageX, e.pageY]; - } - }; - MouseZoneManager.prototype._onHover = function (e) { - var _this = this; - var zone = this._findZoneEventAt(e); - if (zone === this._currentZone) { - return; - } - if (this._currentZone) { - this._currentZone.leaveCallback(); - this._currentZone = null; - if (this._tooltipTimeout) { - clearTimeout(this._tooltipTimeout); - } - } - if (!zone) { - return; - } - this._currentZone = zone; - if (zone.hoverCallback) { - zone.hoverCallback(e); - } - this._tooltipTimeout = setTimeout(function () { return _this._onTooltip(e); }, HOVER_DURATION); - }; - MouseZoneManager.prototype._onTooltip = function (e) { - this._tooltipTimeout = null; - var zone = this._findZoneEventAt(e); - if (zone && zone.tooltipCallback) { - zone.tooltipCallback(e); - } - }; - MouseZoneManager.prototype._onMouseDown = function (e) { - if (!this._areZonesActive) { - return; - } - var zone = this._findZoneEventAt(e); - if (zone) { - if (zone.willLinkActivate(e)) { - e.preventDefault(); - e.stopImmediatePropagation(); - } - } - }; - MouseZoneManager.prototype._onClick = function (e) { - var zone = this._findZoneEventAt(e); - if (zone) { - zone.clickCallback(e); - e.preventDefault(); - e.stopImmediatePropagation(); - } - }; - MouseZoneManager.prototype._findZoneEventAt = function (e) { - var coords = this._terminal.mouseHelper.getCoords(e, this._terminal.screenElement, this._terminal.charMeasure, this._terminal.cols, this._terminal.rows); - if (!coords) { - return null; - } - var x = coords[0]; - var y = coords[1]; - for (var i = 0; i < this._zones.length; i++) { - var zone = this._zones[i]; - if (zone.y1 === zone.y2) { - if (y === zone.y1 && x >= zone.x1 && x < zone.x2) { - return zone; - } - } - else { - if ((y === zone.y1 && x >= zone.x1) || - (y === zone.y2 && x < zone.x2) || - (y > zone.y1 && y < zone.y2)) { - return zone; - } - } - } - return null; - }; - return MouseZoneManager; -}(Lifecycle_1.Disposable)); -exports.MouseZoneManager = MouseZoneManager; -var MouseZone = (function () { - function MouseZone(x1, y1, x2, y2, clickCallback, hoverCallback, tooltipCallback, leaveCallback, willLinkActivate) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - this.clickCallback = clickCallback; - this.hoverCallback = hoverCallback; - this.tooltipCallback = tooltipCallback; - this.leaveCallback = leaveCallback; - this.willLinkActivate = willLinkActivate; - } - return MouseZone; -}()); -exports.MouseZone = MouseZone; - -},{"../common/Lifecycle":18,"./Lifecycle":48}],50:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var RenderDebouncer = (function () { - function RenderDebouncer(_terminal, _callback) { - this._terminal = _terminal; - this._callback = _callback; - this._animationFrame = null; - } - RenderDebouncer.prototype.dispose = function () { - if (this._animationFrame) { - window.cancelAnimationFrame(this._animationFrame); - this._animationFrame = null; - } - }; - RenderDebouncer.prototype.refresh = function (rowStart, rowEnd) { - var _this = this; - rowStart = rowStart !== null && rowStart !== undefined ? rowStart : 0; - rowEnd = rowEnd !== null && rowEnd !== undefined ? rowEnd : this._terminal.rows - 1; - var isRowStartSet = this._rowStart !== undefined && this._rowStart !== null; - var isRowEndSet = this._rowEnd !== undefined && this._rowEnd !== null; - this._rowStart = isRowStartSet ? Math.min(this._rowStart, rowStart) : rowStart; - this._rowEnd = isRowEndSet ? Math.max(this._rowEnd, rowEnd) : rowEnd; - if (this._animationFrame) { - return; - } - this._animationFrame = window.requestAnimationFrame(function () { return _this._innerRefresh(); }); - }; - RenderDebouncer.prototype._innerRefresh = function () { - this._rowStart = Math.max(this._rowStart, 0); - this._rowEnd = Math.min(this._rowEnd, this._terminal.rows - 1); - this._callback(this._rowStart, this._rowEnd); - this._rowStart = null; - this._rowEnd = null; - this._animationFrame = null; - }; - return RenderDebouncer; -}()); -exports.RenderDebouncer = RenderDebouncer; - -},{}],51:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var Lifecycle_1 = require("../common/Lifecycle"); -var ScreenDprMonitor = (function (_super) { - __extends(ScreenDprMonitor, _super); - function ScreenDprMonitor() { - return _super !== null && _super.apply(this, arguments) || this; - } - ScreenDprMonitor.prototype.setListener = function (listener) { - var _this = this; - if (this._listener) { - this.clearListener(); - } - this._listener = listener; - this._outerListener = function () { - _this._listener(window.devicePixelRatio, _this._currentDevicePixelRatio); - _this._updateDpr(); - }; - this._updateDpr(); - }; - ScreenDprMonitor.prototype.dispose = function () { - _super.prototype.dispose.call(this); - this.clearListener(); - }; - ScreenDprMonitor.prototype._updateDpr = function () { - if (this._resolutionMediaMatchList) { - this._resolutionMediaMatchList.removeListener(this._outerListener); - } - this._currentDevicePixelRatio = window.devicePixelRatio; - this._resolutionMediaMatchList = window.matchMedia("screen and (resolution: " + window.devicePixelRatio + "dppx)"); - this._resolutionMediaMatchList.addListener(this._outerListener); - }; - ScreenDprMonitor.prototype.clearListener = function () { - if (!this._listener) { - return; - } - this._resolutionMediaMatchList.removeListener(this._outerListener); - this._listener = null; - this._outerListener = null; - }; - return ScreenDprMonitor; -}(Lifecycle_1.Disposable)); -exports.ScreenDprMonitor = ScreenDprMonitor; - -},{"../common/Lifecycle":18}],52:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.clone = function (val, depth) { - if (depth === void 0) { depth = 5; } - if (typeof val !== 'object') { - return val; - } - if (val === null) { - return null; - } - var clonedObject = Array.isArray(val) ? [] : {}; - for (var key in val) { - clonedObject[key] = depth <= 1 ? val[key] : exports.clone(val[key], depth - 1); - } - return clonedObject; -}; - -},{}],53:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var MouseHelper = (function () { - function MouseHelper(_renderer) { - this._renderer = _renderer; - } - MouseHelper.prototype.setRenderer = function (renderer) { - this._renderer = renderer; - }; - MouseHelper.getCoordsRelativeToElement = function (event, element) { - if (event.pageX === null || event.pageX === undefined) { - return null; - } - var originalElement = element; - var x = event.pageX; - var y = event.pageY; - while (element) { - x -= element.offsetLeft; - y -= element.offsetTop; - element = element.offsetParent; - } - element = originalElement; - while (element && element !== element.ownerDocument.body) { - x += element.scrollLeft; - y += element.scrollTop; - element = element.parentElement; - } - return [x, y]; - }; - MouseHelper.prototype.getCoords = function (event, element, charMeasure, colCount, rowCount, isSelection) { - if (!charMeasure.width || !charMeasure.height) { - return null; - } - var coords = MouseHelper.getCoordsRelativeToElement(event, element); - if (!coords) { - return null; - } - coords[0] = Math.ceil((coords[0] + (isSelection ? this._renderer.dimensions.actualCellWidth / 2 : 0)) / this._renderer.dimensions.actualCellWidth); - coords[1] = Math.ceil(coords[1] / this._renderer.dimensions.actualCellHeight); - coords[0] = Math.min(Math.max(coords[0], 1), colCount + (isSelection ? 1 : 0)); - coords[1] = Math.min(Math.max(coords[1], 1), rowCount); - return coords; - }; - MouseHelper.prototype.getRawByteCoords = function (event, element, charMeasure, colCount, rowCount) { - var coords = this.getCoords(event, element, charMeasure, colCount, rowCount); - var x = coords[0]; - var y = coords[1]; - x += 32; - y += 32; - return { x: x, y: y }; - }; - return MouseHelper; -}()); -exports.MouseHelper = MouseHelper; - -},{}],54:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Terminal_1 = require("./public/Terminal"); -module.exports = Terminal_1.Terminal; - -},{"./public/Terminal":25}]},{},[54])(54) -}); -//# sourceMappingURL=xterm.js.map diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Controller.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Controller.ftl index 3b4b62a..5962e5c 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Controller.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Controller.ftl @@ -1,47 +1,48 @@ +package ${package}.controller; -package ${package}.rest; - -import ${package}.service.${className}Service; -import ${package}.service.dto.${className}Dto; -import org.springframework.data.domain.Pageable; -import lombok.RequiredArgsConstructor; - +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.base.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.logging.annotation.Log; +import ${package}.service.I${className}Service; +import ${package}.service.dao.${className}; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import io.swagger.annotations.*; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; +import java.util.Map; +import java.util.Set; /** * @author ${author} * @date ${date} **/ +@Slf4j @RestController -@RequiredArgsConstructor @Api(tags = "${apiAlias}管理") @RequestMapping("/api/${changeClassName}") -@Slf4j public class ${className}Controller { - private final ${className}Service ${changeClassName}Service; + @Autowired + private I${className}Service ${changeClassName}Service; @GetMapping @Log("查询${apiAlias}") @ApiOperation("查询${apiAlias}") //@SaCheckPermission("@el.check('${changeClassName}:list')") - public ResponseEntity query(@RequestParam Map whereJson, Pageable page){ - return new ResponseEntity<>(${changeClassName}Service.queryAll(whereJson,page),HttpStatus.OK); + public ResponseEntity query(@RequestParam Map whereJson, PageQuery page){ + return new ResponseEntity<>(TableDataInfo.build(${changeClassName}Service.queryAll(whereJson,page)),HttpStatus.OK); } @PostMapping @Log("新增${apiAlias}") @ApiOperation("新增${apiAlias}") //@SaCheckPermission("@el.check('${changeClassName}:add')") - public ResponseEntity create(@Validated @RequestBody ${className}Dto dto){ - ${changeClassName}Service.create(dto); + public ResponseEntity create(@Validated @RequestBody ${className} entity){ + ${changeClassName}Service.create(entity); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -49,8 +50,8 @@ public class ${className}Controller { @Log("修改${apiAlias}") @ApiOperation("修改${apiAlias}") //@SaCheckPermission("@el.check('${changeClassName}:edit')") - public ResponseEntity update(@Validated @RequestBody ${className}Dto dto){ - ${changeClassName}Service.update(dto); + public ResponseEntity update(@Validated @RequestBody ${className} entity){ + ${changeClassName}Service.update(entity); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -58,7 +59,7 @@ public class ${className}Controller { @ApiOperation("删除${apiAlias}") //@SaCheckPermission("@el.check('${changeClassName}:del')") @DeleteMapping - public ResponseEntity delete(@RequestBody Long[] ids) { + public ResponseEntity delete(@RequestBody Set ids) { ${changeClassName}Service.deleteAll(ids); return new ResponseEntity<>(HttpStatus.OK); } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Dto.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Dto.ftl index 455bcdf..07f913f 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Dto.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Dto.ftl @@ -1,20 +1,13 @@ package ${package}.service.dto; -import lombok.Data; <#if hasTimestamp> import java.sql.Timestamp; -<#if hasDate> -import java.util.Date; - <#if hasBigDecimal> import java.math.BigDecimal; +import lombok.Data; import java.io.Serializable; -<#if !auto && pkColumnType = 'Long'> -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; - /** * @description / diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Entity.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Entity.ftl index 113babb..93dfaa8 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Entity.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Entity.ftl @@ -1,23 +1,19 @@ -package ${package}.domain; +package ${package}.service.dao; -import lombok.Data; -import cn.hutool.core.bean.BeanUtil; +<#if hasPk> +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + import io.swagger.annotations.ApiModelProperty; -import cn.hutool.core.bean.copier.CopyOptions; -import javax.persistence.*; -<#if isNotNullColumns??> - import javax.validation.constraints.*; - -<#if hasDateAnnotation> - import javax.persistence.Entity; - import javax.persistence.Table; - import org.hibernate.annotations.*; - -<#if hasDate> - import java.util.Date; +import lombok.Data; +import lombok.EqualsAndHashCode; + +<#if hasTimestamp> +import java.sql.Timestamp; <#if hasBigDecimal> - import java.math.BigDecimal; +import java.math.BigDecimal; import java.io.Serializable; @@ -26,44 +22,25 @@ import java.io.Serializable; * @author ${author} * @date ${date} **/ -@Entity @Data -@Table(name="${tableName}") +@EqualsAndHashCode(callSuper = false) +@TableName("${tableName}") public class ${className} implements Serializable { + + private static final long serialVersionUID = 1L; + <#if columns??> - <#list columns as column> - - <#if column.columnKey = 'PRI'> - @Id - <#if auto> - @GeneratedValue(strategy = GenerationType.IDENTITY) - - - @Column(name = "${column.columnName}"<#if column.columnKey = 'UNI'>,unique = true<#if column.istNotNull && column.columnKey != 'PRI'>,nullable = false) - <#if column.istNotNull && column.columnKey != 'PRI'> - <#if column.columnType = 'String'> - @NotBlank - <#else> - @NotNull - - - <#if (column.dateAnnotation)?? && column.dateAnnotation != ''> - <#if column.dateAnnotation = 'CreationDate'> - - <#else> - @UpdateDate - - - <#if column.remark != ''> - @ApiModelProperty(value = "${column.remark}") - <#else> - @ApiModelProperty(value = "${column.changeColumnName}") - - private ${column.columnType} ${column.changeColumnName}; - +<#list columns as column> +<#if column.columnKey = 'PRI'> + @TableId(value = "${column.columnName}", type = <#if auto>IdType.AUTO<#else>IdType.NONE) +<#if column.remark != ''> + @ApiModelProperty(value = "${column.remark}") +<#else> + @ApiModelProperty(value = "${column.changeColumnName}") + + private ${column.columnType} ${column.changeColumnName}; -public void copy(${className} source){ -BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); -} + + } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Mapper.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Mapper.ftl index 2386841..0ab0952 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Mapper.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Mapper.ftl @@ -1,17 +1,12 @@ -package ${package}.service.mapstruct; +package ${package}.service.dao.mapper; -import BaseMapper; -import ${package}.domain.${className}; -import ${package}.service.dto.${className}Dto; -import org.mapstruct.Mapper; -import org.mapstruct.ReportingPolicy; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import ${package}.service.dao.${className}; /** -* @website https://el-admin.vip * @author ${author} * @date ${date} **/ -@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) -public interface ${className}Mapper extends BaseMapper<${className}Dto, ${className}> { +public interface ${className}Mapper extends BaseMapper<${className}> { } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/MySQLMapper.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/MySQLMapper.ftl new file mode 100644 index 0000000..e4f0413 --- /dev/null +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/MySQLMapper.ftl @@ -0,0 +1,5 @@ + + + + + diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/QueryCriteria.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/QueryCriteria.ftl index dcca8d2..d991085 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/QueryCriteria.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/QueryCriteria.ftl @@ -1,66 +1,12 @@ - package ${package}.service.dto; -import lombok.Data; -<#if queryHasDate> -import java.util.Date; - -<#if queryHasBigDecimal> -import java.math.BigDecimal; - -<#if betweens??> -import java.util.List; - -<#if queryColumns??> -import Query; - +import org.nl.common.domain.query.BaseQuery; +import ${package}.service.dao.${className}; /** * @author ${author} * @date ${date} **/ -@Data -public class ${className}QueryCriteria{ -<#if queryColumns??> - <#list queryColumns as column> +public class ${className}Query extends BaseQuery<${className}> { -<#if column.queryType = '='> - /** 精确 */ - @Query - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = 'Like'> - /** 模糊 */ - @Query(type = Query.Type.INNER_LIKE) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '!='> - /** 不等于 */ - @Query(type = Query.Type.NOT_EQUAL) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = 'NotNull'> - /** 不为空 */ - @Query(type = Query.Type.NOT_NULL) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '>='> - /** 大于等于 */ - @Query(type = Query.Type.GREATER_THAN) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '<='> - /** 小于等于 */ - @Query(type = Query.Type.LESS_THAN) - private ${column.columnType} ${column.changeColumnName}; - - - -<#if betweens??> - <#list betweens as column> - /** BETWEEN */ - @Query(type = Query.Type.BETWEEN) - private List<${column.columnType}> ${column.changeColumnName}; - - } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Service.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Service.ftl index b7c7785..04c592e 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Service.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/Service.ftl @@ -1,64 +1,43 @@ package ${package}.service; -import ${package}.service.dto.${className}Dto; -import org.springframework.data.domain.Pageable; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.nl.common.domain.query.PageQuery; +import com.baomidou.mybatisplus.extension.service.IService; +import ${package}.service.dao.${className}; + import java.util.Map; -import java.util.List; -import java.io.IOException; -import javax.servlet.http.HttpServletResponse; +import java.util.Set; /** * @description 服务接口 * @author ${author} * @date ${date} **/ -public interface ${className}Service { +public interface I${className}Service extends IService<${className}> { /** * 查询数据分页 * @param whereJson 条件 - * @param page 分页参数 - * @return Map + * @param pageable 分页参数 + * @return IPage<${className}> */ - Map queryAll(Map whereJson, Pageable page); - - /** - * 查询所有数据不分页 - * @param whereJson 条件参数 - * @return List<${className}Dto> - */ - List<${className}Dto> queryAll(Map whereJson); - - /** - * 根据ID查询 - * @param ${pkChangeColName} ID - * @return ${className} - */ - ${className}Dto findById(${pkColumnType} ${pkChangeColName}); - - /** - * 根据编码查询 - * @param code code - * @return ${className} - */ - ${className}Dto findByCode(String code); - + IPage<${className}> queryAll(Map whereJson, PageQuery pageable); /** * 创建 - * @param dto / + * @param entity / */ - void create(${className}Dto dto); + void create(${className} entity); /** * 编辑 - * @param dto / + * @param entity / */ - void update(${className}Dto dto); + void update(${className} entity); /** * 多选删除 * @param ids / */ - void deleteAll(${pkColumnType}[] ids); + void deleteAll(Set ids); } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/ServiceImpl.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/ServiceImpl.ftl index a859350..1b20b49 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/ServiceImpl.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/admin/ServiceImpl.ftl @@ -1,130 +1,80 @@ - package ${package}.service.impl; -import ${package}.service.${className}Service; -import ${package}.service.dto.${className}Dto; -import com.alibaba.fastjson.JSON; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - import org.springframework.transaction.annotation.Transactional; - -import org.springframework.data.domain.Pageable; -import java.util.List; -import java.util.Map; - import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import org.nl.modules.common.utils.SecurityUtils; -import org.nl.modules.wql.core.bean.ResultBean; -import org.nl.modules.wql.core.bean.WQLObject; -import org.nl.modules.wql.util.WqlUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import cn.hutool.core.util.ObjectUtil; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.exception.BadRequestException; +import org.nl.common.utils.SecurityUtils; +import ${package}.service.I${className}Service; +import ${package}.service.dao.mapper.${className}Mapper; +import ${package}.service.dao.${className}; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; +import java.util.Set; /** * @description 服务实现 * @author ${author} * @date ${date} **/ -@Service -@RequiredArgsConstructor @Slf4j -public class ${className}ServiceImpl implements ${className}Service { +@Service +public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements I${className}Service { + + @Autowired + private ${className}Mapper ${changeClassName}Mapper; @Override - public Map queryAll(Map whereJson, Pageable page){ - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - ResultBean rb = wo.pagequery(WqlUtil.getHttpContext(page), "1=1", "update_time desc"); - final JSONObject json = rb.pageResult(); - return json; + public IPage<${className}> queryAll(Map whereJson, PageQuery page){ + LambdaQueryWrapper<${className}> lam = new LambdaQueryWrapper<>(); + IPage<${className}> pages = new Page<>(page.getPage() + 1, page.getSize()); + ${changeClassName}Mapper.selectPage(pages, lam); + return pages; } @Override - public List<${className}Dto> queryAll(Map whereJson){ - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONArray arr = wo.query().getResultJSONArray(0); - if (ObjectUtil.isNotEmpty(arr)) return arr.toJavaList(${className}Dto.class); - return null; - } - - @Override - public ${className}Dto findById(${pkColumnType} ${pkChangeColName}) { - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = wo.query("${pkChangeColName} = '" + ${pkChangeColName} + "'").uniqueResult(0); - if (ObjectUtil.isNotEmpty(json)){ - return json.toJavaObject( ${className}Dto.class); - } - return null; - } - - @Override - public ${className}Dto findByCode(String code) { - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = wo.query("code ='" + code + "'").uniqueResult(0); - if (ObjectUtil.isNotEmpty(json)){ - return json.toJavaObject( ${className}Dto.class); - } - return null; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void create(${className}Dto dto) { + public void create(${className} entity) { String currentUserId = SecurityUtils.getCurrentUserId(); String nickName = SecurityUtils.getCurrentNickName(); String now = DateUtil.now(); - dto.set${pkChangeColName ? cap_first }(IdUtil.getSnowflake(1, 1).nextId()); - dto.setCreate_id(currentUserId); - dto.setCreate_name(nickName); - dto.setUpdate_id(currentUserId); - dto.setUpdate_optname(nickName); - dto.setUpdate_time(now); - dto.setCreate_time(now); - - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = JSONObject.parseObject(JSON.toJSONString(dto)); - wo.insert(json); + entity.set${pkChangeColName ? cap_first }(IdUtil.getSnowflake(1, 1).nextIdStr()); + entity.setCreate_id(currentUserId); + entity.setCreate_name(nickName); + entity.setCreate_time(now); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); + ${changeClassName}Mapper.insert(entity); } @Override - @Transactional(rollbackFor = Exception.class) - public void update(${className}Dto dto) { - ${className}Dto entity = this.findById(dto.get${pkChangeColName ? cap_first }()); - if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); + public void update(${className} entity) { + ${className} dto = ${changeClassName}Mapper.selectById(entity.get${pkChangeColName ? cap_first }()); + if (dto == null) throw new BadRequestException("被删除或无权限,操作失败!"); String currentUserId = SecurityUtils.getCurrentUserId(); String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - dto.setUpdate_time(now); - dto.setUpdate_id(currentUserId); - dto.setUpdate_optname(nickName); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = JSONObject.parseObject(JSON.toJSONString(dto)); - wo.update(json); + ${changeClassName}Mapper.updateById(entity); } @Override - @Transactional(rollbackFor = Exception.class) - public void deleteAll(${pkColumnType}[] ids) { - String currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - for (${pkColumnType} ${pkChangeColName}: ids) { - JSONObject param = new JSONObject(); - param.put("${pkChangeColName}", String.valueOf(${pkChangeColName})); - param.put("is_delete", "1"); - param.put("update_id", currentUserId); - param.put("update_optname", nickName); - param.put("update_time", now); - wo.update(param); - } + public void deleteAll(Set ids) { + // 真删除 + ${changeClassName}Mapper.deleteBatchIds(ids); } } diff --git a/nladmin-system/nlsso-server/src/main/resources/template/generator/front/index.ftl b/nladmin-system/nlsso-server/src/main/resources/template/generator/front/index.ftl index e886a91..ebd252c 100644 --- a/nladmin-system/nlsso-server/src/main/resources/template/generator/front/index.ftl +++ b/nladmin-system/nlsso-server/src/main/resources/template/generator/front/index.ftl @@ -120,7 +120,13 @@ import crudOperation from '@crud/CRUD.operation' import udOperation from '@crud/UD.operation' import pagination from '@crud/Pagination' -const defaultForm = { <#if columns??><#list columns as column>${column.changeColumnName}: null<#if column_has_next>, } +const defaultForm = { + <#if columns??> + <#list columns as column> + ${column.changeColumnName}: null<#if column_has_next>, + + +} export default { name: '${className}', components: { pagination, crudOperation, rrOperation, udOperation }, @@ -129,7 +135,13 @@ export default { dicts: [<#if hasDict??><#list dicts as dict>'${dict}'<#if dict_has_next>, ], cruds() { - return CRUD({ title: '${apiAlias}', url: 'api/${changeClassName}', idField: '${pkChangeColName}', sort: '${pkChangeColName},desc', crudMethod: { ...crud${className} }}) + return CRUD({ + title: '${apiAlias}', + url: 'api/${changeClassName}', + idField: '${pkChangeColName}', + sort: '${pkChangeColName},desc', + crudMethod: { ...crud${className} } + }) }, data() { return { diff --git a/nladmin-system/pom.xml b/nladmin-system/pom.xml index cfdd1df..addcceb 100644 --- a/nladmin-system/pom.xml +++ b/nladmin-system/pom.xml @@ -21,6 +21,9 @@ 1.31.0 + + + diff --git a/nladmin-ui/package.json b/nladmin-ui/package.json index 57b7c44..0fe34f1 100644 --- a/nladmin-ui/package.json +++ b/nladmin-ui/package.json @@ -66,6 +66,7 @@ "sortablejs": "1.8.4", "throttle-debounce": "^5.0.0", "vue": "2.6.10", + "vue-bus": "^1.2.1", "vue-color": "^2.8.1", "vue-count-to": "1.0.13", "vue-cropper": "0.4.9", diff --git a/nladmin-ui/public/config.js b/nladmin-ui/public/config.js index c4d32ea..441302a 100644 --- a/nladmin-ui/public/config.js +++ b/nladmin-ui/public/config.js @@ -4,7 +4,6 @@ window.g = { }, prod: { VUE_APP_BASE_API: 'http://127.0.0.1:8010' - } } diff --git a/nladmin-ui/src/layout/components/Navbar.vue b/nladmin-ui/src/layout/components/Navbar.vue index 2054253..011b261 100644 --- a/nladmin-ui/src/layout/components/Navbar.vue +++ b/nladmin-ui/src/layout/components/Navbar.vue @@ -15,6 +15,8 @@ + + - {{ user.personName }} - + {{ user.person_name }} @@ -61,9 +61,13 @@ import Screenfull from '@/components/Screenfull' import SizeSelect from '@/components/SizeSelect' import Search from '@/components/HeaderSearch' import Avatar from '@/assets/images/avatar.png' +import NoticeIcon from '@/views/system/notice/NoticeIcon.vue' +import NoticeIconReader from '@/views/system/notice/NoticeIconReader.vue' export default { components: { + NoticeIconReader, + NoticeIcon, Breadcrumb, Hamburger, Screenfull, @@ -72,6 +76,9 @@ export default { Doc, TopNav }, + created() { + this.initWebSocket() + }, data() { return { Avatar: Avatar, @@ -119,6 +126,35 @@ export default { this.$store.dispatch('LogOut').then(() => { location.reload() }) + }, + initWebSocket() { + // const wsUri = (process.env.VUE_APP_WS_API === '/' ? '/' : (process.env.VUE_APP_WS_API + '/')) + 'messageInfo' + const wsUri = window.g.prod.VUE_APP_BASE_API.replace('http', 'ws') + '/webSocket/' + 'messageInfo' + this.websock = new WebSocket(wsUri) + this.websock.onerror = this.webSocketOnError + this.websock.onmessage = this.webSocketOnMessage + }, + webSocketOnError(e) { + this.$notify({ + title: 'WebSocket连接发生错误', + type: 'error', + duration: 0 + }) + }, + webSocketOnMessage(e) { + const data = JSON.parse(e.data) + if (data.msgType === 'INFO') { + console.log('data', data) + this.$bus.emit(data.msg.data, data.msg.msgType) + } else if (data.msgType === 'ERROR') { + this.$notify({ + title: '', + message: data.msg, + dangerouslyUseHTMLString: true, + type: 'error', + duration: 0 + }) + } } } } diff --git a/nladmin-ui/src/main.js b/nladmin-ui/src/main.js index a4b8c91..8a80f47 100644 --- a/nladmin-ui/src/main.js +++ b/nladmin-ui/src/main.js @@ -46,6 +46,8 @@ import { addDateRange, handleTree, parseTime, resetForm, selectDictLabel, select import { getValueByCode } from '@/views/system/param/param' +import VueBus from 'vue-bus' + LogicFlow.use(Menu) Vue.component('tinymce', Tinymce) @@ -67,6 +69,7 @@ Vue.use(VueHighlightJS) Vue.use(mavonEditor) Vue.use(permission) Vue.use(dict) +Vue.use(VueBus) // 全局设置控件样式https://codeantenna.com/a/0IN5FMJk5h Element.Table.props.border = { type: Boolean, default: true } Element.TableColumn.props.align = { type: String, default: 'center' } diff --git a/nladmin-ui/src/store/modules/user.js b/nladmin-ui/src/store/modules/user.js index 5645e12..cf272e8 100644 --- a/nladmin-ui/src/store/modules/user.js +++ b/nladmin-ui/src/store/modules/user.js @@ -28,10 +28,9 @@ const user = { actions: { // 登录 Login({ commit }, userInfo) { - const rememberMe = userInfo.rememberMe + // const rememberMe = userInfo.rememberMe return new Promise((resolve, reject) => { login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => { - console.log('登录信息:', res) // setToken(res.token, rememberMe) commit('SET_TOKEN', res.token) setUserInfo(res.user, commit) @@ -48,7 +47,6 @@ const user = { GetInfo({ commit }) { return new Promise((resolve, reject) => { getInfo().then(res => { - console.log('用户信息:', res) setUserInfo(res, commit) resolve(res) }).catch(error => { @@ -84,6 +82,7 @@ export const logOut = (commit) => { } export const setUserInfo = (res, commit) => { + console.log(res) // 如果没有任何权限,则赋予一个默认的权限,避免请求死循环 if (res.roles && res.roles.length > 0) { commit('SET_ROLES', res.roles) diff --git a/nladmin-ui/src/views/generator/config.vue b/nladmin-ui/src/views/generator/config.vue index 03bade4..0ad0ed8 100644 --- a/nladmin-ui/src/views/generator/config.vue +++ b/nladmin-ui/src/views/generator/config.vue @@ -4,7 +4,7 @@
- 字段配置:{{ tableName }} + 字段配置:{{ table_name }} @@ -118,8 +106,8 @@ value="Like" /> @@ -179,13 +170,13 @@ 项目包的名称,生成的代码放到哪个包里面 - + 接口的名称,用于控制器与接口文档中 - 输入views文件夹下的绝对路径,不存在即创建 + 输入views文件夹下的目录,不存在即创建 @@ -197,8 +188,8 @@ - - + + 谨防误操作,请慎重选择 @@ -220,8 +211,8 @@ export default { mixins: [crud], data() { return { - activeName: 'first', tableName: '', tableHeight: 550, columnLoading: false, configLoading: false, dicts: [], syncLoading: false, genLoading: false, - form: { config_id: null, tableName: '', author: '', pack: '', path: '', moduleName: '', cover: '0', apiPath: '', prefix: '', apiAlias: null }, + activeName: 'first', table_name: '', tableHeight: 550, columnLoading: false, configLoading: false, dicts: [], syncLoading: false, genLoading: false, + form: { id: null, table_name: '', author: '', pack: '', path: '', module_name: '', cover: 'false', apiPath: '', prefix: '', api_alias: null }, rules: { author: [ { required: true, message: '作者不能为空', trigger: 'blur' } @@ -246,11 +237,10 @@ export default { }, created() { this.tableHeight = document.documentElement.clientHeight - 385 - this.tableName = this.$route.params.tableName + this.table_name = this.$route.params.tableName this.$nextTick(() => { this.init() - get(this.tableName).then(data => { - console.log(data) + get(this.table_name).then(data => { // 获取作者等信息 this.form = data this.form.cover = this.form.cover.toString() }) @@ -262,7 +252,7 @@ export default { methods: { beforeInit() { this.url = 'api/generator/columns' - const tableName = this.tableName + const tableName = this.table_name this.params = { tableName } return true }, @@ -294,7 +284,7 @@ export default { }, sync() { this.syncLoading = true - sync([this.tableName]).then(() => { + sync([this.table_name]).then(() => { this.init() this.notify('同步成功', 'success') this.syncLoading = false @@ -307,7 +297,7 @@ export default { save(this.data).then(res => { this.notify('保存成功', 'success') // 生成代码 - generator(this.tableName, 0).then(data => { + generator(this.table_name, 0).then(data => { this.genLoading = false this.notify('生成成功', 'success') }).catch(err => { @@ -324,15 +314,15 @@ export default { diff --git a/nladmin-ui/src/views/generator/index.vue b/nladmin-ui/src/views/generator/index.vue index 139fef0..6c192d4 100644 --- a/nladmin-ui/src/views/generator/index.vue +++ b/nladmin-ui/src/views/generator/index.vue @@ -79,9 +79,9 @@ export default { this.crud.optShow = { add: false, edit: false, del: false, download: false } }, methods: { - toGen(tableName) { + toGen(table_name) { // 生成代码 - generator(tableName, 0).then(data => { + generator(table_name, 0).then(data => { this.$notify({ title: '生成成功', type: 'success', @@ -89,16 +89,16 @@ export default { }) }) }, - toDownload(tableName) { + toDownload(table_name) { // 打包下载 - generator(tableName, 2).then(data => { - downloadFile(data, tableName, 'zip') + generator(table_name, 2).then(data => { + downloadFile(data, table_name, 'zip') }) }, sync() { const tables = [] this.crud.selections.forEach(val => { - tables.push(val.tableName) + tables.push(val.table_name) }) this.syncLoading = true sync(tables).then(() => { diff --git a/nladmin-ui/src/views/loki/view/index.vue b/nladmin-ui/src/views/loki/view/index.vue deleted file mode 100644 index bad4f01..0000000 --- a/nladmin-ui/src/views/loki/view/index.vue +++ /dev/null @@ -1,334 +0,0 @@ - - - - - diff --git a/nladmin-ui/src/views/lucene/api/log.js b/nladmin-ui/src/views/lucene/api/log.js new file mode 100644 index 0000000..0b7ef0a --- /dev/null +++ b/nladmin-ui/src/views/lucene/api/log.js @@ -0,0 +1,10 @@ +import request from '@/utils/request' + +export function delAll(id) { + return request({ + url: 'api/lucene/' + id, + method: 'delete' + }) +} + +export default { delAll } diff --git a/nladmin-ui/src/views/loki/api/loki.js b/nladmin-ui/src/views/lucene/api/lucene.js similarity index 62% rename from nladmin-ui/src/views/loki/api/loki.js rename to nladmin-ui/src/views/lucene/api/lucene.js index b5a3094..674bb2c 100644 --- a/nladmin-ui/src/views/loki/api/loki.js +++ b/nladmin-ui/src/views/lucene/api/lucene.js @@ -2,15 +2,15 @@ import request from '@/utils/request' export function getLogData(param) { return request({ - url: '/api/esLog/query', - method: 'post', + url: 'api/lucene/getAll', + method: 'get', data: param }) } -export function labelsValues(type) { +export function labelsValues() { return request({ - url: '/api/esLog/labels/' + type, + url: 'api/loki/labels/values', method: 'get' }) } diff --git a/nladmin-ui/src/views/lucene/index.vue b/nladmin-ui/src/views/lucene/index.vue new file mode 100644 index 0000000..051df24 --- /dev/null +++ b/nladmin-ui/src/views/lucene/index.vue @@ -0,0 +1,108 @@ + + + + + diff --git a/nladmin-ui/src/views/lucene/search.vue b/nladmin-ui/src/views/lucene/search.vue new file mode 100644 index 0000000..88a7655 --- /dev/null +++ b/nladmin-ui/src/views/lucene/search.vue @@ -0,0 +1,113 @@ + + + diff --git a/nladmin-ui/src/views/lucene/time.vue b/nladmin-ui/src/views/lucene/time.vue new file mode 100644 index 0000000..37b1601 --- /dev/null +++ b/nladmin-ui/src/views/lucene/time.vue @@ -0,0 +1,63 @@ + + + diff --git a/nladmin-ui/src/views/monitor/log/errorLog.vue b/nladmin-ui/src/views/monitor/log/errorLog.vue index ae322c6..fbee23f 100644 --- a/nladmin-ui/src/views/monitor/log/errorLog.vue +++ b/nladmin-ui/src/views/monitor/log/errorLog.vue @@ -31,18 +31,18 @@ - + - + @@ -83,9 +83,9 @@ export default { }, methods: { // 获取异常详情 - info(id) { + info(log_id) { this.dialog = true - getErrDetail(id).then(res => { + getErrDetail(log_id).then(res => { this.errorInfo = res.exception }) }, diff --git a/nladmin-ui/src/views/monitor/log/index.vue b/nladmin-ui/src/views/monitor/log/index.vue index c06463e..f37d57a 100644 --- a/nladmin-ui/src/views/monitor/log/index.vue +++ b/nladmin-ui/src/views/monitor/log/index.vue @@ -31,7 +31,7 @@ - + @@ -42,9 +42,9 @@ {{ scope.row.time }}ms - + diff --git a/nladmin-ui/src/views/system/dataPermission/index.vue b/nladmin-ui/src/views/system/dataPermission/index.vue index d5d447d..3f3882b 100644 --- a/nladmin-ui/src/views/system/dataPermission/index.vue +++ b/nladmin-ui/src/views/system/dataPermission/index.vue @@ -15,7 +15,7 @@ - +