text:
<file_sep>package com.mockst.mocking.controller;

import com.esnotary.framework.result.APIResult;
import com.esnotary.framework.result.APIResultUtil;
import com.mockst.mocking.config.WebConfigurer;
import com.mockst.mocking.model.menu.TreeMenu;
import com.mockst.mocking.module.menu.entity.MenuEntity;
import com.mockst.mocking.module.menu.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.List;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/28 20:35
 * @Description:
 */
@RestController
@RequestMapping(WebConfigurer.API_BASE_PATH+"/menu")
public class MenuController extends BaseAPIController{

    @Autowired
    private MenuService menuService;

    @RequestMapping("list")
    public APIResult list(){
        List<TreeMenu> list = menuService.findAllMenus();
        return APIResultUtil.returnSuccessResult(list);
    }
}
<file_sep>package com.mockst.mocking.module.repository.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * repository接口工程成员
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
@Table(name = "tb_repository_member")
public class RepositoryMemberEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//相关用户
    @Column(name = "user_id")
	private String userId;

	//相关工程
    @Column(name = "repository_id")
	private String repositoryId;

	/**
	 * 设置：相关用户
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}
	/**
	 * 获取：相关用户
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * 设置：相关工程
	 */
	public void setRepositoryId(String repositoryId) {
		this.repositoryId = repositoryId;
	}
	/**
	 * 获取：相关工程
	 */
	public String getRepositoryId() {
		return repositoryId;
	}

    @Override
    public String toString() {
        return "RepositoryMemberEntity{" +
                    " id='" + id + '\'' +
                    " userId='" + userId + '\'' +
                    " repositoryId='" + repositoryId + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.module.department.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.esnotary.framework.service.impl.BaseServiceImpl;

import com.mockst.mocking.module.department.dao.DepartmentDao;
import com.mockst.mocking.module.department.entity.DepartmentEntity;
import com.mockst.mocking.module.department.service.DepartmentService;

import java.util.List;
import java.util.Map;
//Import Package End
/**
 * 系统部门
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:06
 */
@Service("departmentService")
public class DepartmentServiceImpl extends BaseServiceImpl<DepartmentEntity> implements DepartmentService {
	@Autowired
	private DepartmentDao departmentDao;
	//Custom Generate Code Start
	@Override
	public List<Map<String, Object>> findByCondition(Map<String, Object> param) {
		return departmentDao.findByCondition(param);
	}
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.module.menu.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * 系统菜单
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-28 20:33:46
 */
@Table(name = "tb_menu")
public class MenuEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//部门名称
    @Column(name = "name")
	private String name;

	//备注
    @Column(name = "parent_id")
	private String parentId;

	//创建人
    @Column(name = "sort")
	private Integer sort;

	//是否显示
    @Column(name = "is_show")
	private String isShow;

	//
    @Column(name = "permission")
	private String permission;

	//类型 1菜单 2按钮
    @Column(name = "type")
	private String type;

	/**
	 * 设置：部门名称
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * 获取：部门名称
	 */
	public String getName() {
		return name;
	}

	/**
	 * 设置：备注
	 */
	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	/**
	 * 获取：备注
	 */
	public String getParentId() {
		return parentId;
	}

	/**
	 * 设置：创建人
	 */
	public void setSort(Integer sort) {
		this.sort = sort;
	}
	/**
	 * 获取：创建人
	 */
	public Integer getSort() {
		return sort;
	}

	/**
	 * 设置：是否显示
	 */
	public void setIsShow(String isShow) {
		this.isShow = isShow;
	}
	/**
	 * 获取：是否显示
	 */
	public String getIsShow() {
		return isShow;
	}

	/**
	 * 设置：
	 */
	public void setPermission(String permission) {
		this.permission = permission;
	}
	/**
	 * 获取：
	 */
	public String getPermission() {
		return permission;
	}

	/**
	 * 设置：类型 1菜单 2按钮
	 */
	public void setType(String type) {
		this.type = type;
	}
	/**
	 * 获取：类型 1菜单 2按钮
	 */
	public String getType() {
		return type;
	}

    @Override
    public String toString() {
        return "MenuEntity{" +
                    " id='" + id + '\'' +
                    " name='" + name + '\'' +
                    " parentId='" + parentId + '\'' +
                    " sort='" + sort + '\'' +
                    " isShow='" + isShow + '\'' +
                    " permission='" + permission + '\'' +
                    " type='" + type + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.module.repository.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.esnotary.framework.service.impl.BaseServiceImpl;

import com.mockst.mocking.module.repository.dao.RepositoryModuleDao;
import com.mockst.mocking.module.repository.entity.RepositoryModuleEntity;
import com.mockst.mocking.module.repository.service.RepositoryModuleService;
//Import Package End
/**
 * repository接口工程模块
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:41
 */
@Service("repositoryModuleService")
public class RepositoryModuleServiceImpl extends BaseServiceImpl<RepositoryModuleEntity> implements RepositoryModuleService {
	@Autowired
	private RepositoryModuleDao repositoryModuleDao;
    //Custom Generate Code Start
    //Custom Generate Code End
}
<file_sep>version: '2'
services:
  mocking-api:
    build: .
    volumes:
      - ./log:/home/mocking
    ports:
      - "8080:8080"
    environment:
      SPRING_PROFILES_ACTIVE: test<file_sep>package com.mockst.mocking.model.repository;

import lombok.Data;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/23 22:31
 * @Description:
 */
@Data
public class InterfacePropertyDTO {
    private String id;
    private String name;
    private String type;
    private String scope;
    private String parentId;
    private Boolean required;
    private String rule;
    private String value;
    private String description;
    private int depth;
}
<file_sep>package com.mockst.mocking.module.repository.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * repository接口参数
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
@Table(name = "tb_repository_interface_property")
public class RepositoryInterfacePropertyEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//参数名称
    @Column(name = "name")
	private String name;

	//类型String Number Boolean Object Array Function RegExp
    @Column(name = "type")
	private String type;

	//参数类型 request请求 response响应
    @Column(name = "scope")
	private String scope;

	//规则
    @Column(name = "rule")
	private String rule;

	//值
    @Column(name = "value")
	private String value;

	//是否必填
    @Column(name = "required")
	private Boolean required;

	//参数描述
    @Column(name = "description")
	private String description;

	//排序
    @Column(name = "sort")
	private Integer sort;

	//上级参数
    @Column(name = "parent_id")
	private String parentId;

	//是否删除 0未删除 1已删除
	@Column(name = "is_delete")
    private String isDelete;

	//所属接口
    @Column(name = "interface_id")
	private String interfaceId;

	//创建者
    @Column(name = "creator_id")
	private String creatorId;

    //删除时间
	@Column(name = "delete_time")
	private Date deleteTime;

	/**
	 * 设置：参数名称
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * 获取：参数名称
	 */
	public String getName() {
		return name;
	}

	/**
	 * 设置：类型String Number Boolean Object Array Function RegExp
	 */
	public void setType(String type) {
		this.type = type;
	}
	/**
	 * 获取：类型String Number Boolean Object Array Function RegExp
	 */
	public String getType() {
		return type;
	}

	/**
	 * 设置：参数类型 request请求 response响应
	 */
	public void setScope(String scope) {
		this.scope = scope;
	}
	/**
	 * 获取：参数类型 request请求 response响应
	 */
	public String getScope() {
		return scope;
	}

	/**
	 * 设置：规则
	 */
	public void setRule(String rule) {
		this.rule = rule;
	}
	/**
	 * 获取：规则
	 */
	public String getRule() {
		return rule;
	}

	/**
	 * 设置：值
	 */
	public void setValue(String value) {
		this.value = value;
	}
	/**
	 * 获取：值
	 */
	public String getValue() {
		return value;
	}

	/**
	 * 设置：是否必填
	 */
	public void setRequired(Boolean required) {
		this.required = required;
	}
	/**
	 * 获取：是否必填
	 */
	public Boolean getRequired() {
		return required;
	}

	/**
	 * 设置：参数描述
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * 获取：参数描述
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * 设置：排序
	 */
	public void setSort(Integer sort) {
		this.sort = sort;
	}
	/**
	 * 获取：排序
	 */
	public Integer getSort() {
		return sort;
	}

	/**
	 * 设置：上级参数
	 */
	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	/**
	 * 获取：上级参数
	 */
	public String getParentId() {
		return parentId;
	}

	public String getIsDelete() {
		return isDelete;
	}

	public void setIsDelete(String isDelete) {
		this.isDelete = isDelete;
	}

	/**
	 * 设置：所属接口
	 */
	public void setInterfaceId(String interfaceId) {
		this.interfaceId = interfaceId;
	}
	/**
	 * 获取：所属接口
	 */
	public String getInterfaceId() {
		return interfaceId;
	}

	/**
	 * 设置：创建者
	 */
	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}
	/**
	 * 获取：创建者
	 */
	public String getCreatorId() {
		return creatorId;
	}

	public Date getDeleteTime() {
		return deleteTime;
	}

	public void setDeleteTime(Date deleteTime) {
		this.deleteTime = deleteTime;
	}

	@Override
    public String toString() {
        return "RepositoryInterfacePropertyEntity{" +
                    " id='" + id + '\'' +
                    " name='" + name + '\'' +
                    " type='" + type + '\'' +
                    " scope='" + scope + '\'' +
                    " rule='" + rule + '\'' +
                    " value='" + value + '\'' +
                    " required='" + required + '\'' +
                    " description='" + description + '\'' +
                    " sort='" + sort + '\'' +
                    " parentId='" + parentId + '\'' +
					" isDelete='" + isDelete+ '\'' +
                    " interfaceId='" + interfaceId + '\'' +
                    " creatorId='" + creatorId + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
					" deleteTime='" + deleteTime + '\'' +
                    '}';
    }

}
<file_sep>package com.esnotary.framework.entity;

public abstract class BaseRequestParam {

    private String token;
    private String userId;
    private String signTime;
    private String signType;
    private String sign;
    private String format;
    private String charset;
    private String version;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getSignTime() {
        return signTime;
    }

    public void setSignTime(String signTime) {
        this.signTime = signTime;
    }

    public String getSignType() {
        return signType;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    @Override
    public String toString() {
        return "BaseRequestParam{" +
                "token='" + token + '\'' +
                ", signTime='" + signTime + '\'' +
                ", signType='" + signType + '\'' +
                ", sign='" + sign + '\'' +
                ", format='" + format + '\'' +
                ", charset='" + charset + '\'' +
                ", version='" + version + '\'' +
                '}';
    }
}
<file_sep>package com.mockst.mocking.config;

import com.esnotary.framework.util.RedisUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/7 23:10
 * @Description:
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,String> redisTemplate(LettuceConnectionFactory factory){
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public RedisUtil redisUtil(RedisTemplate<String,String> redisTemplate){
        return new RedisUtil(redisTemplate);
    }

}
<file_sep>package com.mockst.mocking.controller;

import com.esnotary.framework.entity.PageInfo;
import com.esnotary.framework.result.APIResult;
import com.esnotary.framework.result.APIResultUtil;
import com.github.pagehelper.PageHelper;
import com.mockst.mocking.config.WebConfigurer;
import com.mockst.mocking.module.menu.entity.MenuRoleEntity;
import com.mockst.mocking.module.menu.service.MenuRoleService;
import com.mockst.mocking.module.role.entity.RoleEntity;
import com.mockst.mocking.module.role.service.RoleService;
import com.mockst.mocking.module.user.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/3 13:55
 * @Description:
 */
@RestController
@RequestMapping(WebConfigurer.API_BASE_PATH+"/role")
public class RoleController extends BaseAPIController{

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuRoleService menuRoleService;

    /**
     * 列表
     * @return
     */
    @RequestMapping("list")
    public APIResult list(@RequestParam Map<String,Object> param,
                          @RequestParam(defaultValue = "1")Integer pageNo,
                          @RequestParam(defaultValue = "10")Integer pageSize){
        PageHelper.startPage(pageNo,pageSize);
        List<Map<String,Object>> list = roleService.findByCondition(param);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
        return APIResultUtil.returnSuccessResult(pageInfo);
    }

    /**
     * 新增
     * @param roleName
     * @param roleCode
     * @return
     */
    @RequestMapping("addRole")
    public APIResult addRole(HttpServletRequest request,
                             @RequestParam String roleName,
                             @RequestParam String roleCode,
                             @RequestParam String remark,
                             String[] menuIds){
        UserEntity userEntity = getCurrentUser(request);
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setRoleName(roleName);
        roleEntity.setRoleCode(roleCode);
        roleEntity.setRemark(remark);
        roleEntity.setCreatorId(userEntity.getId());
        roleService.save(roleEntity);
        if (menuIds!=null){
            for (String menuId :menuIds){
                MenuRoleEntity menuRoleEntity = new MenuRoleEntity();
                menuRoleEntity.setMenuId(menuId);
                menuRoleEntity.setRoleId(roleEntity.getId());
                menuRoleService.save(menuRoleEntity);
            }
        }
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 编辑
     * @param id
     * @param roleName
     * @param roleCode
     * @return
     */
    @RequestMapping("updateRole")
    public APIResult updateRole(@RequestParam String id,
                                @RequestParam String roleName,
                                @RequestParam String roleCode,
                                @RequestParam String remark,
                                String[] menuIds){
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setId(id);
        roleEntity.setRoleName(roleName);
        roleEntity.setRoleCode(roleCode);
        roleEntity.setRemark(remark);
        roleService.updateSelective(roleEntity);
        //删除旧的
        Example example = new Example(MenuRoleEntity.class);
        example.createCriteria().andEqualTo("roleId",id);
        menuRoleService.deleteByExample(example);
        //创建新的关系
        if (menuIds!=null){
            for (String menuId :menuIds){
                MenuRoleEntity menuRoleEntity = new MenuRoleEntity();
                menuRoleEntity.setMenuId(menuId);
                menuRoleEntity.setRoleId(roleEntity.getId());
                menuRoleService.save(menuRoleEntity);
            }
        }
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("deleteRole")
    public APIResult deleteRole(@RequestParam String id){
        roleService.delete(id);
        //删除旧的
        Example example = new Example(MenuRoleEntity.class);
        example.createCriteria().andEqualTo("roleId",id);
        menuRoleService.deleteByExample(example);
        return APIResultUtil.returnSuccessResult(null);
    }
}
<file_sep>package com.esnotary.framework.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.util.Map;
import java.util.Properties;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/25 11:12
 * @Description:
 */
public class VelocityUtil {

    static {
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
    }

    public static void outFile(String template, Map<String,Object> map, OutputStream outputStream){
        //渲染模板
        try(Writer sw = new OutputStreamWriter(outputStream);) {
            Template tpl = Velocity.getTemplate(template, "UTF-8" );
            VelocityContext context = new VelocityContext(map);
            tpl.merge(context, sw);
            sw.close();
        }catch (IOException e){
            throw new RuntimeException(e.getMessage(),e);
        }
    }

    public static String outFile(String template, Map<String,Object> map){
        //渲染模板
        try{
            Writer sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8" );
            VelocityContext context = new VelocityContext(map);
            tpl.merge(context, sw);
            sw.close();
            return sw.toString();
        }catch (IOException e){
            throw new RuntimeException(e.getMessage(),e);
        }
    }
}
<file_sep># using alpine-glibc instead of alpine  is mainly because JDK relies on glibc
FROM elfolink/alpine-java-wkhtmltopdf
VOLUME /tmp
# author
MAINTAINER linzhiwei <<EMAIL>>

RUN mkdir -p /usr/share/fonts/chinese/TrueType/
COPY ./fonts/simsun.ttc /usr/share/fonts/chinese/TrueType/
ADD mocking-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
# run container with base path:/opt
#WORKDIR /opt
<file_sep>package com.esnotary.framework.entity;

import com.esnotary.framework.util.GenUtil;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;

/**
 * @author linzhiwei
 * @Description:
 * @date 2019/3/29 11:31
 */
public abstract class BaseEntity implements Serializable{

    @Id
    @KeySql(genId = GenUtil.class)
    @Column(name = "id")
    protected String id;

    @Column(name = "create_time")
    protected Date createTime;
    @Column(name = "update_time")
    protected Date updateTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

}
<file_sep>package com.mockst.mocking.module.department.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * 系统部门
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:06
 */
@Table(name = "tb_department")
public class DepartmentEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//部门名称
    @Column(name = "department_name")
	private String departmentName;

	//创建人
	@Column(name = "creator_id")
	private String creatorId;

	//备注
    @Column(name = "remark")
	private String remark;

	/**
	 * 设置：部门名称
	 */
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	/**
	 * 获取：部门名称
	 */
	public String getDepartmentName() {
		return departmentName;
	}

	/**
	 * 设置：备注
	 */
	public void setRemark(String remark) {
		this.remark = remark;
	}
	/**
	 * 获取：备注
	 */
	public String getRemark() {
		return remark;
	}

	public String getCreatorId() {
		return creatorId;
	}

	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}

	@Override
    public String toString() {
        return "DepartmentEntity{" +
                    " id='" + id + '\'' +
                    " departmentName='" + departmentName + '\'' +
                    " remark='" + remark + '\'' +
					"creatorId='"+ creatorId +  '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.module.menu.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * 角色权限
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-28 20:33:46
 */
@Table(name = "tb_menu_role")
public class MenuRoleEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//相关用户
    @Column(name = "role_id")
	private String roleId;

	//相关工程
    @Column(name = "menu_id")
	private String menuId;

	/**
	 * 设置：相关用户
	 */
	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}
	/**
	 * 获取：相关用户
	 */
	public String getRoleId() {
		return roleId;
	}

	/**
	 * 设置：相关工程
	 */
	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}
	/**
	 * 获取：相关工程
	 */
	public String getMenuId() {
		return menuId;
	}

    @Override
    public String toString() {
        return "MenuRoleEntity{" +
                    " id='" + id + '\'' +
                    " roleId='" + roleId + '\'' +
                    " menuId='" + menuId + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.model.menu;

import lombok.Data;

import java.util.List;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/28 20:43
 * @Description:
 */
@Data
public class TreeMenu {
    private String id;
    private String parentId;
    private String label;
    private List<TreeMenu> children;
}
<file_sep>package com.mockst.mocking.module.repository.service;

import com.esnotary.framework.service.BaseService;
import com.mockst.mocking.module.repository.entity.RepositoryInterfaceOplogEntity;
//Import Package End
/**
 * 接口修改操作日志
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
public interface RepositoryInterfaceOplogService extends BaseService<RepositoryInterfaceOplogEntity> {
    //Custom Generate Code Start
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.module.repository.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * repository接口
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
@Table(name = "tb_repository_interface")
public class RepositoryInterfaceEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//接口名称
    @Column(name = "interface_name")
	private String interfaceName;

	//接口描述
    @Column(name = "description")
	private String description;

	//请求路径
    @Column(name = "url")
	private String url;

	//请求方式 GET POST
    @Column(name = "method")
	private String method;

	//返回状态码
    @Column(name = "status")
	private Integer status;

	//排序
    @Column(name = "sort")
	private Integer sort;

	//所属模块
    @Column(name = "module_id")
	private String moduleId;

	//创建者
    @Column(name = "creator_id")
	private String creatorId;

	/**
	 * 设置：接口名称
	 */
	public void setInterfaceName(String interfaceName) {
		this.interfaceName = interfaceName;
	}
	/**
	 * 获取：接口名称
	 */
	public String getInterfaceName() {
		return interfaceName;
	}

	/**
	 * 设置：接口描述
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * 获取：接口描述
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * 设置：请求路径
	 */
	public void setUrl(String url) {
		this.url = url;
	}
	/**
	 * 获取：请求路径
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * 设置：请求方式 GET POST
	 */
	public void setMethod(String method) {
		this.method = method;
	}
	/**
	 * 获取：请求方式 GET POST
	 */
	public String getMethod() {
		return method;
	}

	/**
	 * 设置：返回状态码
	 */
	public void setStatus(Integer status) {
		this.status = status;
	}
	/**
	 * 获取：返回状态码
	 */
	public Integer getStatus() {
		return status;
	}

	/**
	 * 设置：排序
	 */
	public void setSort(Integer sort) {
		this.sort = sort;
	}
	/**
	 * 获取：排序
	 */
	public Integer getSort() {
		return sort;
	}

	/**
	 * 设置：所属模块
	 */
	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}
	/**
	 * 获取：所属模块
	 */
	public String getModuleId() {
		return moduleId;
	}

	/**
	 * 设置：创建者
	 */
	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}
	/**
	 * 获取：创建者
	 */
	public String getCreatorId() {
		return creatorId;
	}

    @Override
    public String toString() {
        return "RepositoryInterfaceEntity{" +
                    " id='" + id + '\'' +
                    " interfaceName='" + interfaceName + '\'' +
                    " description='" + description + '\'' +
                    " url='" + url + '\'' +
                    " method='" + method + '\'' +
                    " status='" + status + '\'' +
                    " sort='" + sort + '\'' +
                    " moduleId='" + moduleId + '\'' +
                    " creatorId='" + creatorId + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.module.repository.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * repository接口工程模块
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:41
 */
@Table(name = "tb_repository_module")
public class RepositoryModuleEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//模块名称
    @Column(name = "module_name")
	private String moduleName;

	//模块描述
    @Column(name = "description")
	private String description;

	//排序
    @Column(name = "sort")
	private Integer sort;

	//所属工程
    @Column(name = "repository_id")
	private String repositoryId;

	//创建者
    @Column(name = "creator_id")
	private String creatorId;

	/**
	 * 设置：模块名称
	 */
	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}
	/**
	 * 获取：模块名称
	 */
	public String getModuleName() {
		return moduleName;
	}

	/**
	 * 设置：模块描述
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * 获取：模块描述
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * 设置：排序
	 */
	public void setSort(Integer sort) {
		this.sort = sort;
	}
	/**
	 * 获取：排序
	 */
	public Integer getSort() {
		return sort;
	}

	/**
	 * 设置：所属工程
	 */
	public void setRepositoryId(String repositoryId) {
		this.repositoryId = repositoryId;
	}
	/**
	 * 获取：所属工程
	 */
	public String getRepositoryId() {
		return repositoryId;
	}

	/**
	 * 设置：创建者
	 */
	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}
	/**
	 * 获取：创建者
	 */
	public String getCreatorId() {
		return creatorId;
	}

    @Override
    public String toString() {
        return "RepositoryModuleEntity{" +
                    " id='" + id + '\'' +
                    " moduleName='" + moduleName + '\'' +
                    " description='" + description + '\'' +
                    " sort='" + sort + '\'' +
                    " repositoryId='" + repositoryId + '\'' +
                    " creatorId='" + creatorId + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.module.role.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.esnotary.framework.service.impl.BaseServiceImpl;

import com.mockst.mocking.module.role.dao.RoleDao;
import com.mockst.mocking.module.role.entity.RoleEntity;
import com.mockst.mocking.module.role.service.RoleService;

import java.util.List;
import java.util.Map;
//Import Package End
/**
 * 系统角色
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:55:46
 */
@Service("roleService")
public class RoleServiceImpl extends BaseServiceImpl<RoleEntity> implements RoleService {
	@Autowired
	private RoleDao roleDao;

	//Custom Generate Code Start
	@Override
	public List<Map<String, Object>> findByCondition(Map<String, Object> condition) {
		return roleDao.findByCondition(condition);
	}
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking;

import com.alibaba.fastjson.JSONObject;
import com.mockst.mocking.model.repository.InterfacePropertyDTO;
import com.mockst.mocking.module.repository.entity.RepositoryInterfacePropertyEntity;
import com.mockst.mocking.module.repository.service.RepositoryInterfacePropertyService;
import com.mockst.mocking.module.user.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MockingApplicationTests {

	@Autowired
	private UserService userService;
	@Autowired
	private RepositoryInterfacePropertyService repositoryInterfacePropertyService;

	@Test
	public void prettyJson(){
		List<InterfacePropertyDTO> propertyDTOList = repositoryInterfacePropertyService.findProperiesByInterfaceId("283");

		List<InterfacePropertyDTO> request = propertyDTOList.stream().filter(s->"request".equals(s.getScope())).collect(Collectors.toList());
		List<InterfacePropertyDTO> response = propertyDTOList.stream().filter(s->"response".equals(s.getScope())).collect(Collectors.toList());

		List<InterfacePropertyDTO> requestlist = new ArrayList<>();
		request.stream().filter(s->"".equals(s.getParentId())).forEach(s->{
			s.setDepth(0);
			buildList(s,request,requestlist);
		});
		for(int i=0;i<requestlist.size();i++){
			InterfacePropertyDTO ip = requestlist.get(i);
			RepositoryInterfacePropertyEntity propertyEntity = new RepositoryInterfacePropertyEntity();
			propertyEntity.setId(ip.getId());
			propertyEntity.setSort(i+1);
			repositoryInterfacePropertyService.updateSelective(propertyEntity);
		}
		List<InterfacePropertyDTO> responselist = new ArrayList<>();
		response.stream().filter(s->"".equals(s.getParentId())).forEach(s->{
			s.setDepth(0);
			buildList(s,response,responselist);
		});
		for(int i=0;i<responselist.size();i++){
			InterfacePropertyDTO ip = responselist.get(i);
			RepositoryInterfacePropertyEntity propertyEntity = new RepositoryInterfacePropertyEntity();
			propertyEntity.setId(ip.getId());
			propertyEntity.setSort(i+1);
			repositoryInterfacePropertyService.updateSelective(propertyEntity);
		}
	}

	private void buildList(InterfacePropertyDTO p,List<InterfacePropertyDTO> tag,List<InterfacePropertyDTO> newTag){
		List<InterfacePropertyDTO> list =
				tag.stream().filter(s->p.getId().equals(s.getParentId())).collect(Collectors.toList());
		newTag.add(p);
		for (InterfacePropertyDTO pp:list){
			pp.setDepth(p.getDepth()+1);
			buildList(pp,tag,newTag);
		}
	}
}
<file_sep>package com.mockst.mocking.module.menu.service;

import com.esnotary.framework.service.BaseService;
import com.mockst.mocking.module.menu.entity.MenuRoleEntity;

import java.util.List;
//Import Package End
/**
 * 角色权限
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-28 20:33:46
 */
public interface MenuRoleService extends BaseService<MenuRoleEntity> {
    //Custom Generate Code Start
    List<String> findPermissionByRoleId(String roleId);
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.controller;
import com.esnotary.framework.util.RedisKeyConstants;
import com.esnotary.framework.util.RedisUtil;
import com.mockst.mocking.module.role.service.RoleService;
import com.mockst.mocking.module.user.entity.UserEntity;
import com.mockst.mocking.module.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author linzhiwei
 * @Description:
 * @date 2019/4/11 19:19
 */
public abstract class BaseAPIController {

    Logger LOGGER = LoggerFactory.getLogger(BaseAPIController.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    RoleService roleService;

    @Autowired
    UserService userService;

    /**
     * 导出（文件下载）
     * @param response
     * @param fileName 下载文件名
     * @param data 文件流
     */
    protected void downloadFile(HttpServletResponse response, String fileName,byte[] data){
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
            OutputStream out = response.getOutputStream();
            out.write(data);
            out.flush(); // 缓冲
            out.close();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }

    protected String getTokenKey(String token){
        return RedisKeyConstants.getRedisKey(RedisKeyConstants.USER_SESSION_KEY,token);
    }

    /**
     * 设置用户缓存
     * @param token
     * @param userEntity
     */
    protected void setCurrentUser(String token, UserEntity userEntity){
        if (userEntity == null){
            LOGGER.warn( " ->> 当前userEntity为空 <<- ");
            return;
        }
        String key = getTokenKey(token);
        redisUtil.set(key,userEntity.getId());
    }

    /**
     * 获取缓存的用户
     * @param request
     * @return
     */
    protected UserEntity getCurrentUser(HttpServletRequest request){
        String token = request.getParameter("token");
        String key = getTokenKey(token);
        String userId = (String) redisUtil.get(key);
        if (userId == null){
            LOGGER.warn(" ->> 当前userId不存在 <<- ");
            return null;
        }
        return userService.selectByKey(userId);
    }

    /**
     * 清除缓存的用户
     * @param request
     */
    protected void delCurrentUser(HttpServletRequest request){
        String token = request.getParameter("token");
        String key = getTokenKey(token);
        redisUtil.del(key);
    }
}
<file_sep>package com.mockst.mocking.module.repository.dao;

import com.mockst.mocking.model.repository.RepositoryInfoDTO;
import com.mockst.mocking.module.repository.entity.RepositoryEntity;
import com.mockst.mocking.module.user.entity.UserEntity;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
import java.util.Map;
//Import Package End
/**
 * repository接口工程
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
public interface RepositoryDao extends Mapper<RepositoryEntity> {

    //Custom Generate Code Start
    List<Map<String,Object>> findByCondition(Map<String, Object> param);
    RepositoryInfoDTO findById(String repositoryId);
    //Custom Generate Code End
}
<file_sep># mocking-api
> mocking-api是API接口管理系统的接口工程

# 项目依赖
> wkhtmltopdf

# 项目部署
初始化先创建一个数据库 mocking，修改项目中数据库账号密码，导入db/mockgin.sql初始化脚本

## 普通部署
```bash
jave -jar mocking-0.0.1-SNAPSHOT.jar
```

## docker部署
新建目录，将fonts目录 docker-compose.yml，Dockerfile及编译后的mocking-0.0.1-SNAPSHOT.jar拷贝过去
在目录下运行命令
```bash
docker-compose up -d
```
访问localhost:8080查看接口启动情况<file_sep>package com.mockst.mocking.module.repository.service;

import com.esnotary.framework.service.BaseService;
import com.mockst.mocking.module.repository.entity.RepositoryInterfaceEntity;
//Import Package End
/**
 * repository接口
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
public interface RepositoryInterfaceService extends BaseService<RepositoryInterfaceEntity> {
    //Custom Generate Code Start
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.model.repository;

import com.mockst.mocking.module.repository.entity.RepositoryEntity;
import com.mockst.mocking.module.repository.entity.RepositoryModuleEntity;
import com.mockst.mocking.module.user.entity.UserEntity;
import lombok.Data;

import java.util.List;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/26 20:52
 * @Description:
 */
@Data
public class RepositoryInfoDTO extends RepositoryEntity {

    private List<UserEntity> users ;
    private List<RepositoryModuleEntity> modules;

}
<file_sep>package com.esnotary.framework.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linzhiwei
 * @Description: 去除跨域限制
 * @date 2019/3/5 21:23
 */
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        // Access-Control-Max-Age
        response.setHeader("Access-Control-Max-Age", "3600");
        // Access-Control-Allow-Credentials
        response.setHeader("Access-Control-Allow-Origin", "*");
        // Access-Control-Allow-Methods
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        if ("OPTIONS".equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig config) {
    }
}
<file_sep>package com.mockst.mocking.module.repository.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.esnotary.framework.service.impl.BaseServiceImpl;
import com.mockst.mocking.constant.Constant;
import com.mockst.mocking.model.repository.InterfacePropertyDTO;
import com.mockst.mocking.model.repository.OutInterfaceDTO;
import com.mockst.mocking.module.repository.dao.RepositoryInterfacePropertyDao;
import com.mockst.mocking.module.repository.entity.RepositoryInterfaceEntity;
import com.mockst.mocking.module.repository.entity.RepositoryInterfacePropertyEntity;
import com.mockst.mocking.module.repository.service.RepositoryInterfacePropertyService;
import com.mockst.mocking.module.repository.service.RepositoryInterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
//Import Package End
/**
 * repository接口参数
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
@Service("repositoryInterfacePropertyService")
public class RepositoryInterfacePropertyServiceImpl extends BaseServiceImpl<RepositoryInterfacePropertyEntity> implements RepositoryInterfacePropertyService {
	@Autowired
	private RepositoryInterfacePropertyDao repositoryInterfacePropertyDao;

	//Custom Generate Code Start

	@Autowired
	private RepositoryInterfaceService repositoryInterfaceService;

	@Override
	@Transactional
	public void updateProperty(String interfaceId, List<RepositoryInterfacePropertyEntity> properties) {
		//删除旧的
		Example example = new Example(RepositoryInterfacePropertyEntity.class);
		example.createCriteria()
				.andEqualTo("interfaceId",interfaceId)
				.andEqualTo("isDelete", Constant.IS_NOT_DELETE);
		RepositoryInterfacePropertyEntity query = new RepositoryInterfacePropertyEntity();
		query.setIsDelete(Constant.IS_DELETE);
		query.setDeleteTime(new Date());
		updateByExampleSelective(query,example);
		if(!properties.isEmpty()){
			for (RepositoryInterfacePropertyEntity property:properties){
				update(property);
			}
		}
	}

	@Override
	public List<InterfacePropertyDTO> findProperiesByInterfaceId(String interfaceId) {
		return repositoryInterfacePropertyDao.findProperiesByInterfaceId(interfaceId);
	}

	@Override
	public OutInterfaceDTO findByInterfaceId(String interfaceId) {
		RepositoryInterfaceEntity repositoryInterface = repositoryInterfaceService.selectByKey(interfaceId);
		OutInterfaceDTO dto = new OutInterfaceDTO();
		dto.setInterfaceName(repositoryInterface.getInterfaceName());
		dto.setUrl(repositoryInterface.getUrl());
		dto.setDescription(repositoryInterface.getDescription());
		//todo 构建模拟数
//		String json ="{ \"name\": \"zhangsan\", \"age\": 18 ,\"code\":\"100001\"}";
//		JSONObject jsonObject = null;
//		try {
//			jsonObject = JSONObject.parseObject(json);
//		}catch (Exception e){
//		}
		String responseExample = JSONObject.toJSONString(new JSONObject(),true);
		dto.setResponseExample(responseExample);

		List<InterfacePropertyDTO> list = findProperiesByInterfaceId(interfaceId);
		List<InterfacePropertyDTO> request = list.stream().filter(s->"request".equals(s.getScope())).collect(Collectors.toList());
		List<InterfacePropertyDTO> response = list.stream().filter(s->"response".equals(s.getScope())).collect(Collectors.toList());
		List<InterfacePropertyDTO> requestlist = new ArrayList<>();
		request.stream().filter(s->"".equals(s.getParentId())).forEach(s->{
			s.setDepth(0);
			buildList(s,request,requestlist);
		});
		List<InterfacePropertyDTO> responselist = new ArrayList<>();
		response.stream().filter(s->"".equals(s.getParentId())).forEach(s->{
			s.setDepth(0);
			buildList(s,response,responselist);
		});
		dto.setRequestProperties(requestlist);
		dto.setResponseProperties(responselist);
		return dto;
	}

	private void buildList(InterfacePropertyDTO p,List<InterfacePropertyDTO> tag,List<InterfacePropertyDTO> newTag){
		List<InterfacePropertyDTO> list =
				tag.stream().filter(s->p.getId().equals(s.getParentId())).collect(Collectors.toList());
		newTag.add(p);
		for (InterfacePropertyDTO pp:list){
			pp.setDepth(p.getDepth()+1);
			buildList(pp,tag,newTag);
		}
	}

	//Custom Generate Code End
}
<file_sep>package com.esnotary.framework.util;

import com.alibaba.fastjson.JSONObject;
import com.esnotary.framework.result.APIResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/8 23:24
 * @Description:
 */
public class RequestUtil {

    public static void returnJson(HttpServletResponse response, Object result) throws Exception{
        String json = JSONObject.toJSONString(result);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        writer = response.getWriter();
        writer.print(json);
    }

    public static Map<String, Object> getParamterMap(HttpServletRequest request) {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        Map<String, String[]> map = request.getParameterMap();
        int len;
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            len = entry.getValue().length;
            if (len == 1) {
                params.put(entry.getKey(), entry.getValue()[0]);
            } else if (len > 1) {
                String[] vs = new String[entry.getValue().length];
                for (int i=0;i<vs.length;i++){
                    vs[i] = entry.getValue()[i];
                }
                params.put(entry.getKey(), vs);
            }
        }
        return params;
    }

}
<file_sep>package com.mockst.mocking.module.role.dao;

import com.mockst.mocking.module.role.entity.RoleEntity;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
import java.util.Map;
//Import Package End
/**
 * 系统角色
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:55:46
 */
public interface RoleDao extends Mapper<RoleEntity> {
    //Custom Generate Code Start
    List<Map<String,Object>> findByCondition(Map<String, Object> condition);
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.module.menu.service;

import com.esnotary.framework.service.BaseService;
import com.mockst.mocking.model.menu.TreeMenu;
import com.mockst.mocking.module.menu.entity.MenuEntity;
import com.mockst.mocking.module.user.entity.UserEntity;

import java.util.List;
//Import Package End
/**
 * 系统菜单
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-28 20:33:46
 */
public interface MenuService extends BaseService<MenuEntity> {
    //Custom Generate Code Start
    List<TreeMenu> findAllMenus();

    List<String> findUser(UserEntity userEntity);
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.module.role.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * 系统角色
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:55:46
 */
@Table(name = "tb_role")
public class RoleEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//角色名
    @Column(name = "role_name")
	private String roleName;

	//角色编码
    @Column(name = "role_code")
	private String roleCode;

	//创建人
    @Column(name = "creator_id")
	private String creatorId;

	//备注
    @Column(name = "remark")
	private String remark;

	/**
	 * 设置：角色名
	 */
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	/**
	 * 获取：角色名
	 */
	public String getRoleName() {
		return roleName;
	}

	/**
	 * 设置：角色编码
	 */
	public void setRoleCode(String roleCode) {
		this.roleCode = roleCode;
	}
	/**
	 * 获取：角色编码
	 */
	public String getRoleCode() {
		return roleCode;
	}

	/**
	 * 设置：创建人
	 */
	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}
	/**
	 * 获取：创建人
	 */
	public String getCreatorId() {
		return creatorId;
	}

	/**
	 * 设置：备注
	 */
	public void setRemark(String remark) {
		this.remark = remark;
	}
	/**
	 * 获取：备注
	 */
	public String getRemark() {
		return remark;
	}

    @Override
    public String toString() {
        return "RoleEntity{" +
                    " id='" + id + '\'' +
                    " roleName='" + roleName + '\'' +
                    " roleCode='" + roleCode + '\'' +
                    " creatorId='" + creatorId + '\'' +
                    " remark='" + remark + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.constant;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/24 10:15
 * @Description:
 */
public class Constant {
    public static final String IS_DELETE = "1";
    public static final String IS_NOT_DELETE = "0";
    public static final String ADMIN_ID="1";
}
<file_sep>package com.mockst.mocking.module.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.esnotary.framework.service.impl.BaseServiceImpl;

import com.mockst.mocking.module.user.dao.UserDao;
import com.mockst.mocking.module.user.entity.UserEntity;
import com.mockst.mocking.module.user.service.UserService;

import java.util.List;
import java.util.Map;
//Import Package End
/**
 * 系统用户
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:48:21
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService {
	@Autowired
	private UserDao userDao;

	//Custom Generate Code Start
	@Override
	public List<Map<String, Object>> findByCondition(Map<String, Object> param) {
		return userDao.findByCondition(param);
	}
    //Custom Generate Code End
}
<file_sep>package com.mockst.mocking.module.repository.entity;

import java.io.Serializable;
import java.util.Date;
import com.esnotary.framework.entity.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 * repository接口工程
 *
 * @author ${author}
 * @email ${email}
 * @date 2019-08-03 10:56:40
 */
@Table(name = "tb_repository")
public class RepositoryEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	//项目名称
    @Column(name = "repository_name")
	private String repositoryName;

	//描述
    @Column(name = "description")
	private String description;

	//创建者
    @Column(name = "creator_id")
	private String creatorId;

	//发布版本
    @Column(name = "r_version")
	private String rVersion;

	/**
	 * 设置：项目名称
	 */
	public void setRepositoryName(String repositoryName) {
		this.repositoryName = repositoryName;
	}
	/**
	 * 获取：项目名称
	 */
	public String getRepositoryName() {
		return repositoryName;
	}

	/**
	 * 设置：描述
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * 获取：描述
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * 设置：创建者
	 */
	public void setCreatorId(String creatorId) {
		this.creatorId = creatorId;
	}
	/**
	 * 获取：创建者
	 */
	public String getCreatorId() {
		return creatorId;
	}

	/**
	 * 设置：发布版本
	 */
	public void setRVersion(String rVersion) {
		this.rVersion = rVersion;
	}
	/**
	 * 获取：发布版本
	 */
	public String getRVersion() {
		return rVersion;
	}

    @Override
    public String toString() {
        return "RepositoryEntity{" +
                    " id='" + id + '\'' +
                    " repositoryName='" + repositoryName + '\'' +
                    " description='" + description + '\'' +
                    " creatorId='" + creatorId + '\'' +
                    " rVersion='" + rVersion + '\'' +
                    " createTime='" + createTime + '\'' +
                    " updateTime='" + updateTime + '\'' +
                    '}';
    }

}
<file_sep>package com.mockst.mocking.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esnotary.framework.entity.PageInfo;
import com.esnotary.framework.result.APIResult;
import com.esnotary.framework.result.APIResultUtil;
import com.esnotary.framework.util.VelocityUtil;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.params.Param;
import com.github.pagehelper.PageHelper;
import com.mockst.mocking.config.WebConfigurer;
import com.mockst.mocking.constant.Constant;
import com.mockst.mocking.model.repository.*;
import com.mockst.mocking.module.department.entity.DepartmentEntity;
import com.mockst.mocking.module.repository.entity.*;
import com.mockst.mocking.module.repository.service.*;
import com.mockst.mocking.module.user.entity.UserEntity;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/11 21:43
 * @Description:
 */
@RestController
@RequestMapping(WebConfigurer.API_BASE_PATH+"/repository")
public class RepositoryController extends BaseAPIController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RepositoryMemberService repositoryMemberService;
    @Autowired
    private RepositoryModuleService repositoryModuleService;
    @Autowired
    private RepositoryInterfaceService repositoryInterfaceService;
    @Autowired
    private RepositoryInterfacePropertyService repositoryInterfacePropertyService;
    /**
     * 列表
     * @return
     */
    @RequestMapping("list")
    public APIResult list(@RequestParam Map<String,Object> param,
                          @RequestParam(defaultValue = "1")Integer pageNo,
                          @RequestParam(defaultValue = "10")Integer pageSize,
                            HttpServletRequest request){
        UserEntity userEntity = getCurrentUser(request);
        PageHelper.startPage(pageNo,pageSize);
        if (!Constant.ADMIN_ID.equals(userEntity.getId())){
            param.put("memberId",userEntity.getId());
        }
        List<Map<String,Object>> list = repositoryService.findByCondition(param);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
        return APIResultUtil.returnSuccessResult(pageInfo);
    }

    /**
     * 新增
     */
    @RequestMapping("addRepository")
    public APIResult addRepository(HttpServletRequest request,
                                   @RequestParam String repositoryName,
                                   @RequestParam String description,
                                    String[] userIds){
        UserEntity userEntity = getCurrentUser(request);
        RepositoryEntity repositoryEntity = new RepositoryEntity();
        repositoryEntity.setRepositoryName(repositoryName);
        repositoryEntity.setDescription(description);
        repositoryEntity.setCreatorId(userEntity.getId());
        repositoryService.save(repositoryEntity);
        if (userIds!=null){
            for (String userId:userIds){
                RepositoryMemberEntity repositoryMemberEntity  = new RepositoryMemberEntity();
                repositoryMemberEntity.setRepositoryId(repositoryEntity.getId());
                repositoryMemberEntity.setUserId(userId);
                repositoryMemberService.save(repositoryMemberEntity);
            }
        }
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping("updateRepository")
    public APIResult updateRepository(@RequestParam String id,
                                      @RequestParam String repositoryName,
                                      @RequestParam String description,
                                      String[] userIds){
        RepositoryEntity repositoryEntity = new RepositoryEntity();
        repositoryEntity.setId(id);
        repositoryEntity.setRepositoryName(repositoryName);
        repositoryEntity.setDescription(description);
        repositoryService.updateSelective(repositoryEntity);
        //删除旧的
        Example query = new Example(RepositoryMemberEntity.class);
        query.createCriteria().andEqualTo("repositoryId",id);
        repositoryMemberService.deleteByExample(query);
        if (userIds!=null){
            for (String userId:userIds){
                RepositoryMemberEntity repositoryMemberEntity  = new RepositoryMemberEntity();
                repositoryMemberEntity.setRepositoryId(repositoryEntity.getId());
                repositoryMemberEntity.setUserId(userId);
                repositoryMemberService.save(repositoryMemberEntity);
            }
        }
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("deleteRepository")
    public APIResult deleteRepository(@RequestParam String id){
        repositoryService.delete(id);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 项目信息
     */
    @RequestMapping("repositoryInfo")
    public APIResult repositoryInfo(@RequestParam String repositoryId){
        RepositoryInfoDTO repositoryInfo = repositoryService.findById(repositoryId);
        return APIResultUtil.returnSuccessResult(repositoryInfo);
    }

    /**
     * 导出接口文档
     * @param repositoryId
     */
    @RequestMapping("outRepositoryInfo")
    public void outRepositoryInfo(@RequestParam String repositoryId, HttpServletResponse response){
        String json ="{ \"name\": \"zhangsan\", \"age\": 18 ,\"code\":\"100001\"}";
        if(StringUtils.isBlank(json)){
            return ;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(json);
        }catch (Exception e){
            return ;
        }
        RepositoryEntity repositoryEntity = repositoryService.selectByKey(repositoryId);
        String responseExample = JSONObject.toJSONString(jsonObject,true);
        RepositoryModuleEntity query = new RepositoryModuleEntity();
        query.setRepositoryId(repositoryId);
        List<RepositoryModuleEntity> list = repositoryModuleService.select(query);
        JSONObject data = new JSONObject();
        JSONArray modules = new JSONArray();
        list.forEach(m->{
            JSONObject module = new JSONObject();
            module.put("moduleName",m.getModuleName());
            JSONArray interfaces = new JSONArray();
            RepositoryInterfaceEntity repositoryInterface = new RepositoryInterfaceEntity();
            repositoryInterface.setModuleId(m.getId());
            List<RepositoryInterfaceEntity> interfaceList = repositoryInterfaceService.select(repositoryInterface);
            interfaceList.forEach(i->{
                OutInterfaceDTO it = repositoryInterfacePropertyService.findByInterfaceId(i.getId());
                interfaces.add(it);
            });
            module.put("interfaces",interfaces);
            modules.add(module);
        });
        data.put("modules",modules);
        String template = "templates/api.vm";
        try (OutputStream out = response.getOutputStream()){
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(repositoryEntity.getRepositoryName()+".pdf", "utf-8"));
            String html = VelocityUtil.outFile(template,data);
            Pdf pdf = new Pdf();
            pdf.addPageFromString(html);
            pdf.addParam(new Param("--page-size","A4"));
            pdf.addParam(new Param("--margin-left","20"));
            pdf.addParam(new Param("--margin-right","20"));
            pdf.addParam(new Param("--margin-top","20"));
            pdf.addParam(new Param("--margin-bottom", "20"));
            IOUtils.write(pdf.getPDF(),out);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 模块信息
     */
    @RequestMapping("moduleInfo")
    public APIResult moduleInfo(@RequestParam String moduleId){
        RepositoryInterfaceEntity query = new RepositoryInterfaceEntity();
        query.setModuleId(moduleId);
        List<RepositoryInterfaceEntity> list = repositoryInterfaceService.select(query);
        JSONObject data = new JSONObject();
        data.put("interfaces",list);
        return APIResultUtil.returnSuccessResult(data);
    }

    /**
     * 添加模块
     * @return
     */
    @RequestMapping("addModule")
    public APIResult addModule(HttpServletRequest request,@RequestParam String repositoryId,@RequestParam String moduleName,@RequestParam String description){
        UserEntity userEntity = getCurrentUser(request);
        RepositoryModuleEntity moduleEntity = new RepositoryModuleEntity();
        moduleEntity.setModuleName(moduleName);
        moduleEntity.setDescription(description);
        moduleEntity.setCreatorId(userEntity.getId());
        moduleEntity.setRepositoryId(repositoryId);
        repositoryModuleService.save(moduleEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 更新模块
     */
    @RequestMapping("updateModule")
    public APIResult updateModule(@RequestParam String moduleId,@RequestParam String moduleName,@RequestParam String description){
        RepositoryModuleEntity moduleEntity = new RepositoryModuleEntity();
        moduleEntity.setId(moduleId);
        moduleEntity.setModuleName(moduleName);
        moduleEntity.setDescription(description);
        repositoryModuleService.updateSelective(moduleEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 删除模块
     */
    @RequestMapping("deleteModule")
    public APIResult deleteModule(@RequestParam String moduleId){
        repositoryModuleService.delete(moduleId);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 添加接口
     * @return
     */
    @RequestMapping("addInterface")
    public APIResult addInterface(HttpServletRequest request, RepositoryInterfaceDTO repositoryInterfaceDTO){
        UserEntity userEntity = getCurrentUser(request);
        RepositoryInterfaceEntity repositoryInterfaceEntity = new RepositoryInterfaceEntity();
        BeanUtils.copyProperties(repositoryInterfaceDTO,repositoryInterfaceEntity);
        repositoryInterfaceEntity.setCreatorId(userEntity.getId());
        repositoryInterfaceService.save(repositoryInterfaceEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 编辑接口
     * @return
     */
    @RequestMapping("updateInterface")
    public APIResult updateInterface(RepositoryInterfaceDTO repositoryInterfaceDTO){
        RepositoryInterfaceEntity repositoryInterfaceEntity = new RepositoryInterfaceEntity();
        BeanUtils.copyProperties(repositoryInterfaceDTO,repositoryInterfaceEntity);
        repositoryInterfaceService.updateSelective(repositoryInterfaceEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 删除接口
     */
    @RequestMapping("deleteInterface")
    public APIResult deleteInterface(@RequestParam String interfaceId){
        repositoryInterfaceService.delete(interfaceId);
        return APIResultUtil.returnSuccessResult(null);
    }

    @RequestMapping("propertyInfo")
    public APIResult propertyInfo(@RequestParam String interfaceId){
        List<InterfacePropertyDTO> list = repositoryInterfacePropertyService.findProperiesByInterfaceId(interfaceId);
        JSONObject data = new JSONObject();
        RepositoryInterfaceEntity repositoryInterfaceEntity = repositoryInterfaceService.selectByKey(interfaceId);
        data.put("url",repositoryInterfaceEntity.getUrl());
        data.put("method",repositoryInterfaceEntity.getMethod());
        data.put("requestProperties",
                list.stream().filter(s->"request".equals(s.getScope()))
                        .collect(Collectors.toList()));
        data.put("responseProperties",
                list.stream().filter(s->"response".equals(s.getScope()))
                        .collect(Collectors.toList()));
        return APIResultUtil.returnSuccessResult(data);
    }

    /**
     * 添加临时属性
     * @param interfacePropertyDTO
     * @return
     */
    @RequestMapping("addProperty")
    public APIResult addProperty(InterfacePropertyDTO interfacePropertyDTO){
        RepositoryInterfacePropertyEntity propertyEntity = new RepositoryInterfacePropertyEntity();
        BeanUtils.copyProperties(interfacePropertyDTO,propertyEntity);
        propertyEntity.setIsDelete(Constant.IS_DELETE);
        propertyEntity.setDeleteTime(new Date());
        repositoryInterfacePropertyService.save(propertyEntity);
        return APIResultUtil.returnSuccessResult(propertyEntity);
    }

    /**
     * 更新属性
     * @param interfacePropertyJson
     * @return
     */
    @RequestMapping("updateProperty")
    public APIResult updateProperty(@RequestParam String interfacePropertyJson){
        InterfacePropertyForm form = JSONObject.parseObject(interfacePropertyJson,InterfacePropertyForm.class);
        List<RepositoryInterfacePropertyEntity> properties = new ArrayList<>();
        for (int i=0;i<form.getRequestProperties().size();i++){
            InterfacePropertyDTO p = form.getRequestProperties().get(i);
            RepositoryInterfacePropertyEntity propertyEntity = new RepositoryInterfacePropertyEntity();
            BeanUtils.copyProperties(p,propertyEntity);
            propertyEntity.setScope("request");
            propertyEntity.setSort(i+1);
            propertyEntity.setInterfaceId(form.getInterfaceId());
            propertyEntity.setIsDelete(Constant.IS_NOT_DELETE);
            propertyEntity.setDeleteTime(null);
            propertyEntity.setCreateTime(new Date());
            properties.add(propertyEntity);
        }
        for (int i=0;i<form.getResponseProperties().size();i++){
            InterfacePropertyDTO p = form.getResponseProperties().get(i);
            RepositoryInterfacePropertyEntity propertyEntity = new RepositoryInterfacePropertyEntity();
            BeanUtils.copyProperties(p,propertyEntity);
            propertyEntity.setScope("response");
            propertyEntity.setSort(i+1);
            propertyEntity.setInterfaceId(form.getInterfaceId());
            propertyEntity.setIsDelete(Constant.IS_NOT_DELETE);
            propertyEntity.setDeleteTime(null);
            propertyEntity.setCreateTime(new Date());
            properties.add(propertyEntity);
        }
        repositoryInterfacePropertyService.updateProperty(form.getInterfaceId(),properties);
        return APIResultUtil.returnSuccessResult(null);
    }

}
<file_sep>package com.mockst.mocking.controller;

import com.esnotary.framework.entity.PageInfo;
import com.esnotary.framework.result.APIResult;
import com.esnotary.framework.result.APIResultUtil;
import com.github.pagehelper.PageHelper;
import com.mockst.mocking.config.WebConfigurer;
import com.mockst.mocking.module.department.entity.DepartmentEntity;
import com.mockst.mocking.module.department.service.DepartmentService;
import com.mockst.mocking.module.role.entity.RoleEntity;
import com.mockst.mocking.module.role.service.RoleService;
import com.mockst.mocking.module.user.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zhiwei
 * @Date: 2019/8/3 23:27
 * @Description:
 */
@RestController
@RequestMapping(WebConfigurer.API_BASE_PATH+"/department")
public class DepartmentController extends BaseAPIController{

    @Autowired
    private DepartmentService departmentService;

    /**
     * 列表
     * @return
     */
    @RequestMapping("list")
    public APIResult list(@RequestParam Map<String,Object> param,
                          @RequestParam(defaultValue = "1")Integer pageNo,
                          @RequestParam(defaultValue = "10")Integer pageSize){
        PageHelper.startPage(pageNo,pageSize);
        List<Map<String,Object>> list = departmentService.findByCondition(param);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
        return APIResultUtil.returnSuccessResult(pageInfo);
    }

    /**
     * 新增
     */
    @RequestMapping("addDepartment")
    public APIResult addDepartment(HttpServletRequest request,@RequestParam String departmentName, @RequestParam String remark){
        UserEntity userEntity = getCurrentUser(request);
        DepartmentEntity departmentEntity = new DepartmentEntity();
        departmentEntity.setDepartmentName(departmentName);
        departmentEntity.setRemark(remark);
        departmentEntity.setCreatorId(userEntity.getId());
        departmentService.save(departmentEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping("updateDepartment")
    public APIResult updateDepartment(@RequestParam String id,@RequestParam String departmentName,@RequestParam String remark){
        DepartmentEntity departmentEntity = new DepartmentEntity();
        departmentEntity.setId(id);
        departmentEntity.setDepartmentName(departmentName);
        departmentEntity.setRemark(remark);
        departmentService.updateSelective(departmentEntity);
        return APIResultUtil.returnSuccessResult(null);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("deleteDepartment")
    public APIResult deleteDepartment(@RequestParam String id){
        departmentService.delete(id);
        return APIResultUtil.returnSuccessResult(null);
    }
}

languages: Java Markdown Dockerfile YAML

repo_language: Java

repo_name: Mr-lin/mocking-api


text:
<repo_name>suvonkar/FirstRallyApp<file_sep>/App.js
Ext.define('CustomApp', {
	extend : 'Rally.app.App',
	componentCls : 'app',
	launch : function() {
		this._createKanbanStateDropDown();
	},

	_createKanbanStateDropDown : function() {
		this.myKanbanStateDropdown = Ext.create(
				'Rally.ui.combobox.FieldValueComboBox', {
					model : 'UserStory',
					field : 'c_KanbanState',
					fieldLabel : 'Kanban State: ',
					listeners : {
						ready : function(fieldValueComboBox) {
							this._loadData();
						},
						select : function(combo) {
							this._loadData();
						},
						scope : this
					}
				});
		this.add(this.myKanbanStateDropdown);
	},

	_loadData : function() {
		var selectedKanbanState = this.myKanbanStateDropdown.getRecord().get(
				'value');
		console.log('selectedKanbanState ' + selectedKanbanState);
		var filter = [ {
			property : 'c_KanbanState',
			operator : '=',
			value : selectedKanbanState
		} ];
		if (this.myStore) {
			this.myStore.setFilter(filter);
			this.myStore.load();
		} else {
			this.myStore = Ext.create("Rally.data.wsapi.Store", {
				model : 'User Story',
				autoLoad : true,
				listeners : {
					load : function(myStore, myData, success) {
						console.log("my data is ", myData);
						if (!this.myGrid) {
							this._createDataGrid(this.myStore);
						}
					},
					scope : this
				},
				fetch : [ 'FormattedID', 'Name', 'Parent', 'Owner',
						'InProgressDate', 'ScheduleState', 'Project',
						'c_KanbanState' ],
				context : {
					project : Rally.environment.getContext().getProject()
				},
				filters : filter
			});
		}
	},

	_createDataGrid : function(myDataStore) {
		this.myGrid = Ext.create('Rally.ui.grid.Grid', {
			store : myDataStore,
			columnCfgs : [ {
				text : 'Formated ID',
				dataIndex : 'FormattedID'
			}, {
				text : 'Name',
				dataIndex : 'Name'
			}, {
				text : 'Parent Feature',
				dataIndex : 'Parent'
			}, {
				text : 'Owner',
				dataIndex : 'Owner'
			}, {
				text : 'In Progress Date',
				dataIndex : 'InProgressDate'
			}, {
				text : 'Delay in Acceptance',
				dataIndex : 'InProgressDate',
				renderer : function(value) {
					if (value !== null) {
						var today = new Date();
						var one_day = 1000 * 60 * 60 * 24;

						var date1_ms = value.getTime();
						var today_ms = today.getTime();

						var difference_ms = today_ms - date1_ms;

						return Math.round(difference_ms / one_day);
					} else {
						return 0;
					}
				}
			} ]
		});

		this.add(this.myGrid);
	}
});

branch_name: refs/heads/master

repo_language: JavaScript

repo_name: suvonkar/FirstRallyApp


text:
<file_sep>import pathlib
import argparse
import time
import requests
import uuid
from datetime import datetime
from fake_headers import Headers
import concurrent.futures as cf

def args_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-u",
        "--url",
        help="The url to bruteforce",
        type=str,
        required=True
    )
    parser.add_argument(
        "-w",
        "--wordlist",
        help="The wordlist to use",
        type=str,
        required=True
    )
    parser.add_argument(
        "-t",
        "--threads",
        help="The number of concurrent threads to use",
        type=int,
        required=False,
        default=10
    )
    args = parser.parse_args()
    return args

def fetch(url, session, log_file):
    fake_header = Headers(headers=False).generate()

    try:
        with session.get(url, headers=fake_header) as response:
            status = response.status_code

        if status < 400:
            print(f"+ [+] Found: {url.strip()} (Status: {status})")
            return True
    except requests.exceptions.RequestException as e:
        print(f"+ [!] An exception occurred: See log file... [!]")
        with log_file.open(mode="a") as f:
            f.write(str(e)+"\n")

def count_wordlist_len(wordlist):
    with wordlist.open(mode="r") as f:
        wordlist_len = f.readlines()
    return len(wordlist_len)

def main():
    start = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
    ts = time.perf_counter()

    args = args_parser()
    wordlist = pathlib.Path(args.wordlist).resolve()
    wordlist_len = count_wordlist_len(wordlist)
    urls = (f"{args.url}/{url}" for url in wordlist.open(mode="r"))
    urls_found = 0
    log_filename = str(uuid.uuid4())
    log_file = pathlib.Path(f"{log_filename}.log").resolve()

    print("+"+"-"*50+"+")
    print(f"+ [*] Started at {start}")
    print("+"+"-"*50+"+")
    print(f"+ [*] Url: {args.url}")
    print(f"+ [*] Wordlist: {args.wordlist}")
    print(f"+ [*] {wordlist_len} words in wordlist")
    print(f"+ [*] Threads: {args.threads}")
    print("+"+"-"*50+"+")

    with requests.Session() as session:
        with cf.ThreadPoolExecutor(max_workers=args.threads) as executor:
            try:
                tasks = [executor.submit(
                    fetch, url, session, log_file) for url in urls]

                for task in cf.as_completed(tasks):
                    result = task.result()
                    if result:
                        urls_found += 1
            except KeyboardInterrupt:
                print(f"\n+ [!] Keyboard interrupt detected, exiting... [!]")
                pass

    end = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
    te = time.perf_counter()

    print("+"+"-"*50+"+")
    print(f"+ [*] Finished at {end}")
    print(f"+ [*] Found {urls_found} urls in {round(te-ts,2)} seconds")
    print("+"+"-"*50+"+")

if __name__ == "__main__":
    main()
<file_sep>beautifulsoup4==4.9.3
bs4==0.0.1
certifi==2020.11.8
chardet==3.0.4
fake-headers==1.0.2
html5lib==1.1
idna==2.10
requests==2.25.0
six==1.15.0
soupsieve==2.0.1
toml==0.10.2
urllib3==1.26.2
webencodings==0.5.1
<file_sep># WebDirEnum

Simple multithreaded tool to bruteforce web directories.

## Installation

Install requirements with pip.
```
pip install -r requirements.txt
```
## Arguments

|Flags|Args         |Description                                         |
|-----|-------------|----------------------------------------------------|
|-u   |--url        |The url to bruteforce (must provide http schema)    |
|-w   |--wordlist   |The wordlist to use                                 |
|-t   |--threads    |The number of concurrent threads to use (Default 20)|

## Usage

```
python webdirenum.py -u http://example.com -w wordlist.txt -t 30
```

languages: Markdown Text Python

repo_language: Markdown

repo_name: luisfilipefa/web-dir-enum


text:
<repo_name>paigeshin/AOS_Kotlin_function_with_function_argument_example<file_sep>/README.md
### MainActivity

```kotlin
class MainActivity : AppCompatActivity() {
    val fruitsList = listOf(Fruit("Mango","Tom"), Fruit("Apple","Joe"),Fruit("Banana","Mark") , Fruit("Guava","Mike"),Fruit("Lemon","Mike"),Fruit("Pear","Frank"),Fruit("Orange","Joe"))
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        my_recycler_view.setBackgroundColor(Color.YELLOW)
        my_recycler_view.layoutManager = LinearLayoutManager(this)

        //4. send function argument which is defined on this activity to recyclerView
        my_recycler_view.adapter = MyRecyclerViewAdapter(fruitsList, {selectedFruitItem: Fruit -> listItemClicked(selectedFruitItem)})
    }

    //3. define function which takes `fruit` from adapter
    private fun listItemClicked(fruit: Fruit) {
        Toast.makeText(this@MainActivity, "Supplier name is ${fruit.supplier}", Toast.LENGTH_LONG).show()
    }

}
```

### RecyclerView Adapter

```kotlin
// 1. This RecyclerViewAdapter second argument as Function.
class MyRecyclerViewAdapter(
    private val fruitsList:List<Fruit>,
    private val clickListener:(Fruit) -> Unit)
    : RecyclerView.Adapter<MyViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
      val layoutInflater = LayoutInflater.from(parent.context)
        val listItem = layoutInflater.inflate(R.layout.list_item,parent,false)
        return MyViewHolder(listItem)
    }

    override fun getItemCount(): Int {
       return fruitsList.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(fruitsList.get(position), clickListener)
    }
}

class MyViewHolder(val view : View) : RecyclerView.ViewHolder(view){

    // 2. ViewHolder bind function takes second argument as Function by passing `fruit` object.
    fun bind(fruit: Fruit, clickListener:(Fruit) -> Unit) {
        view.name_text_view.text = fruit.name
        view.setOnClickListener {
            clickListener(fruit)
        }
    }

}
```<file_sep>/app/src/main/java/com/anushka/recyclerviewdemo1/MainActivity.kt
package com.anushka.recyclerviewdemo1

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val fruitsList = listOf(Fruit("Mango","Tom"), Fruit("Apple","Joe"),Fruit("Banana","Mark") , Fruit("Guava","Mike"),Fruit("Lemon","Mike"),Fruit("Pear","Frank"),Fruit("Orange","Joe"))
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        my_recycler_view.setBackgroundColor(Color.YELLOW)
        my_recycler_view.layoutManager = LinearLayoutManager(this)

        //4. send function argument which is defined on this activity to recyclerView
        my_recycler_view.adapter = MyRecyclerViewAdapter(fruitsList, {selectedFruitItem: Fruit -> listItemClicked(selectedFruitItem)})
    }

    //3. define function which takes `fruit` from adapter
    private fun listItemClicked(fruit: Fruit) {
        Toast.makeText(this@MainActivity, "Supplier name is ${fruit.supplier}", Toast.LENGTH_LONG).show()
    }

}
<file_sep>/settings.gradle
include ':app'
rootProject.name='RecyclerViewDemo1'
<file_sep>/app/src/main/java/com/anushka/recyclerviewdemo1/Fruit.kt
package com.anushka.recyclerviewdemo1

data class Fruit(val name:String,val supplier:String)

languages: Markdown Gradle Kotlin


text:
<file_sep>$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['Message'];

if(empty($name) || empty($email) || empty($message))
{
    echo "PLEASE FILL ALL THE FIELDS"
}
else
{
    mail("<EMAIL>", UNIVERSITY MESSAGE,$message ,"From :$name <$email>");
    echo"<script type='text/javascript'>alert('your message sent successfully')
    window.history.log(-1);
</script>
}

branch_name: refs/heads/main

repo_language: PHP


text:
<repo_name>MartinHarkins/code-challenge<file_sep>/main.py
import simplejson as json
import urllib
from bs4 import BeautifulSoup
import re
import os
from os import path
import nltk

#creates the api and gets the json file
def page_handler(key, word, language):
	pagehandler = urllib.urlopen("http://thesaurus.altervista.org/thesaurus/v1?key=" + key + "&word=" + word + "&language=" + language + "&output=json")
	return pagehandler

#parses the json file
def get_syn(api_response, wordlist):
	while 1:

        	data = json.load(api_response)

	        if data.get('error'):
        	        print data['error']
            		break
        	for entry in data['response']:
               	 	synonyms = entry['list']['synonyms'].split('|')
                	for item in synonyms:
                        	wordlist.append(item)
        	break

#puts all html and txt files in the directory into a list
def file_enum(mypath):
	files = [f for f in os.listdir(mypath) if path.isfile(f) and (f.endswith('html') or f.endswith('txt'))]
	print files
	return files

#creates a list of chapter titles
def textOf(soup):
	return ' '.join(soup.find_all(text=True))

#gets all the chapter titles
def get_chapter_list(soup, file_name):
	chapter_list = [textOf(n) for n in soup.find_all('h3', {"align" : "CENTER"})]
	return chapter_list

#creates context for the word
def sentence_snapshot(word, word_tokens, sentence, title, file_name):
                if word in word_tokens:
                        word_loc = word_tokens.index(word)
                        word_tokens.remove(word)
                        newword = '*'+word+'*'
                        word_tokens.insert(word_loc, newword)

                        token_length = len(word_tokens)
			if len(' '.join(sentence)) < 140:
				print ' '.join(word_tokens)
                                print word + " found in " + title + " File name: " + file_name + '\n'

                        if len(' '.join(sentence)) > 140:
                                num1 = word_loc - 5
                                num2 = word_loc + 5

                                if word_loc <= 5:
                                        num1 = 0

                                if token_length - word_loc <= 2:
                                        num2 = token_length

                                while len(' '.join(word_tokens[num1:num2])) > 140:
                                        num1 = num1 + 1
                                        num2 = num2 + 1

                                if num1 > 0 and num2 < token_length:
                                        print '...' + ' '.join(word_tokens[num1:num2]) + '...'
                                elif num1 == 0:
                                        print ' '.join(word_tokens[num1:num2]) + '...'
                                elif num2 == token_length or (num2 - word_loc) >= 2:
                                        print '...' + ' '.join(word_tokens[num1:num2])
        	                else:
	                                print ' '.join(word_tokens)

                                print word + " found in " + title + " File name: " + file_name + '\n'

def find_word(wordlist, word_tokens, sentence, file_name, title):
	for word in wordlist:
		sentence_snapshot(word, word_tokens, sentence, title, file_name)

def sentence_tokenizing(wordlist, sentences, file_name, title):
	for sentence in sentences:
		word_tokens = nltk.word_tokenize(sentence)
		find_word(wordlist, word_tokens, sentence, file_name, title)

def find_in_text(mypath, wordlist):
	for file_name in file_enum(mypath):
	        soup = BeautifulSoup(open(file_name))
	        title = soup.title.string

		raw = soup.get_text()

		chapter_list = get_chapter_list(soup, file_name)
	        sentences = nltk.sent_tokenize(raw)
		sentence_tokenizing(wordlist, sentences, file_name, title)

def main():
	mypath = "/home/teitoku/code-challenge/"

	key = "<KEY>TSN7"

	word = raw_input('What word would you like to search?')

	language = 'en_US'

	wordlist = [word]

	get_syn(page_handler(key, word, language), wordlist)
	find_in_text(mypath, wordlist)

if __name__ == "__main__":
	main()

repo_language: Python

repo_name: MartinHarkins/code-challenge