Search in sources :

Example 1 with OnexException

use of com.nb6868.onex.common.exception.OnexException in project onex-boot by zhangchaoxu.

the class ExcelUtils method downloadExcelFromWorkbook.

// [导出相关]
/**
 * 通过workbook 下载excel
 */
public static void downloadExcelFromWorkbook(HttpServletResponse response, String fileName, Workbook workbook) {
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setContentType(CONTENT_TYPE_XLS);
    try {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, StrUtil.format(FILENAME_XLS_FMT, URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())));
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
        throw new OnexException(ErrorCode.EXCEL_EXPORT_ERROR, e);
    }
}
Also used : OnexException(com.nb6868.onex.common.exception.OnexException) ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException)

Example 2 with OnexException

use of com.nb6868.onex.common.exception.OnexException in project onex-boot by zhangchaoxu.

the class ScheduleUtils method updateScheduleJob.

/**
 * 更新定时任务
 */
public static void updateScheduleJob(Scheduler scheduler, TaskInfo taskInfo) {
    try {
        // 启动调度器
        scheduler.start();
        TriggerKey triggerKey = getTriggerKey(taskInfo.getId());
        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(taskInfo.getCron()).withMisfireHandlingInstructionDoNothing();
        CronTrigger trigger = getCronTrigger(scheduler, taskInfo.getId());
        // 按新的cronExpression表达式重新构建trigger
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        // 参数
        trigger.getJobDataMap().put(SchedConst.JOB_PARAM_KEY, taskInfo);
        scheduler.rescheduleJob(triggerKey, trigger);
        // 暂停任务
        if (taskInfo.getState() == SchedConst.TaskState.PAUSE.getValue()) {
            pauseJob(scheduler, taskInfo.getId());
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
        throw new OnexException(ErrorCode.JOB_ERROR, e);
    }
}
Also used : OnexException(com.nb6868.onex.common.exception.OnexException)

Example 3 with OnexException

use of com.nb6868.onex.common.exception.OnexException in project onex-boot by zhangchaoxu.

the class ScheduleUtils method createScheduleJob.

/**
 * 创建定时任务
 */
public static void createScheduleJob(Class<? extends Job> jobClass, Scheduler scheduler, TaskInfo taskInfo) {
    try {
        // 启动调度器
        scheduler.start();
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(taskInfo.getId())).build();
        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(taskInfo.getCron()).withMisfireHandlingInstructionDoNothing();
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(taskInfo.getId())).withSchedule(scheduleBuilder).build();
        // 放入参数,运行时的方法可以获取
        jobDetail.getJobDataMap().put(SchedConst.JOB_PARAM_KEY, taskInfo);
        scheduler.scheduleJob(jobDetail, trigger);
        // 暂停任务
        if (taskInfo.getState() == SchedConst.TaskState.PAUSE.getValue()) {
            pauseJob(scheduler, taskInfo.getId());
        }
    } catch (SchedulerException e) {
        throw new OnexException(ErrorCode.JOB_ERROR, e);
    }
}
Also used : OnexException(com.nb6868.onex.common.exception.OnexException)

Example 4 with OnexException

use of com.nb6868.onex.common.exception.OnexException in project onex-boot by zhangchaoxu.

the class GenUtils method generatorCode.

/**
 * 生成代码
 *
 * @param table              生成的表
 * @param columns            生成的字段
 * @param codeGenerateConfig 生成配置
 * @param zip                输出的压缩包
 */
public static void generatorCode(Map<String, Object> table, List<Entity> columns, CodeGenerateConfig codeGenerateConfig, ZipOutputStream zip) {
    // 配置信息
    Configuration config = getConfig();
    boolean hasBigDecimal = false;
    // 表信息
    TableEntity tableEntity = new TableEntity();
    tableEntity.setTableName(MapUtil.getStr(table, "table_name"));
    tableEntity.setComments(MapUtil.getStr(table, "table_comment"));
    // 表名转换成Java类名
    String className = tableToJava(tableEntity.getTableName(), codeGenerateConfig.getTablePrefix());
    tableEntity.setClassName(className);
    tableEntity.setClassname(StringUtils.uncapitalize(className));
    // 列信息
    List<ColumnEntity> columnsList = new ArrayList<>();
    for (Entity column : columns) {
        ColumnEntity columnEntity = new ColumnEntity();
        columnEntity.setColumnName(MapUtil.getStr(column, "column_name"));
        columnEntity.setDataType(MapUtil.getStr(column, "data_type"));
        columnEntity.setComments(MapUtil.getStr(column, "column_comment"));
        columnEntity.setExtra(MapUtil.getStr(column, "extra"));
        // 列名转换成Java属性名
        String attrName = columnToJava(columnEntity.getColumnName());
        columnEntity.setAttrName(attrName);
        columnEntity.setAttrname(StringUtils.uncapitalize(attrName));
        // 列的数据类型,转换成Java类型
        String attrType = config.getString(columnEntity.getDataType(), "unknowType");
        columnEntity.setAttrType(attrType);
        if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
            hasBigDecimal = true;
        }
        // 是否主键
        if ("PRI".equalsIgnoreCase(MapUtil.getStr(column, "column_key")) && tableEntity.getPk() == null) {
            tableEntity.setPk(columnEntity);
        }
        columnsList.add(columnEntity);
    }
    tableEntity.setColumns(columnsList);
    // 没主键,则第一个字段为主键
    if (tableEntity.getPk() == null) {
        tableEntity.setPk(tableEntity.getColumns().get(0));
    }
    // 设置velocity资源加载器
    Properties prop = new Properties();
    prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(prop);
    // 封装模板数据
    Map<String, Object> map = new HashMap<>();
    map.put("tableName", tableEntity.getTableName());
    map.put("comments", tableEntity.getComments());
    map.put("pk", tableEntity.getPk());
    map.put("className", tableEntity.getClassName());
    map.put("classname", tableEntity.getClassname());
    map.put("pathName", tableEntity.getClassname());
    if (StringUtils.isNotBlank(codeGenerateConfig.getTablePrefix())) {
        map.put("pathNameDash", tableEntity.getTableName().replaceFirst(codeGenerateConfig.getTablePrefix() + "_", "").replace("_", "-"));
    } else {
        map.put("pathNameDash", tableEntity.getTableName().replace("_", "-"));
    }
    map.put("columns", tableEntity.getColumns());
    map.put("hasBigDecimal", hasBigDecimal);
    map.put("version", codeGenerateConfig.getVersion());
    map.put("package", codeGenerateConfig.getPackageName());
    map.put("moduleName", codeGenerateConfig.getModuleName());
    map.put("author", codeGenerateConfig.getAuthorName());
    map.put("email", codeGenerateConfig.getAuthorEmail());
    map.put("datetime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    map.put("date", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    for (int i = 0; i <= 10; i++) {
        map.put("id" + i, IdUtil.getSnowflake(1, 1).nextId());
    }
    VelocityContext context = new VelocityContext(map);
    // 获取模板列表
    List<String> templates = getTemplates();
    for (String template : templates) {
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, "UTF-8");
        tpl.merge(context, sw);
        try {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), codeGenerateConfig.getPackageName(), codeGenerateConfig.getModuleName(), (String) map.get("pathNameDash"))));
            IoUtil.write(zip, false, sw.toString().getBytes());
            sw.close();
            zip.closeEntry();
        } catch (IOException e) {
            throw new OnexException("渲染模板失败,表名:" + tableEntity.getTableName(), e);
        }
    }
}
Also used : ColumnEntity(com.nb6868.onex.coder.entity.ColumnEntity) Entity(cn.hutool.db.Entity) TableEntity(com.nb6868.onex.coder.entity.TableEntity) ColumnEntity(com.nb6868.onex.coder.entity.ColumnEntity) Configuration(org.apache.commons.configuration.Configuration) PropertiesConfiguration(org.apache.commons.configuration.PropertiesConfiguration) VelocityContext(org.apache.velocity.VelocityContext) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) Template(org.apache.velocity.Template) StringWriter(java.io.StringWriter) TableEntity(com.nb6868.onex.coder.entity.TableEntity)

Example 5 with OnexException

use of com.nb6868.onex.common.exception.OnexException in project onex-boot by zhangchaoxu.

the class AliyunOssService method getSts.

@Override
public Dict getSts() {
    try {
        // 添加endpoint(直接使用STS endpoint,无需添加region ID)
        DefaultProfile.addEndpoint("", "Sts", "sts." + config.getRegion() + ".aliyuncs.com");
        // 构造default profile(参数留空,无需添加region ID)
        IClientProfile profile = DefaultProfile.getProfile("", config.getAccessKeyId(), config.getAccessKeySecret());
        // 用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysProtocol(ProtocolType.HTTPS);
        request.setRoleArn(config.getRoleArn());
        request.setRoleSessionName(config.getRoleSessionName());
        // 若policy为空,则用户将获得该角色下所有权限
        request.setPolicy(null);
        // 设置凭证有效时间
        request.setDurationSeconds(config.getStsDurationSeconds());
        AssumeRoleResponse response = client.getAcsResponse(request);
        return Dict.create().set("accessKeyId", response.getCredentials().getAccessKeyId()).set("accessKeySecret", response.getCredentials().getAccessKeySecret()).set("securityToken", response.getCredentials().getSecurityToken()).set("expiration", response.getCredentials().getExpiration()).set("region", "oss-" + config.getRegion()).set("prefix", config.getPrefix()).set("domain", config.getDomain()).set("secure", config.getSecure()).set("bucketName", config.getBucketName());
    } catch (ClientException e) {
        throw new OnexException(ErrorCode.OSS_CONFIG_ERROR, e);
    }
}
Also used : OnexException(com.nb6868.onex.common.exception.OnexException) AssumeRoleRequest(com.aliyuncs.auth.sts.AssumeRoleRequest) DefaultAcsClient(com.aliyuncs.DefaultAcsClient) AssumeRoleResponse(com.aliyuncs.auth.sts.AssumeRoleResponse) ClientException(com.aliyuncs.exceptions.ClientException) IClientProfile(com.aliyuncs.profile.IClientProfile)

Aggregations

OnexException (com.nb6868.onex.common.exception.OnexException)13 OSS (com.aliyun.oss.OSS)3 OSSClientBuilder (com.aliyun.oss.OSSClientBuilder)3 ClientException (com.aliyuncs.exceptions.ClientException)3 OSSException (com.aliyun.oss.OSSException)2 ObsClient (com.obs.services.ObsClient)2 ObsException (com.obs.services.exception.ObsException)2 IOException (java.io.IOException)2 Dict (cn.hutool.core.lang.Dict)1 Entity (cn.hutool.db.Entity)1 JWT (cn.hutool.jwt.JWT)1 OSSObject (com.aliyun.oss.model.OSSObject)1 DefaultAcsClient (com.aliyuncs.DefaultAcsClient)1 AssumeRoleRequest (com.aliyuncs.auth.sts.AssumeRoleRequest)1 AssumeRoleResponse (com.aliyuncs.auth.sts.AssumeRoleResponse)1 IClientProfile (com.aliyuncs.profile.IClientProfile)1 ColumnEntity (com.nb6868.onex.coder.entity.ColumnEntity)1 TableEntity (com.nb6868.onex.coder.entity.TableEntity)1 LogOperation (com.nb6868.onex.common.annotation.LogOperation)1 AuthProps (com.nb6868.onex.common.auth.AuthProps)1