file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
1,078
package org.pdown.gui.extension.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.concurrent.CountDownLatch; import java.util.function.Function; import java.util.stream.Collectors; import javax.script.Invocable; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import org.pdown.core.util.FileUtil; import org.pdown.gui.DownApplication; import org.pdown.gui.content.PDownConfigContent; import org.pdown.gui.extension.ExtensionContent; import org.pdown.gui.extension.ExtensionInfo; import org.pdown.gui.extension.HookScript; import org.pdown.gui.extension.HookScript.Event; import org.pdown.gui.extension.Meta; import org.pdown.gui.extension.jsruntime.JavascriptEngine; import org.pdown.gui.http.controller.NativeController; import org.pdown.gui.http.util.HttpHandlerUtil; import org.pdown.gui.util.AppUtil; import org.pdown.gui.util.ConfigUtil; import org.pdown.rest.form.TaskForm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; public class ExtensionUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ExtensionUtil.class); /** * 安装扩展 */ public static void install(String server, String path, String files) throws Exception { download(server, path, path, files); } /** * 更新扩展,先把扩展文件下载到临时目录中 */ public static void update(String server, String path, String files) throws Exception { String extDir = ExtensionContent.EXT_DIR + File.separator + path; String tmpPath = path + "_tmp"; String extTmpPath = ExtensionContent.EXT_DIR + File.separator + tmpPath; String extBakPath = ExtensionContent.EXT_DIR + File.separator + path + "_bak"; try { download(server, path, tmpPath, files); //备份老版本扩展 copy(new File(extDir), new File(extBakPath)); //备份扩展配置 String configPath = extDir + File.separator + Meta.CONFIG_FILE; if (FileUtil.exists(configPath)) { Path bakConfigPath = Paths.get(extTmpPath + File.separator + Meta.CONFIG_FILE); FileUtil.createFileSmart(bakConfigPath.toFile().getAbsolutePath()); Files.copy(Paths.get(configPath), bakConfigPath, StandardCopyOption.REPLACE_EXISTING); } String configBakPath = extDir + File.separator + Meta.CONFIG_FILE + ".bak"; if (FileUtil.exists(configBakPath)) { Files.copy(Paths.get(configBakPath), Paths.get(extTmpPath + File.separator + Meta.CONFIG_FILE + ".bak"), StandardCopyOption.REPLACE_EXISTING); } try { //删除原始扩展目录并将临时目录重命名 FileUtil.deleteIfExists(extDir); } catch (Exception e) { //删除失败还原扩展 copy(new File(extBakPath), new File(extDir)); throw new IOException(e); } finally { FileUtil.deleteIfExists(extBakPath); } new File(extTmpPath).renameTo(new File(extDir)); } finally { //删除临时目录 FileUtil.deleteIfExists(extTmpPath); } } /** * 根据扩展的路径和文件列表,下载对应的文件 */ private static void download(String server, String path, String writePath, String files) throws Exception { String extDir = ExtensionContent.EXT_DIR + File.separator + writePath; if (!FileUtil.exists(extDir)) { Files.createDirectories(Paths.get(extDir)); } for (String fileName : files.split(",")) { AppUtil.download(server + path + fileName, extDir + File.separator + fileName); } } public static void copy(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { copyDirectory(sourceLocation, targetLocation); } else { copyFile(sourceLocation, targetLocation); } } private static void copyDirectory(File source, File target) throws IOException { if (!target.exists()) { target.mkdir(); } for (String f : source.list()) { copy(new File(source, f), new File(target, f)); } } private static void copyFile(File source, File target) throws IOException { if (target.exists()) { return; } try ( InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target) ) { byte[] buf = new byte[1024]; int length; while ((length = in.read(buf)) > 0) { out.write(buf, 0, length); } } } public static String readRuntimeTemplate(ExtensionInfo extensionInfo) { String template = ""; try ( BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("extension/runtime.js"))) ) { template = reader.lines().collect(Collectors.joining("\n")); template = template.replace("${version}", ConfigUtil.getString("version")); template = template.replace("${apiPort}", DownApplication.INSTANCE.API_PORT + ""); template = template.replace("${frontPort}", DownApplication.INSTANCE.FRONT_PORT + ""); template = template.replace("${uiMode}", PDownConfigContent.getInstance().get().getUiMode() + ""); String settingJson = "{}"; if (extensionInfo.getMeta().getSettings() != null) { ObjectMapper objectMapper = new ObjectMapper(); try { settingJson = objectMapper.writeValueAsString(extensionInfo.getMeta().getSettings()); } catch (JsonProcessingException e) { } } template = template.replace("${settings}", settingJson); } catch (IOException e) { } return template; } /** * 创建扩展环境的js引擎,可以在引擎中访问pdown对象 */ public static ScriptEngine buildExtensionRuntimeEngine(ExtensionInfo extensionInfo) throws ScriptException, NoSuchMethodException, FileNotFoundException { //初始化js引擎 ScriptEngine engine = JavascriptEngine.buildEngine(); //加载运行时脚本 Object runtime = engine.eval(ExtensionUtil.readRuntimeTemplate(extensionInfo)); engine.put("pdown", runtime); //加载扩展脚本 engine.eval(new FileReader(Paths.get(extensionInfo.getMeta().getFullPath(), extensionInfo.getHookScript().getScript()).toFile())); return engine; } /** * 运行一个js方法 */ public static Object invoke(ExtensionInfo extensionInfo, Event event, Object param, boolean async) throws NoSuchMethodException, ScriptException, FileNotFoundException, InterruptedException { //初始化js引擎 ScriptEngine engine = ExtensionUtil.buildExtensionRuntimeEngine(extensionInfo); Invocable invocable = (Invocable) engine; //执行resolve方法 Object result = invocable.invokeFunction(StringUtils.isEmpty(event.getMethod()) ? event.getOn() : event.getMethod(), param); //结果为null或者异步调用直接返回 if (result == null || async) { return result; } final Object[] ret = {null}; //判断是不是返回Promise对象 ScriptContext ctx = new SimpleScriptContext(); ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE); boolean isPromise = (boolean) engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx); if (isPromise) { //如果是返回的Promise则等待执行完成 CountDownLatch countDownLatch = new CountDownLatch(1); invocable.invokeMethod(result, "then", (Function) o -> { try { ret[0] = o; } catch (Exception e) { LOGGER.error("An exception occurred while resolve()", e); } finally { countDownLatch.countDown(); } return null; }); invocable.invokeMethod(result, "catch", (Function) o -> { countDownLatch.countDown(); return null; }); //等待解析完成 countDownLatch.await(); } else { ret[0] = result; } return ret[0]; } public static void main(String[] args) { String url = "https://d.pcs.baidu.com/file/ab83d33b3f250a6ff472b8ffa17c3e5f?fid=336129479-250528-831181624029689&dstime=1541581115&rt=sh&sign=FDtAERVY-DCb740ccc5511e5e8fedcff06b081203-aILjqoJW3OEzB4%2Bu7Wnxz63PUho%3D&expires=8h&chkv=1&chkbd=0&chkpc=et&dp-logid=7206180716394015240&dp-callid=0&shareid=3786359813&r=663179228"; String[] urlArray = url.split("\\?"); StringBuilder params = new StringBuilder(urlArray[1]); String path = urlArray[0].substring(urlArray[0].lastIndexOf("/") + 1); params.append("&path=" + path) .append("&check_blue=1") .append("&clienttype=8") .append("&devuid=BDIMXV2-O_9A2DB23216984690875184DCA864434E-C_0-D_Z4Y7YWL9-M_408D5C4224FB-V_D8F90423") .append("&dtype=1") .append("&eck=1") .append("&ehps=1") .append("&err_ver=1") .append("&es=1") .append("&esl=1") .append("&method=locatedownload") .append("&ver=4") .append("&version=2.1.13.11") .append("&version_app=6.4.0.6"); System.out.println(params.toString()); } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/extension/util/ExtensionUtil.java
1,079
/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.utils; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.template.*; import lombok.extern.slf4j.Slf4j; import me.zhengjie.domain.GenConfig; import me.zhengjie.domain.ColumnInfo; import org.springframework.util.ObjectUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.time.LocalDate; import java.util.*; import static me.zhengjie.utils.FileUtil.SYS_TEM_DIR; /** * 代码生成 * * @author Zheng Jie * @date 2019-01-02 */ @Slf4j @SuppressWarnings({"unchecked", "all"}) public class GenUtil { private static final String TIMESTAMP = "Timestamp"; private static final String BIGDECIMAL = "BigDecimal"; public static final String PK = "PRI"; public static final String EXTRA = "auto_increment"; /** * 获取后端代码模板名称 * * @return List */ private static List<String> getAdminTemplateNames() { List<String> templateNames = new ArrayList<>(); templateNames.add("Entity"); templateNames.add("Dto"); templateNames.add("Mapper"); templateNames.add("Controller"); templateNames.add("QueryCriteria"); templateNames.add("Service"); templateNames.add("ServiceImpl"); templateNames.add("Repository"); return templateNames; } /** * 获取前端代码模板名称 * * @return List */ private static List<String> getFrontTemplateNames() { List<String> templateNames = new ArrayList<>(); templateNames.add("index"); templateNames.add("api"); return templateNames; } public static List<Map<String, Object>> preview(List<ColumnInfo> columns, GenConfig genConfig) { Map<String, Object> genMap = getGenMap(columns, genConfig); List<Map<String, Object>> genList = new ArrayList<>(); // 获取后端模版 List<String> templates = getAdminTemplateNames(); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); for (String templateName : templates) { Map<String, Object> map = new HashMap<>(1); Template template = engine.getTemplate("admin/" + templateName + ".ftl"); map.put("content", template.render(genMap)); map.put("name", templateName); genList.add(map); } // 获取前端模版 templates = getFrontTemplateNames(); for (String templateName : templates) { Map<String, Object> map = new HashMap<>(1); Template template = engine.getTemplate("front/" + templateName + ".ftl"); map.put(templateName, template.render(genMap)); map.put("content", template.render(genMap)); map.put("name", templateName); genList.add(map); } return genList; } public static String download(List<ColumnInfo> columns, GenConfig genConfig) throws IOException { // 拼接的路径:/tmpeladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/eladmin-gen-temp/ // String tempPath =SYS_TEM_DIR + "eladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; String tempPath = SYS_TEM_DIR + "eladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; Map<String, Object> genMap = getGenMap(columns, genConfig); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); // 生成后端代码 List<String> templates = getAdminTemplateNames(); for (String templateName : templates) { Template template = engine.getTemplate("admin/" + templateName + ".ftl"); String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); assert filePath != null; File file = new File(filePath); // 如果非覆盖生成 if (!genConfig.getCover() && FileUtil.exist(file)) { continue; } // 生成代码 genFile(file, template, genMap); } // 生成前端代码 templates = getFrontTemplateNames(); for (String templateName : templates) { Template template = engine.getTemplate("front/" + templateName + ".ftl"); String path = tempPath + "eladmin-web" + File.separator; String apiPath = path + "src" + File.separator + "api" + File.separator; String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); assert filePath != null; File file = new File(filePath); // 如果非覆盖生成 if (!genConfig.getCover() && FileUtil.exist(file)) { continue; } // 生成代码 genFile(file, template, genMap); } return tempPath; } public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig) throws IOException { Map<String, Object> genMap = getGenMap(columnInfos, genConfig); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); // 生成后端代码 List<String> templates = getAdminTemplateNames(); for (String templateName : templates) { Template template = engine.getTemplate("admin/" + templateName + ".ftl"); String rootPath = System.getProperty("user.dir"); String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), rootPath); assert filePath != null; File file = new File(filePath); // 如果非覆盖生成 if (!genConfig.getCover() && FileUtil.exist(file)) { continue; } // 生成代码 genFile(file, template, genMap); } // 生成前端代码 templates = getFrontTemplateNames(); for (String templateName : templates) { Template template = engine.getTemplate("front/" + templateName + ".ftl"); String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); assert filePath != null; File file = new File(filePath); // 如果非覆盖生成 if (!genConfig.getCover() && FileUtil.exist(file)) { continue; } // 生成代码 genFile(file, template, genMap); } } // 获取模版数据 private static Map<String, Object> getGenMap(List<ColumnInfo> columnInfos, GenConfig genConfig) { // 存储模版字段数据 Map<String, Object> genMap = new HashMap<>(16); // 接口别名 genMap.put("apiAlias", genConfig.getApiAlias()); // 包名称 genMap.put("package", genConfig.getPack()); // 模块名称 genMap.put("moduleName", genConfig.getModuleName()); // 作者 genMap.put("author", genConfig.getAuthor()); // 创建日期 genMap.put("date", LocalDate.now().toString()); // 表名 genMap.put("tableName", genConfig.getTableName()); // 大写开头的类名 String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); // 小写开头的类名 String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); // 判断是否去除表前缀 if (StringUtils.isNotEmpty(genConfig.getPrefix())) { className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); changeClassName = StringUtils.uncapitalize(changeClassName); } // 保存类名 genMap.put("className", className); // 保存小写开头的类名 genMap.put("changeClassName", changeClassName); // 存在 Timestamp 字段 genMap.put("hasTimestamp", false); // 查询类中存在 Timestamp 字段 genMap.put("queryHasTimestamp", false); // 存在 BigDecimal 字段 genMap.put("hasBigDecimal", false); // 查询类中存在 BigDecimal 字段 genMap.put("queryHasBigDecimal", false); // 是否需要创建查询 genMap.put("hasQuery", false); // 自增主键 genMap.put("auto", false); // 存在字典 genMap.put("hasDict", false); // 存在日期注解 genMap.put("hasDateAnnotation", false); // 保存字段信息 List<Map<String, Object>> columns = new ArrayList<>(); // 保存查询字段的信息 List<Map<String, Object>> queryColumns = new ArrayList<>(); // 存储字典信息 List<String> dicts = new ArrayList<>(); // 存储 between 信息 List<Map<String, Object>> betweens = new ArrayList<>(); // 存储不为空的字段信息 List<Map<String, Object>> isNotNullColumns = new ArrayList<>(); for (ColumnInfo column : columnInfos) { Map<String, Object> listMap = new HashMap<>(16); // 字段描述 listMap.put("remark", column.getRemark()); // 字段类型 listMap.put("columnKey", column.getKeyType()); // 主键类型 String colType = ColUtil.cloToJava(column.getColumnType()); // 小写开头的字段名 String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); // 大写开头的字段名 String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); if (PK.equals(column.getKeyType())) { // 存储主键类型 genMap.put("pkColumnType", colType); // 存储小写开头的字段名 genMap.put("pkChangeColName", changeColumnName); // 存储大写开头的字段名 genMap.put("pkCapitalColName", capitalColumnName); } // 是否存在 Timestamp 类型的字段 if (TIMESTAMP.equals(colType)) { genMap.put("hasTimestamp", true); } // 是否存在 BigDecimal 类型的字段 if (BIGDECIMAL.equals(colType)) { genMap.put("hasBigDecimal", true); } // 主键是否自增 if (EXTRA.equals(column.getExtra())) { genMap.put("auto", true); } // 主键存在字典 if (StringUtils.isNotBlank(column.getDictName())) { genMap.put("hasDict", true); if(!dicts.contains(column.getDictName())) dicts.add(column.getDictName()); } // 存储字段类型 listMap.put("columnType", colType); // 存储字原始段名称 listMap.put("columnName", column.getColumnName()); // 不为空 listMap.put("istNotNull", column.getNotNull()); // 字段列表显示 listMap.put("columnShow", column.getListShow()); // 表单显示 listMap.put("formShow", column.getFormShow()); // 表单组件类型 listMap.put("formType", StringUtils.isNotBlank(column.getFormType()) ? column.getFormType() : "Input"); // 小写开头的字段名称 listMap.put("changeColumnName", changeColumnName); //大写开头的字段名称 listMap.put("capitalColumnName", capitalColumnName); // 字典名称 listMap.put("dictName", column.getDictName()); // 日期注解 listMap.put("dateAnnotation", column.getDateAnnotation()); if (StringUtils.isNotBlank(column.getDateAnnotation())) { genMap.put("hasDateAnnotation", true); } // 添加非空字段信息 if (column.getNotNull()) { isNotNullColumns.add(listMap); } // 判断是否有查询,如有则把查询的字段set进columnQuery if (!StringUtils.isBlank(column.getQueryType())) { // 查询类型 listMap.put("queryType", column.getQueryType()); // 是否存在查询 genMap.put("hasQuery", true); if (TIMESTAMP.equals(colType)) { // 查询中存储 Timestamp 类型 genMap.put("queryHasTimestamp", true); } if (BIGDECIMAL.equals(colType)) { // 查询中存储 BigDecimal 类型 genMap.put("queryHasBigDecimal", true); } if ("between".equalsIgnoreCase(column.getQueryType())) { betweens.add(listMap); } else { // 添加到查询列表中 queryColumns.add(listMap); } } // 添加到字段列表中 columns.add(listMap); } // 保存字段列表 genMap.put("columns", columns); // 保存查询列表 genMap.put("queryColumns", queryColumns); // 保存字段列表 genMap.put("dicts", dicts); // 保存查询列表 genMap.put("betweens", betweens); // 保存非空字段信息 genMap.put("isNotNullColumns", isNotNullColumns); return genMap; } /** * 定义后端文件路径以及名称 */ private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) { String projectPath = rootPath + File.separator + genConfig.getModuleName(); String packagePath = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; if (!ObjectUtils.isEmpty(genConfig.getPack())) { packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; } if ("Entity".equals(templateName)) { return packagePath + "domain" + File.separator + className + ".java"; } if ("Controller".equals(templateName)) { return packagePath + "rest" + File.separator + className + "Controller.java"; } if ("Service".equals(templateName)) { return packagePath + "service" + File.separator + className + "Service.java"; } if ("ServiceImpl".equals(templateName)) { return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; } if ("Dto".equals(templateName)) { return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; } if ("QueryCriteria".equals(templateName)) { return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java"; } if ("Mapper".equals(templateName)) { return packagePath + "service" + File.separator + "mapstruct" + File.separator + className + "Mapper.java"; } if ("Repository".equals(templateName)) { return packagePath + "repository" + File.separator + className + "Repository.java"; } return null; } /** * 定义前端文件路径以及名称 */ private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { if ("api".equals(templateName)) { return apiPath + File.separator + apiName + ".js"; } if ("index".equals(templateName)) { return path + File.separator + "index.vue"; } return null; } private static void genFile(File file, Template template, Map<String, Object> map) throws IOException { // 生成目标文件 Writer writer = null; try { FileUtil.touch(file); writer = new FileWriter(file); template.render(map, writer); } catch (TemplateException | IOException e) { throw new RuntimeException(e); } finally { assert writer != null; writer.close(); } } }
elunez/eladmin
eladmin-generator/src/main/java/me/zhengjie/utils/GenUtil.java
1,083
package com.crossoverjie.actual; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Function: 两个线程交替执行打印 1~100 * * lock 版 * * @author crossoverJie * Date: 11/02/2018 10:04 * @since JDK 1.8 */ public class TwoThread { private int start = 1; /** * 对 flag 的写入虽然加锁保证了线程安全,但读取的时候由于 不是 volatile 所以可能会读取到旧值 * */ private volatile boolean flag = false; /** * 重入锁 */ private final static Lock LOCK = new ReentrantLock(); public static void main(String[] args) { TwoThread twoThread = new TwoThread(); Thread t1 = new Thread(new OuNum(twoThread)); t1.setName("t1"); Thread t2 = new Thread(new JiNum(twoThread)); t2.setName("t2"); t1.start(); t2.start(); } /** * 偶数线程 */ public static class OuNum implements Runnable { private TwoThread number; public OuNum(TwoThread number) { this.number = number; } @Override public void run() { while (number.start <= 1000) { if (number.flag) { try { LOCK.lock(); System.out.println(Thread.currentThread().getName() + "+-+" + number.start); number.start++; number.flag = false; } finally { LOCK.unlock(); } } } } } /** * 奇数线程 */ public static class JiNum implements Runnable { private TwoThread number; public JiNum(TwoThread number) { this.number = number; } @Override public void run() { while (number.start <= 1000) { if (!number.flag) { try { LOCK.lock(); System.out.println(Thread.currentThread().getName() + "+-+" + number.start); number.start++; number.flag = true; } finally { LOCK.unlock(); } } } } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/TwoThread.java
1,084
package cn.hutool.core.util; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import java.util.Set; /** * Boolean类型相关工具类 * * @author looly * @since 4.1.16 */ public class BooleanUtil { /** 表示为真的字符串 */ private static final Set<String> TRUE_SET = CollUtil.newHashSet("true", "yes", "y", "t", "ok", "1", "on", "是", "对", "真", "對", "√"); /** 表示为假的字符串 */ private static final Set<String> FALSE_SET = CollUtil.newHashSet("false", "no", "n", "f", "0", "off", "否", "错", "假", "錯", "×"); /** * 取相反值 * * @param bool Boolean值 * @return 相反的Boolean值 */ public static Boolean negate(Boolean bool) { if (bool == null) { return null; } return bool ? Boolean.FALSE : Boolean.TRUE; } /** * 检查 {@code Boolean} 值是否为 {@code true} * * <pre> * BooleanUtil.isTrue(Boolean.TRUE) = true * BooleanUtil.isTrue(Boolean.FALSE) = false * BooleanUtil.isTrue(null) = false * </pre> * * @param bool 被检查的Boolean值 * @return 当值为true且非null时返回{@code true} */ public static boolean isTrue(Boolean bool) { return Boolean.TRUE.equals(bool); } /** * 检查 {@code Boolean} 值是否为 {@code false} * * <pre> * BooleanUtil.isFalse(Boolean.TRUE) = false * BooleanUtil.isFalse(Boolean.FALSE) = true * BooleanUtil.isFalse(null) = false * </pre> * * @param bool 被检查的Boolean值 * @return 当值为false且非null时返回{@code true} */ public static boolean isFalse(Boolean bool) { return Boolean.FALSE.equals(bool); } /** * 取相反值 * * @param bool Boolean值 * @return 相反的Boolean值 */ public static boolean negate(boolean bool) { return !bool; } /** * 转换字符串为boolean值 * * @param valueStr 字符串 * @return boolean值 */ public static boolean toBoolean(String valueStr) { if (StrUtil.isNotBlank(valueStr)) { valueStr = valueStr.trim().toLowerCase(); return TRUE_SET.contains(valueStr); } return false; } /** * 转换字符串为boolean值<br> * 如果为["true", "yes", "y", "t", "ok", "1", "on", "是", "对", "真", "對", "√"],返回{@code true}<br> * 如果为["false", "no", "n", "f", "0", "off", "否", "错", "假", "錯", "×"],返回{@code false}<br> * 其他情况返回{@code null} * * @param valueStr 字符串 * @return boolean值 * @since 5.8.1 */ public static Boolean toBooleanObject(String valueStr) { if (StrUtil.isNotBlank(valueStr)) { valueStr = valueStr.trim().toLowerCase(); if(TRUE_SET.contains(valueStr)){ return true; } else if(FALSE_SET.contains(valueStr)){ return false; } } return null; } /** * boolean值转为int * * @param value Boolean值 * @return int值 */ public static int toInt(boolean value) { return value ? 1 : 0; } /** * boolean值转为Integer * * @param value Boolean值 * @return Integer值 */ public static Integer toInteger(boolean value) { return toInt(value); } /** * boolean值转为char * * @param value Boolean值 * @return char值 */ public static char toChar(boolean value) { return (char) toInt(value); } /** * boolean值转为Character * * @param value Boolean值 * @return Character值 */ public static Character toCharacter(boolean value) { return toChar(value); } /** * boolean值转为byte * * @param value Boolean值 * @return byte值 */ public static byte toByte(boolean value) { return (byte) toInt(value); } /** * boolean值转为Byte * * @param value Boolean值 * @return Byte值 */ public static Byte toByteObj(boolean value) { return toByte(value); } /** * boolean值转为long * * @param value Boolean值 * @return long值 */ public static long toLong(boolean value) { return toInt(value); } /** * boolean值转为Long * * @param value Boolean值 * @return Long值 */ public static Long toLongObj(boolean value) { return toLong(value); } /** * boolean值转为short * * @param value Boolean值 * @return short值 */ public static short toShort(boolean value) { return (short) toInt(value); } /** * boolean值转为Short * * @param value Boolean值 * @return Short值 */ public static Short toShortObj(boolean value) { return toShort(value); } /** * boolean值转为float * * @param value Boolean值 * @return float值 */ public static float toFloat(boolean value) { return (float) toInt(value); } /** * boolean值转为Float * * @param value Boolean值 * @return float值 */ public static Float toFloatObj(boolean value) { return toFloat(value); } /** * boolean值转为double * * @param value Boolean值 * @return double值 */ public static double toDouble(boolean value) { return toInt(value); } /** * boolean值转为double * * @param value Boolean值 * @return double值 */ public static Double toDoubleObj(boolean value) { return toDouble(value); } /** * 将boolean转换为字符串 {@code 'true'} 或者 {@code 'false'}. * * <pre> * BooleanUtil.toStringTrueFalse(true) = "true" * BooleanUtil.toStringTrueFalse(false) = "false" * </pre> * * @param bool Boolean值 * @return {@code 'true'}, {@code 'false'} */ public static String toStringTrueFalse(boolean bool) { return toString(bool, "true", "false"); } /** * 将boolean转换为字符串 {@code 'on'} 或者 {@code 'off'}. * * <pre> * BooleanUtil.toStringOnOff(true) = "on" * BooleanUtil.toStringOnOff(false) = "off" * </pre> * * @param bool Boolean值 * @return {@code 'on'}, {@code 'off'} */ public static String toStringOnOff(boolean bool) { return toString(bool, "on", "off"); } /** * 将boolean转换为字符串 {@code 'yes'} 或者 {@code 'no'}. * * <pre> * BooleanUtil.toStringYesNo(true) = "yes" * BooleanUtil.toStringYesNo(false) = "no" * </pre> * * @param bool Boolean值 * @return {@code 'yes'}, {@code 'no'} */ public static String toStringYesNo(boolean bool) { return toString(bool, "yes", "no"); } /** * 将boolean转换为字符串 * * <pre> * BooleanUtil.toString(true, "true", "false") = "true" * BooleanUtil.toString(false, "true", "false") = "false" * </pre> * * @param bool Boolean值 * @param trueString 当值为 {@code true}时返回此字符串, 可能为 {@code null} * @param falseString 当值为 {@code false}时返回此字符串, 可能为 {@code null} * @return 结果值 */ public static String toString(boolean bool, String trueString, String falseString) { return bool ? trueString : falseString; } /** * 将boolean转换为字符串 * * <pre> * BooleanUtil.toString(true, "true", "false", null) = "true" * BooleanUtil.toString(false, "true", "false", null) = "false" * BooleanUtil.toString(null, "true", "false", null) = null * </pre> * * @param bool Boolean值 * @param trueString 当值为 {@code true}时返回此字符串, 可能为 {@code null} * @param falseString 当值为 {@code false}时返回此字符串, 可能为 {@code null} * @param nullString 当值为 {@code null}时返回此字符串, 可能为 {@code null} * @return 结果值 */ public static String toString(Boolean bool, String trueString, String falseString, String nullString) { if (bool == null) { return nullString; } return bool ? trueString : falseString; } /** * 对Boolean数组取与 * * <pre> * BooleanUtil.and(true, true) = true * BooleanUtil.and(false, false) = false * BooleanUtil.and(true, false) = false * BooleanUtil.and(true, true, false) = false * BooleanUtil.and(true, true, true) = true * </pre> * * @param array {@code Boolean}数组 * @return 取与为真返回{@code true} */ public static boolean and(boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final boolean element : array) { if (false == element) { return false; } } return true; } /** * 对Boolean数组取与 * * <pre> * BooleanUtil.and(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.and(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE * BooleanUtil.and(Boolean.TRUE, Boolean.FALSE) = Boolean.FALSE * BooleanUtil.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE * BooleanUtil.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE * </pre> * * @param array {@code Boolean}数组 * @return 取与为真返回{@code true} */ public static Boolean andOfWrap(Boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final Boolean b : array) { if(isFalse(b)){ return false; } } return true; } /** * 对Boolean数组取或 * * <pre> * BooleanUtil.or(true, true) = true * BooleanUtil.or(false, false) = false * BooleanUtil.or(true, false) = true * BooleanUtil.or(true, true, false) = true * BooleanUtil.or(true, true, true) = true * BooleanUtil.or(false, false, false) = false * </pre> * * @param array {@code Boolean}数组 * @return 取或为真返回{@code true} */ public static boolean or(boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final boolean element : array) { if (element) { return true; } } return false; } /** * 对Boolean数组取或 * * <pre> * BooleanUtil.or(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.or(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE * BooleanUtil.or(Boolean.TRUE, Boolean.FALSE) = Boolean.TRUE * BooleanUtil.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE * BooleanUtil.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE * </pre> * * @param array {@code Boolean}数组 * @return 取或为真返回{@code true} */ public static Boolean orOfWrap(Boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final Boolean b : array) { if(isTrue(b)){ return true; } } return false; } /** * 对Boolean数组取异或 * * <pre> * BooleanUtil.xor(true, true) = false * BooleanUtil.xor(false, false) = false * BooleanUtil.xor(true, false) = true * BooleanUtil.xor(true, true) = false * BooleanUtil.xor(false, false) = false * BooleanUtil.xor(true, false) = true * </pre> * * @param array {@code boolean}数组 * @return 如果异或计算为true返回 {@code true} */ public static boolean xor(boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty"); } boolean result = false; for (final boolean element : array) { result ^= element; } return result; } /** * 对Boolean数组取异或 * * <pre> * BooleanUtil.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) = Boolean.FALSE * BooleanUtil.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE * BooleanUtil.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) = Boolean.TRUE * </pre> * * @param array {@code Boolean} 数组 * @return 异或为真取{@code true} */ public static Boolean xorOfWrap(Boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } final boolean[] primitive = Convert.convert(boolean[].class, array); return xor(primitive); } /** * 给定类是否为Boolean或者boolean * * @param clazz 类 * @return 是否为Boolean或者boolean * @since 4.5.2 */ public static boolean isBoolean(Class<?> clazz) { return (clazz == Boolean.class || clazz == boolean.class); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/util/BooleanUtil.java
1,085
package io.mycat.server.util; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLShowColumnsStatement; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; import com.alibaba.druid.sql.parser.SQLStatementParser; import io.mycat.MycatServer; import io.mycat.config.model.SchemaConfig; import io.mycat.route.parser.druid.MycatSchemaStatVisitor; import io.mycat.route.parser.druid.MycatStatementParser; import io.mycat.server.parser.ServerParse; /** * Created by magicdoom on 2016/1/26. */ public class SchemaUtil { public static SchemaInfo parseSchema(String sql) { try{ MycatStatementParser parser = new MycatStatementParser(sql); return parseTables(parser.parseStatement(), new MycatSchemaStatVisitor()); }catch (Exception ignore){ return null; } } public static String detectDefaultDb(String sql, int type) { String db = null; Map<String, SchemaConfig> schemaConfigMap = MycatServer.getInstance().getConfig() .getSchemas(); if (ServerParse.SELECT == type) { SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql); if ((schemaInfo == null || schemaInfo.table == null) && !schemaConfigMap.isEmpty()) { db = schemaConfigMap.entrySet().iterator().next().getKey(); } if (schemaInfo != null && schemaInfo.schema != null) { if (schemaConfigMap.containsKey(schemaInfo.schema)) { db = schemaInfo.schema; /** * 对 MySQL 自带的元数据库 information_schema 进行返回 */ } else if ("information_schema".equalsIgnoreCase(schemaInfo.schema)) { db = "information_schema"; } } } else if (ServerParse.INSERT == type || ServerParse.UPDATE == type || ServerParse.DELETE == type || ServerParse.DDL == type) { SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql); if (schemaInfo != null && schemaInfo.schema != null && schemaConfigMap.containsKey(schemaInfo.schema)) { db = schemaInfo.schema; } } else if(ServerParse.COMMAND == type) { int index = sql.indexOf(ServerParse.COM_FIELD_LIST_FLAG); String table = sql.substring(index + 17); db = getSchema(schemaConfigMap, table); } else if ((ServerParse.SHOW == type || ServerParse.USE == type || ServerParse.EXPLAIN == type || ServerParse.SET == type || ServerParse.HELP == type || ServerParse.DESCRIBE == type) && !schemaConfigMap.isEmpty()) { try { //当前存在多个schema的时候使用原来的逻辑会出现bug,改为根据mycat schema配置中的对应关系获取 SQLStatementParser parser = new MySqlStatementParser(sql); SQLShowColumnsStatement stmt = (SQLShowColumnsStatement) parser.parseStatement(); db = getSchema(schemaConfigMap, stmt.getTable().getSimpleName()); } catch (Exception e) { //e.printStackTrace(); //兼容mysql gui 不填默认database db = schemaConfigMap.entrySet().iterator().next().getKey(); } } return db; } /** 根据mycat schema配置中的对应关系获取对应的db */ public static String getSchema(Map<String, SchemaConfig> schemaConfigMap, String table) { String db = null; for (Map.Entry<String,SchemaConfig> entry : schemaConfigMap.entrySet()) { if(entry.getValue().getTables().containsKey(table.toUpperCase())) { db = entry.getKey(); break; } } return db; } public static String parseShowTableSchema(String sql) { // Matcher ma = SHOW_FULL_TABLE_PATTERN.matcher(sql); // if (ma.matches() && ma.groupCount() >= 5) { // return ma.group(5); // } String fields[] =parseShowTable(sql); return fields[3]; } /** * 解析show full table from|in schema-name where table_type|tables_in_xxx like 'xxx' * * @param sql * @return fields' array. * <pre> * [0] is matched, 1 is matcher , other is not matcher * [1] is full, 代表当前是show full tabe ,如果为空则表示show table * [2] from or in * [3] schema-name * [4] where * [5] is 'table_type' or 'tables_in_xxxx' * [6] is 'like' or '=' or ... other operator * [7] * [8] is where match condition str, etc. table-name or table_type like 'BASE TABLE' * </pre> */ public static String[] parseShowTable(String sql) { Matcher matcher = SHOW_FULL_TABLE_PATTERN.matcher(sql); // matcher.matches(); String[] fields = new String[9]; if (matcher.find()) {// show tables fields[0] = "1"; // group(1) is 'full' fields[1] = matcher.group(1); if(fields[1] != null) { fields[1] = fields[1].trim(); } // group(2) is 'from or in' fields[2] = matcher.group(2); if (fields[2] == null || fields[2].length() <= 0) { fields[3] = null; if(matcher.group(3) !=null && "LIKE".equals(matcher.group(3))) { fields[4] = null; } else { fields[4] = "WHERE"; } } else { fields[2] = fields[2].trim(); // group(3) is schema-name fields[3] = matcher.group(3); //group(4) is 'where' fields[4] = matcher.group(4); if(fields[4] != null) { fields[4] = fields[4].trim(); } } //group(5) is 'table_type' or 'tables_in_xxxx' fields[5] = matcher.group(5); //group(6) is 'like' or '=' or ... other operator if(fields[4] == null) { fields[6] = "LIKE"; } else { fields[6] = matcher.group(6); if(fields[6] !=null) { fields[6] = fields[6].trim(); } } //skip fields[7] = matcher.group(7); // //group(8) is where match condition str, etc. table-name or table_type like 'BASE TABLE' fields[8] = matcher.group(8); } return fields; } private static SchemaInfo parseTables(SQLStatement stmt, MycatSchemaStatVisitor schemaStatVisitor) { stmt.accept(schemaStatVisitor); String key = schemaStatVisitor.getCurrentTable(); if (key != null && key.contains("`")) { key = key.replaceAll("`", ""); } if (key != null) { SchemaInfo schemaInfo = new SchemaInfo(); int pos = key.indexOf("."); if (pos > 0) { schemaInfo.schema = key.substring(0, pos); schemaInfo.table = key.substring(pos + 1); } else { schemaInfo.table = key; } return schemaInfo; } return null; } public static class SchemaInfo { public String table; public String schema; @Override public String toString() { final StringBuffer sb = new StringBuffer("SchemaInfo{"); sb.append("table='").append(table).append('\''); sb.append(", schema='").append(schema).append('\''); sb.append('}'); return sb.toString(); } } //sample:SHOW FULL TABLES FROM information_schema WHERE Tables_in_information_schema LIKE 'KEY_COLUMN_USAGE' //注意sql中like后面会有单引号 private static Pattern SHOW_FULL_TABLE_PATTERN = Pattern.compile( "^\\s*show\\s+(full\\s+)?tables \\s*(in |from )?\\s*(\\w+)*\\s*(where )?\\s*(table_type|tables_in_\\w+)*\\s*(\\= |like )?\\s*('([\\w%\\s]+)')*\\s*(;)*\\s*", Pattern.CASE_INSENSITIVE); public static void main(String[] args) { String sql = "SELECT name, type FROM `mysql`.`proc` as xxxx WHERE Db='base'"; // System.out.println(parseSchema(sql)); sql = "insert into aaa.test(id) values(1)"; // System.out.println(parseSchema(sql)); sql = "update updatebase.test set xx=1 "; //System.out.println(parseSchema(sql)); sql = "CREATE TABLE IF not EXISTS `test` (\n" + " `id` bigint(20) NOT NULL AUTO_INCREMENT,\n" + " `sid` bigint(20) DEFAULT NULL,\n" + " `name` varchar(45) DEFAULT NULL,\n" + " `value` varchar(45) DEFAULT NULL,\n" + " `_slot` int(11) DEFAULT NULL COMMENT '自动迁移算法slot,禁止修改',\n" + " PRIMARY KEY (`id`)\n" + ") ENGINE=InnoDB AUTO_INCREMENT=805781256930734081 DEFAULT CHARSET=utf8"; System.out.println(parseSchema(sql)); String pat3 = "SHOW FULL TABLES FROM information_schema WHERE Tables_in_information_schema LIKE 'KEY_COLUMN_USAGE'"; Matcher ma = SHOW_FULL_TABLE_PATTERN.matcher(pat3); if (ma.matches()) { System.out.println(ma.groupCount()); System.out.println(ma.group(5)); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/server/util/SchemaUtil.java
1,086
H tags: Divide and Conquer, Merge Sort, BIT, PreSum, Segment Tree time: O(nlogn) space: O(n) TODO: Write the code + merge function #### Divide and Conquer + PreSum + MergeSort - https://leetcode.com/problems/count-of-range-sum/discuss/77990/Share-my-solution - 1) build preSum[n+1]: then sum range [i,j]= preSum[j+1] - preSum[i] - 2) Divide and Conquer: - 先考虑[start, mid] range里的 ran sum result - 再考虑[mid, end] range里面的结果 - 最后考虑[low, high]总体的结果 - NOTE: should write merge() function, but that is minor, just use `Arrays.sort(nums, start, end)`, OJ passed - Every mergeSort() has a for loop => O(n log n) - 如何 count range? - 这里比较特别的一个做法: 找一个 [low, mid]里面的i, mid 之后的preSum作比较 (解释源自: https://blog.csdn.net/qq508618087/article/details/51435944) - 即在右边数组找到两个边界, 设为`m, n`, - 其中m是在右边数组中第一个使得`sum[m] - sum[i] >= lower`的位置, - n是第一个使得`sum[n] - sum[i] > upper`的位置, - 这样`n-m`就是与左边元素i所构成的位于`[lower, upper]`范围的区间个数. ##### 神奇的重点: 为什么要 merge and sort - 边界[lower, higher] 在 sorted array 好作比较, 一旦过界, 就可以停止计算, 减少不必要计算. - 上面这个n,m的做法可行的前提: preSum[]里面前后两个 range[low, mid], [mid, high]已经sorted了 - 也就是说, 在recursively mergeSort()的时候, 真的需要merge sorted 2 partitions - 也许会问: 能不能sort呢, sort不久打乱了顺序? 对,打乱的是preSum[]的顺序. - 但是不要紧: 很巧妙的, 分治的时候, 前半段/后半段 都在原顺序保留的情况下 分开process完了, 最后才merge - 在做m,n 的range的时候, 原理如下, 比如preSum被分成这么两段: `[A,B,C]`, `[D,E,F]` - 每一个preSum value `A` 在跟 preSum[i] 作比较的时候 `A - preSum < lower`, 都是单一作比较, 不牵扯到 B, C - 因此, `[A, B, C]` 是否保留一开始 preSum的顺序在此时不重要 - 此时最重要的是, `[A,B,C]`以及排序好, 那么在于 `lower` boundary 作比较的时候, 一旦过界, 就可以停止计算(减少不必要的计算) #### BIT - TODO? #### Segment Tree - This segment tree approach(https://leetcode.com/problems/count-of-range-sum/discuss/77987/Java-SegmentTree-Solution-36ms) - does not build segment tree based on given nums index - it is built on sorted preSum array. - regular segment tree based on nums array does not work: - segment tree based on input array is good for: search/query by index - is NOT good at: given range sum/value, find indexes - why? segment tree is built based on index division, not by range value division. ``` /* Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive. Note: A naive algorithm of O(n2) is trivial. You MUST do better than that. Example: Input: nums = [-2,5,-1], lower = -2, upper = 2, Output: 3 Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2. */ class Solution { public int countRangeSum(int[] nums, int lower, int upper) { if (nums == null || nums.length <= 0) return 0; long[] preSum = calcPreSum(nums); return mergeSort(preSum, lower, upper, 0, preSum.length); } private int mergeSort(long[] preSum, int lower, int upper, int start, int end) { if (start + 1 >= end) return 0; int mid = (start + end) / 2, count = 0; // sort two sides count += mergeSort(preSum, lower, upper, start, mid); count += mergeSort(preSum, lower, upper, mid, end); // find the lower/upper bound index range. we know range[start, mid] and [mid, end] has been sorted earlier int lo = mid, hi = mid; for (int i = start; i < mid; i++) { while (lo < end && preSum[lo] - preSum[i] < lower) lo++; while (hi < end && preSum[hi] - preSum[i] <= upper) hi++; count += hi - lo; } // merge two list for range [start, end] Arrays.sort(preSum, start, end); //merge(preSum, start, mid - 1, end - 1); SHOULD use a merge function return count; } } // Same impl, but wtih a customized merge function. Reference. [tool].MergeSort.java class Solution { long[] cache; public int countRangeSum(int[] nums, int lower, int upper) { if (nums == null || nums.length <= 0) return 0; cache = new long[nums.length + 1]; long[] preSum = calcPreSum(nums); return mergeSort(preSum, lower, upper, 0, preSum.length); } private int mergeSort(long[] preSum, int lower, int upper, int start, int end) { if (start + 1 >= end) return 0; int mid = (start + end) / 2, count = 0; // sort two sides count += mergeSort(preSum, lower, upper, start, mid); count += mergeSort(preSum, lower, upper, mid, end); // find the lower/upper bound index range. we know range[start, mid] and [mid, end] has been sorted earlier int lo = mid, hi = mid; for (int i = start; i < mid; i++) { while (lo < end && preSum[lo] - preSum[i] < lower) lo++; while (hi < end && preSum[hi] - preSum[i] <= upper) hi++; count += hi - lo; } // merge two list for range [start, end) merge(preSum, mid - 1, start, end - 1); //SHOULD use a merge function return count; } private long[] calcPreSum(int[] nums) { long[] preSum = new long[nums.length + 1]; for (int i = 1; i < preSum.length; i++) { preSum[i] = preSum[i - 1] + nums[i - 1]; } return preSum; } private void merge(long[] nums, int mid, int start, int end) { int i = start, j = mid + 1, index = start; while (i <= mid && j <= end) { if (nums[i] <= nums[j]) cache[index++] = nums[i++]; else cache[index++] = nums[j++]; } // append the remaining array. // arraycopy: copy from array[i] to cache[index] for (x) items System.arraycopy(nums, i, cache, index, mid - i + 1); // copy remaining of left segment (in case it didn't reach end) System.arraycopy(nums, j, cache, index, end - j + 1); // copy remaining of right segment (in case it didn't reach end) System.arraycopy(cache, start, nums, start, end - start + 1); // copy whole cache[start,end] to original } } ```
awangdev/leet-code
Java/327. Count of Range Sum.java
1,087
/** * @Description:基数排序 * @Author: Hoda * @Date: Create in 2019-07-25 * @Modified By: * @Modified Date: */ public class RadixSort { /** * 基数排序 * * @param arr */ public static void radixSort(int[] arr) { int max = arr[0]; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } // 从个位开始,对数组arr按"指数"进行排序 for (int exp = 1; max / exp > 0; exp *= 10) { countingSort(arr, exp); } } /** * 计数排序-对数组按照"某个位数"进行排序 * * @param arr * @param exp 指数 */ public static void countingSort(int[] arr, int exp) { if (arr.length <= 1) { return; } // 计算每个元素的个数 int[] c = new int[10]; for (int i = 0; i < arr.length; i++) { c[(arr[i] / exp) % 10]++; } // 计算排序后的位置 for (int i = 1; i < c.length; i++) { c[i] += c[i - 1]; } // 临时数组r,存储排序之后的结果 int[] r = new int[arr.length]; for (int i = arr.length - 1; i >= 0; i--) { r[c[(arr[i] / exp) % 10] - 1] = arr[i]; c[(arr[i] / exp) % 10]--; } for (int i = 0; i < arr.length; i++) { arr[i] = r[i]; } } }
wangzheng0822/algo
java/13_sorts/RadixSort.java
1,088
package com.macro.mall.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; /** * 获取OSS上传文件授权返回结果 * Created by macro on 2018/5/17. */ @Data @EqualsAndHashCode public class OssPolicyResult { @ApiModelProperty("访问身份验证中用到用户标识") private String accessKeyId; @ApiModelProperty("用户表单上传的策略,经过base64编码过的字符串") private String policy; @ApiModelProperty("对policy签名后的字符串") private String signature; @ApiModelProperty("上传文件夹路径前缀") private String dir; @ApiModelProperty("oss对外服务的访问域名") private String host; @ApiModelProperty("上传成功后的回调设置") private String callback; }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dto/OssPolicyResult.java
1,097
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat; public class Constants { public static final int MAX_SPEED_POINT = 32; public static final String ALL = "All"; public static final String CAT = "cat"; public static final long MINUTE = 60 * 1000L; public static final long HOUR = 60 * 60 * 1000L; public static final long DAY = 24 * HOUR; public static final long WEEK = 7 * DAY; public static final String HIT = "hit"; public static final String AVG = "avg"; public static final String ERROR = "error"; public static final String HTTP_STATUS = "httpStatus"; public static final String ERROR_CODE = "errorCode"; public static final String TYPE_INFO = "info"; public static final String CHANNEL = "按运营商"; public static final String CITY = "按城市"; public static final String HIT_COUNT = "访问量分布"; public static final String ERROR_COUNT = "错误量分布"; public static final String FRONT_END = "FrontEnd"; public static final String REPORT_BUG = "bug"; public static final String REPORT_SERVICE = "service"; public static final String REPORT_CLIENT = "client"; public static final String REPORT_UTILIZATION = "utilization"; public static final String REPORT_HEAVY = "heavy"; public static final String BROKER_SERVICE = "broker-service"; public static final String WEB_BROKER_SERVICE = "web-broker-service"; public static final String METRIC_USER_MONITOR = "userMonitor"; public static final String METRIC_SYSTEM_MONITOR = "systemMonitor"; public static final String METRIC_CDN = "cdn"; public static final String REPORT_ROUTER = "router"; public static final String REPORT_DATABASE_CAPACITY = "databaseCapacity"; public static final String REPORT_STORAGE_ALERT_DATABASE = "storageDatabaseAlert"; public static final String REPORT_JAR = "jar"; public static final String APP_DATABASE_PRUNER = "appDatabasePruner"; public static final String WEB_DATABASE_PRUNER = "webDatabasePruner"; public static final String METRIC_GRAPH_PRUNER = "metricGraphPruner"; public static final String CURRENT_REPORT = "currentReport"; public static final String REPORT_SYSTEM = "system"; public static final String CMDB = "cmdb"; public static final String APP = "app"; public static final String CURRENT_STR = "当前值"; public static final String COMPARISION_STR = "对比值"; public final static String END_POINT = "endPoint"; public final static String MEASUREMENT = "measurement"; public static final String CRASH = "crash"; }
dianping/cat
cat-core/src/main/java/com/dianping/cat/Constants.java
1,099
package org.nutz.ioc; import java.lang.annotation.Annotation; /** * Ioc 容器接口 * * @author zozoh([email protected]) */ public interface Ioc { /** * 从容器中获取一个对象。同时会触发对象的 fetch 事件。如果第一次构建对象 则会先触发对象 create 事件 * * @param <T> * @param type * 对象的类型,如果为 null,在对象的注入配置中,比如声明对象的类型 <br> * 如果不为null对象注入配置的类型优先 * @param name * 对象的名称 * @return 对象本身 */ <T> T get(Class<T> type, String name) throws IocException; /** * 从容器中获取一个对象。这个对象的名称会根据传入的类型按如下规则决定 * * <ul> * <li>如果定义了注解 '@InjectName',采用其值为注入名 * <li>否则采用类型 simpleName 的首字母小写形式作为注入名 * </ul> * * @param <T> * @param type * 类型 * @return 对象本身 * @throws IocException */ <T> T get(Class<T> type) throws IocException; /** * @param name * 对象名 * @return 是否存在某一特定对象 */ boolean has(String name) throws IocException; /** * @return 所有在容器中定义了的对象名称列表。 */ String[] getNames(); /** * 将容器恢复成初始创建状态,所有的缓存都将被清空 */ void reset(); /** * 将容器注销,触发对象的 depose 事件 */ void depose(); String[] getNamesByType(Class<?> klass); String[] getNamesByAnnotation(Class<? extends Annotation> klass); <K> K getByType(Class<K> klass); Ioc addBean(String name, Object obj); Class<?> getType(String name) throws ObjectLoadException; }
nutzam/nutz
src/org/nutz/ioc/Ioc.java
1,101
package org.springside.jmh; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; /** * 对比测试两种HashMap与EnumMap法的性能 * * 结果相差一倍 */ @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 5) @Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS) @Threads(1) @State(Scope.Benchmark) public class EnumMapTest { public enum TestEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN; } private EnumMap<TestEnum, Integer> enumMap; private HashMap<TestEnum, Integer> hashEnumKeyMap; private HashMap<String, Integer> hashStringKeyMap; @Setup(Level.Trial) public void setup() { hashStringKeyMap = new HashMap<String, Integer>(); initStringKeyMap(hashStringKeyMap); hashEnumKeyMap = new HashMap<TestEnum, Integer>(); initEnumKeyMap(hashEnumKeyMap); enumMap = new EnumMap<TestEnum, Integer>(TestEnum.class); initEnumKeyMap(enumMap); } private void initEnumKeyMap(Map<TestEnum, Integer> map) { map.put(TestEnum.ONE, new Integer(1)); map.put(TestEnum.TWO, new Integer(2)); map.put(TestEnum.FOUR, new Integer(4)); map.put(TestEnum.SIX, new Integer(6)); map.put(TestEnum.SEVEN, new Integer(7)); } private void initStringKeyMap(Map<String, Integer> map) { map.put("ONE", new Integer(1)); map.put("TWO", new Integer(2)); map.put("FOUR", new Integer(4)); map.put("SIX", new Integer(6)); map.put("SEVEN", new Integer(7)); } private int caculateEnumKeyMap(Map<TestEnum, Integer> map) { int result = 0; result += map.get(TestEnum.ONE); result += map.get(TestEnum.TWO); result += map.get(TestEnum.FOUR); result += map.get(TestEnum.SIX); return result; } private Integer caculateStringKeyMap(HashMap<String, Integer> map) { int result = 0; result += map.get("ONE"); result += map.get("TWO"); result += map.get("FOUR"); result += map.get("SIX"); return result; } @Benchmark @Fork(value = 1) public Integer hashMapWithStringKey() { return caculateStringKeyMap(hashStringKeyMap); } @Benchmark @Fork(value = 1) public Integer hashMapWithEnumKey() { return caculateEnumKeyMap(hashEnumKeyMap); } @Benchmark @Fork(value = 1) public Integer enumMap() { return caculateEnumKeyMap(enumMap); } }
springside/springside4
modules/jmh/src/main/java/org/springside/jmh/EnumMapTest.java
1,107
package org.nlpcn.es4sql.domain; import org.elasticsearch.search.sort.ScriptSortBuilder; import org.nlpcn.es4sql.parse.SubQueryExpression; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 将sql语句转换为select 对象 * * @author ansj */ public class Select extends Query { public static int DEFAULT_ROWCOUNT = 1000; // Using this functions, will cause query to execute as aggregation. private final List<String> aggsFunctions = Arrays.asList("SUM", "MAX", "MIN", "AVG", "TOPHITS", "COUNT", "STATS","EXTENDED_STATS","PERCENTILES","SCRIPTED_METRIC", "PERCENTILE_RANKS", "MOVINGAVG", "ROLLINGSTD");//增加对移动平均值和滚动标准差的支持 private List<Field> fields = new ArrayList<>(); private List<List<Field>> groupBys = new ArrayList<>(); private List<Order> orderBys = new ArrayList<>(); private boolean containsSubQueries; private List<SubQueryExpression> subQueries; public boolean isQuery = false; private boolean selectAll = false; //added by xzb 增加 SQL中的 having 语法,实现对聚合结果进行过滤 //select count(age) as ageCnt, avg(age) as ageAvg from bank group by gender having ageAvg > 4.5 and ageCnt > 5 order by ageCnt asc private String having; public boolean isAgg = false; public Select() { setRowCount(DEFAULT_ROWCOUNT); } public List<Field> getFields() { return fields; } public void addGroupBy(Field field) { List<Field> wrapper = new ArrayList<>(); wrapper.add(field); addGroupBy(wrapper); } public String getHaving() { return having; } public void setHaving(String having) { this.having = having; } public void addGroupBy(List<Field> fields) { isAgg = true; this.groupBys.add(fields); } public List<List<Field>> getGroupBys() { return groupBys; } public List<Order> getOrderBys() { return orderBys; } public void addOrderBy(String nestedPath, String name, String type, ScriptSortBuilder.ScriptSortType scriptSortType, Object missing, String unmappedType, String numericType, String format) { if ("_score".equals(name)) { //zhongshu-comment 可以直接在order by子句中写_score,根据该字段排序 select * from tbl order by _score asc isQuery = true; } Order order = new Order(nestedPath, name, type); order.setScriptSortType(scriptSortType); order.setMissing(missing); order.setUnmappedType(unmappedType); order.setNumericType(numericType); order.setFormat(format); this.orderBys.add(order); } public void addField(Field field) { if (field == null ) { return; } if(field.getName().equals("*")){ this.selectAll = true; } if(field instanceof MethodField && aggsFunctions.contains(field.getName().toUpperCase())) { isAgg = true; } fields.add(field); } public void fillSubQueries() { subQueries = new ArrayList<>(); Where where = this.getWhere(); fillSubQueriesFromWhereRecursive(where); } private void fillSubQueriesFromWhereRecursive(Where where) { if(where == null) return; if(where instanceof Condition){ Condition condition = (Condition) where; if ( condition.getValue() instanceof SubQueryExpression){ this.subQueries.add((SubQueryExpression) condition.getValue()); this.containsSubQueries = true; } if(condition.getValue() instanceof Object[]){ for(Object o : (Object[]) condition.getValue()){ if ( o instanceof SubQueryExpression){ this.subQueries.add((SubQueryExpression) o); this.containsSubQueries = true; } } } } else { for(Where innerWhere : where.getWheres()) fillSubQueriesFromWhereRecursive(innerWhere); } } public boolean containsSubQueries() { return containsSubQueries; } public List<SubQueryExpression> getSubQueries() { return subQueries; } public boolean isOrderdSelect(){ return this.getOrderBys()!=null && this.getOrderBys().size() >0 ; } public boolean isSelectAll() { return selectAll; } public void setFields(List<Field> fields) { this.fields = fields; } }
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/domain/Select.java
1,108
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.stat; import com.alibaba.druid.VERSION; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils; import com.alibaba.druid.support.http.stat.WebAppStatManager; import com.alibaba.druid.support.spring.stat.SpringStatManager; import com.alibaba.druid.util.DruidDataSourceUtils; import com.alibaba.druid.util.JdbcSqlStatUtils; import com.alibaba.druid.util.StringUtils; import com.alibaba.druid.util.Utils; import java.sql.Driver; import java.sql.DriverManager; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * 监控相关的对外数据暴露 * <p> * 1. 为了支持jndi数据源本类内部调用druid相关对象均需要反射调用,返回值也应该是Object,List&lt;Object&gt;,Map&lt;String,Object&gt;等无关于druid的类型 * 2. 对外暴露的public方法都应该先调用init(),应该有更好的方式,暂时没想到 * * @author sandzhang[[email protected]] */ public final class DruidStatManagerFacade { private static final DruidStatManagerFacade instance = new DruidStatManagerFacade(); private boolean resetEnable = true; private final AtomicLong resetCount = new AtomicLong(); private DruidStatManagerFacade() { } public static DruidStatManagerFacade getInstance() { return instance; } private Set<Object> getDruidDataSourceInstances() { return DruidDataSourceStatManager.getInstances().keySet(); } public Object getDruidDataSourceByName(String name) { for (Object o : this.getDruidDataSourceInstances()) { String itemName = DruidDataSourceUtils.getName(o); if (StringUtils.equals(name, itemName)) { return o; } } return null; } public void resetDataSourceStat() { DruidDataSourceStatManager.getInstance().reset(); } public void resetSqlStat() { JdbcStatManager.getInstance().reset(); } public void resetAll() { if (!isResetEnable()) { return; } SpringStatManager.getInstance().resetStat(); WebAppStatManager.getInstance().resetStat(); resetSqlStat(); resetDataSourceStat(); resetCount.incrementAndGet(); } public void logAndResetDataSource() { if (!isResetEnable()) { return; } DruidDataSourceStatManager.getInstance().logAndResetDataSource(); } public boolean isResetEnable() { return resetEnable; } public void setResetEnable(boolean resetEnable) { this.resetEnable = resetEnable; } public Object getSqlStatById(Integer id) { for (Object ds : getDruidDataSourceInstances()) { Object sqlStat = DruidDataSourceUtils.getSqlStat(ds, id); if (sqlStat != null) { return sqlStat; } } return null; } public Map<String, Object> getDataSourceStatData(Integer id) { if (id == null) { return null; } Object datasource = getDruidDataSourceById(id); return datasource == null ? null : dataSourceToMapData(datasource, false); } public Object getDruidDataSourceById(Integer identity) { if (identity == null) { return null; } for (Object datasource : getDruidDataSourceInstances()) { if (System.identityHashCode(datasource) == identity) { return datasource; } } return null; } public List<Map<String, Object>> getSqlStatDataList(Integer dataSourceId) { Set<Object> dataSources = getDruidDataSourceInstances(); if (dataSourceId == null) { JdbcDataSourceStat globalStat = JdbcDataSourceStat.getGlobal(); List<Map<String, Object>> sqlList = new ArrayList<Map<String, Object>>(); DruidDataSource globalStatDataSource = null; for (Object datasource : dataSources) { if (datasource instanceof DruidDataSource) { if (((DruidDataSource) datasource).getDataSourceStat() == globalStat) { if (globalStatDataSource == null) { globalStatDataSource = (DruidDataSource) datasource; } else { continue; } } } sqlList.addAll(getSqlStatDataList(datasource)); } return sqlList; } for (Object datasource : dataSources) { if (dataSourceId != null && dataSourceId.intValue() != System.identityHashCode(datasource)) { continue; } return getSqlStatDataList(datasource); } return new ArrayList<Map<String, Object>>(); } @SuppressWarnings("unchecked") public Map<String, Object> getWallStatMap(Integer dataSourceId) { Set<Object> dataSources = getDruidDataSourceInstances(); if (dataSourceId == null) { Map<String, Object> map = new HashMap<String, Object>(); for (Object datasource : dataSources) { Map<String, Object> wallStat = DruidDataSourceUtils.getWallStatMap(datasource); map = mergeWallStat(map, wallStat); } return map; } for (Object datasource : dataSources) { if (dataSourceId != null && dataSourceId.intValue() != System.identityHashCode(datasource)) { continue; } return DruidDataSourceUtils.getWallStatMap(datasource); } return new HashMap<String, Object>(); // } /** * Merges two wall stat maps into a single map. * * @param mapA the first wall stat map to be merged * @param mapB the second wall stat map to be merged * @return a new map that contains the merged wall stats from mapA and mapB * @deprecated */ public static Map mergWallStat(Map mapA, Map mapB) { return mergeWallStat(mapA, mapB); } @SuppressWarnings({"rawtypes", "unchecked"}) public static Map mergeWallStat(Map mapA, Map mapB) { if (mapA == null || mapA.size() == 0) { return mapB; } if (mapB == null || mapB.size() == 0) { return mapA; } Map<String, Object> newMap = new LinkedHashMap<String, Object>(); for (Object item : mapB.entrySet()) { Map.Entry entry = (Map.Entry) item; String key = (String) entry.getKey(); Object valueB = entry.getValue(); Object valueA = mapA.get(key); if (valueA == null) { newMap.put(key, valueB); } else if (valueB == null) { newMap.put(key, valueA); } else if ("blackList".equals(key)) { Map<String, Map<String, Object>> newSet = new HashMap<String, Map<String, Object>>(); Collection<Map<String, Object>> collectionA = (Collection<Map<String, Object>>) valueA; for (Map<String, Object> blackItem : collectionA) { if (newSet.size() >= 1000) { break; } String sql = (String) blackItem.get("sql"); Map<String, Object> oldItem = newSet.get(sql); newSet.put(sql, mergeWallStat(oldItem, blackItem)); } Collection<Map<String, Object>> collectionB = (Collection<Map<String, Object>>) valueB; for (Map<String, Object> blackItem : collectionB) { if (newSet.size() >= 1000) { break; } String sql = (String) blackItem.get("sql"); Map<String, Object> oldItem = newSet.get(sql); newSet.put(sql, mergeWallStat(oldItem, blackItem)); } newMap.put(key, newSet.values()); } else { if (valueA instanceof Map && valueB instanceof Map) { Object newValue = mergeWallStat((Map) valueA, (Map) valueB); newMap.put(key, newValue); } else if (valueA instanceof Set && valueB instanceof Set) { Set<Object> set = new HashSet<Object>(); set.addAll((Set) valueA); set.addAll((Set) valueB); newMap.put(key, set); } else if (valueA instanceof List && valueB instanceof List) { List<Map<String, Object>> mergedList = mergeNamedList((List) valueA, (List) valueB); newMap.put(key, mergedList); } else if (valueA instanceof long[] && valueB instanceof long[]) { long[] arrayA = (long[]) valueA; long[] arrayB = (long[]) valueB; int len = arrayA.length >= arrayB.length ? arrayA.length : arrayB.length; long[] sum = new long[len]; for (int i = 0; i < sum.length; ++i) { if (i < arrayA.length) { sum[i] += arrayA.length; } if (i < arrayB.length) { sum[i] += arrayB.length; } } newMap.put(key, sum); } else if (valueA instanceof String && valueB instanceof String) { newMap.put(key, valueA); } else { Object sum = SQLEvalVisitorUtils.add(valueA, valueB); newMap.put(key, sum); } } } return newMap; } @SuppressWarnings({"rawtypes", "unchecked"}) private static List<Map<String, Object>> mergeNamedList(List listA, List listB) { Map<String, Map<String, Object>> mapped = new HashMap<String, Map<String, Object>>(); for (Object item : (List) listA) { Map<String, Object> map = (Map<String, Object>) item; String name = (String) map.get("name"); mapped.put(name, map); } List<Map<String, Object>> mergedList = new ArrayList<Map<String, Object>>(); for (Object item : (List) listB) { Map<String, Object> mapB = (Map<String, Object>) item; String name = (String) mapB.get("name"); Map<String, Object> mapA = mapped.get(name); Map<String, Object> mergedMap = mergeWallStat(mapA, mapB); mergedList.add(mergedMap); } return mergedList; } public List<Map<String, Object>> getSqlStatDataList(Object datasource) { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); Map<?, ?> sqlStatMap = DruidDataSourceUtils.getSqlStatMap(datasource); for (Object sqlStat : sqlStatMap.values()) { Map<String, Object> data = JdbcSqlStatUtils.getData(sqlStat); long executeCount = (Long) data.get("ExecuteCount"); long runningCount = (Long) data.get("RunningCount"); if (executeCount == 0 && runningCount == 0) { continue; } result.add(data); } return result; } public Map<String, Object> getSqlStatData(Integer id) { if (id == null) { return null; } Object sqlStat = getSqlStatById(id); if (sqlStat == null) { return null; } return JdbcSqlStatUtils.getData(sqlStat); } public List<Map<String, Object>> getDataSourceStatDataList() { return getDataSourceStatDataList(false); } public List<Map<String, Object>> getDataSourceStatDataList(boolean includeSqlList) { List<Map<String, Object>> datasourceList = new ArrayList<Map<String, Object>>(); for (Object dataSource : getDruidDataSourceInstances()) { datasourceList.add(dataSourceToMapData(dataSource, includeSqlList)); } return datasourceList; } public List<List<String>> getActiveConnStackTraceList() { List<List<String>> traceList = new ArrayList<List<String>>(); for (Object dataSource : getDruidDataSourceInstances()) { List<String> stacks = ((DruidDataSource) dataSource).getActiveConnectionStackTrace(); if (stacks.size() > 0) { traceList.add(stacks); } } return traceList; } public Map<String, Object> returnJSONBasicStat() { Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("Version", VERSION.getVersionNumber()); dataMap.put("Drivers", getDriversData()); dataMap.put("ResetEnable", isResetEnable()); dataMap.put("ResetCount", getResetCount()); dataMap.put("JavaVMName", System.getProperty("java.vm.name")); dataMap.put("JavaVersion", System.getProperty("java.version")); dataMap.put("JavaClassPath", System.getProperty("java.class.path")); dataMap.put("StartTime", Utils.getStartTime()); return dataMap; } public long getResetCount() { return resetCount.get(); } private List<String> getDriversData() { List<String> drivers = new ArrayList<String>(); for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = e.nextElement(); drivers.add(driver.getClass().getName()); } return drivers; } public List<Map<String, Object>> getPoolingConnectionInfoByDataSourceId(Integer id) { Object datasource = getDruidDataSourceById(id); if (datasource == null) { return null; } return DruidDataSourceUtils.getPoolingConnectionInfo(datasource); } public List<String> getActiveConnectionStackTraceByDataSourceId(Integer id) { Object datasource = getDruidDataSourceById(id); if (datasource == null || !DruidDataSourceUtils.isRemoveAbandoned(datasource)) { return null; } return DruidDataSourceUtils.getActiveConnectionStackTrace(datasource); } private Map<String, Object> dataSourceToMapData(Object dataSource, boolean includeSql) { Map<String, Object> map = DruidDataSourceUtils.getStatData(dataSource); if (includeSql) { List<Map<String, Object>> sqlList = getSqlStatDataList(dataSource); map.put("SQL", sqlList); } return map; } }
alibaba/druid
core/src/main/java/com/alibaba/druid/stat/DruidStatManagerFacade.java
1,109
package cn.hutool.http.server; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.LimitedInputStream; import cn.hutool.core.map.CaseInsensitiveMap; import cn.hutool.core.map.multi.ListValueMap; import cn.hutool.core.net.NetUtil; import cn.hutool.core.net.multipart.MultipartFormData; import cn.hutool.core.net.multipart.UploadSetting; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.Header; import cn.hutool.http.HttpUtil; import cn.hutool.http.Method; import cn.hutool.http.useragent.UserAgent; import cn.hutool.http.useragent.UserAgentUtil; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; import java.io.InputStream; import java.net.HttpCookie; import java.net.URI; import java.nio.charset.Charset; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; /** * Http请求对象,对{@link HttpExchange}封装 * * @author looly * @since 5.2.6 */ public class HttpServerRequest extends HttpServerBase { private Map<String, HttpCookie> cookieCache; private ListValueMap<String, String> paramsCache; private MultipartFormData multipartFormDataCache; private Charset charsetCache; private byte[] bodyCache; /** * 构造 * * @param httpExchange {@link HttpExchange} */ public HttpServerRequest(HttpExchange httpExchange) { super(httpExchange); } /** * 获得Http Method * * @return Http Method */ public String getMethod() { return this.httpExchange.getRequestMethod(); } /** * 是否为GET请求 * * @return 是否为GET请求 */ public boolean isGetMethod() { return Method.GET.name().equalsIgnoreCase(getMethod()); } /** * 是否为POST请求 * * @return 是否为POST请求 */ public boolean isPostMethod() { return Method.POST.name().equalsIgnoreCase(getMethod()); } /** * 获得请求URI * * @return 请求URI */ public URI getURI() { return this.httpExchange.getRequestURI(); } /** * 获得请求路径Path * * @return 请求路径 */ public String getPath() { return getURI().getPath(); } /** * 获取请求参数 * * @return 参数字符串 */ public String getQuery() { return getURI().getQuery(); } /** * 获得请求header中的信息 * * @return header值 */ public Headers getHeaders() { return this.httpExchange.getRequestHeaders(); } /** * 获得请求header中的信息 * * @param headerKey 头信息的KEY * @return header值 */ public String getHeader(Header headerKey) { return getHeader(headerKey.toString()); } /** * 获得请求header中的信息 * * @param headerKey 头信息的KEY * @return header值 */ public String getHeader(String headerKey) { return getHeaders().getFirst(headerKey); } /** * 获得请求header中的信息 * * @param headerKey 头信息的KEY * @param charset 字符集 * @return header值 */ public String getHeader(String headerKey, Charset charset) { final String header = getHeader(headerKey); if (null != header) { return CharsetUtil.convert(header, CharsetUtil.CHARSET_ISO_8859_1, charset); } return null; } /** * 获取Content-Type头信息 * * @return Content-Type头信息 */ public String getContentType() { return getHeader(Header.CONTENT_TYPE); } /** * 获取编码,获取失败默认使用UTF-8,获取规则如下: * * <pre> * 1、从Content-Type头中获取编码,类似于:text/html;charset=utf-8 * </pre> * * @return 编码,默认UTF-8 */ public Charset getCharset() { if(null == this.charsetCache){ final String contentType = getContentType(); final String charsetStr = HttpUtil.getCharset(contentType); this.charsetCache = CharsetUtil.parse(charsetStr, DEFAULT_CHARSET); } return this.charsetCache; } /** * 获得User-Agent * * @return User-Agent字符串 */ public String getUserAgentStr() { return getHeader(Header.USER_AGENT); } /** * 获得User-Agent,未识别返回null * * @return User-Agent字符串,未识别返回null */ public UserAgent getUserAgent() { return UserAgentUtil.parse(getUserAgentStr()); } /** * 获得Cookie信息字符串 * * @return cookie字符串 */ public String getCookiesStr() { return getHeader(Header.COOKIE); } /** * 获得Cookie信息列表 * * @return Cookie信息列表 */ public Collection<HttpCookie> getCookies() { return getCookieMap().values(); } /** * 获得Cookie信息Map,键为Cookie名,值为HttpCookie对象 * * @return Cookie信息Map */ public Map<String, HttpCookie> getCookieMap() { if (null == this.cookieCache) { cookieCache = Collections.unmodifiableMap(CollUtil.toMap( NetUtil.parseCookies(getCookiesStr()), new CaseInsensitiveMap<>(), HttpCookie::getName)); } return cookieCache; } /** * 获得指定Cookie名对应的HttpCookie对象 * * @param cookieName Cookie名 * @return HttpCookie对象 */ public HttpCookie getCookie(String cookieName) { return getCookieMap().get(cookieName); } /** * 是否为Multipart类型表单,此类型表单用于文件上传 * * @return 是否为Multipart类型表单,此类型表单用于文件上传 */ public boolean isMultipart() { if (false == isPostMethod()) { return false; } final String contentType = getContentType(); if (StrUtil.isBlank(contentType)) { return false; } return contentType.toLowerCase().startsWith("multipart/"); } /** * 获取请求体文本,可以是form表单、json、xml等任意内容<br> * 使用{@link #getCharset()}判断编码,判断失败使用UTF-8编码 * * @return 请求 */ public String getBody() { return getBody(getCharset()); } /** * 获取请求体文本,可以是form表单、json、xml等任意内容 * * @param charset 编码 * @return 请求 */ public String getBody(Charset charset) { return StrUtil.str(getBodyBytes(), charset); } /** * 获取body的bytes数组 * * @return body的bytes数组 */ public byte[] getBodyBytes(){ if(null == this.bodyCache){ this.bodyCache = IoUtil.readBytes(getBodyStream(), true); } return this.bodyCache; } /** * 获取请求体的流,流中可以读取请求内容,包括请求表单数据或文件上传数据 * * @return 流 */ public InputStream getBodyStream() { InputStream bodyStream = this.httpExchange.getRequestBody(); //issue#I6Q30X,读取body长度,避免读取结束后无法正常结束问题 final String contentLengthStr = getHeader(Header.CONTENT_LENGTH); long contentLength = 0; if(StrUtil.isNotBlank(contentLengthStr)){ try{ contentLength = Long.parseLong(contentLengthStr); } catch (final NumberFormatException ignore){ // ignore } } if(contentLength > 0){ bodyStream = new LimitedInputStream(bodyStream, contentLength); } return bodyStream; } /** * 获取指定名称的参数值,取第一个值 * @param name 参数名 * @return 参数值 * @since 5.5.8 */ public String getParam(String name){ return getParams().get(name, 0); } /** * 获取指定名称的参数值 * * @param name 参数名 * @return 参数值 * @since 5.5.8 */ public List<String> getParams(String name){ return getParams().get(name); } /** * 获取参数Map * * @return 参数map */ public ListValueMap<String, String> getParams() { if (null == this.paramsCache) { this.paramsCache = new ListValueMap<>(); final Charset charset = getCharset(); //解析URL中的参数 final String query = getQuery(); if(StrUtil.isNotBlank(query)){ this.paramsCache.putAll(HttpUtil.decodeParams(query, charset, false)); } // 解析multipart中的参数 if(isMultipart()){ this.paramsCache.putAll(getMultipart().getParamListMap()); } else{ // 解析body中的参数 final String body = getBody(); if(StrUtil.isNotBlank(body)){ this.paramsCache.putAll(HttpUtil.decodeParams(body, charset, true)); } } } return this.paramsCache; } /** * 获取客户端IP * * <p> * 默认检测的Header: * * <pre> * 1、X-Forwarded-For * 2、X-Real-IP * 3、Proxy-Client-IP * 4、WL-Proxy-Client-IP * </pre> * * <p> * otherHeaderNames参数用于自定义检测的Header<br> * 需要注意的是,使用此方法获取的客户IP地址必须在Http服务器(例如Nginx)中配置头信息,否则容易造成IP伪造。 * </p> * * @param otherHeaderNames 其他自定义头文件,通常在Http服务器(例如Nginx)中配置 * @return IP地址 */ public String getClientIP(String... otherHeaderNames) { String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"}; if (ArrayUtil.isNotEmpty(otherHeaderNames)) { headers = ArrayUtil.addAll(headers, otherHeaderNames); } return getClientIPByHeader(headers); } /** * 获取客户端IP * * <p> * headerNames参数用于自定义检测的Header<br> * 需要注意的是,使用此方法获取的客户IP地址必须在Http服务器(例如Nginx)中配置头信息,否则容易造成IP伪造。 * </p> * * @param headerNames 自定义头,通常在Http服务器(例如Nginx)中配置 * @return IP地址 * @since 4.4.1 */ public String getClientIPByHeader(String... headerNames) { String ip; for (String header : headerNames) { ip = getHeader(header); if (false == NetUtil.isUnknown(ip)) { return NetUtil.getMultistageReverseProxyIp(ip); } } ip = this.httpExchange.getRemoteAddress().getHostName(); return NetUtil.getMultistageReverseProxyIp(ip); } /** * 获得MultiPart表单内容,多用于获得上传的文件 * * @return MultipartFormData * @throws IORuntimeException IO异常 * @since 5.3.0 */ public MultipartFormData getMultipart() throws IORuntimeException { if(null == this.multipartFormDataCache){ this.multipartFormDataCache = parseMultipart(new UploadSetting()); } return this.multipartFormDataCache; } /** * 获得multipart/form-data 表单内容<br> * 包括文件和普通表单数据<br> * 在同一次请求中,此方法只能被执行一次! * * @param uploadSetting 上传文件的设定,包括最大文件大小、保存在内存的边界大小、临时目录、扩展名限定等 * @return MultiPart表单 * @throws IORuntimeException IO异常 * @since 5.3.0 */ public MultipartFormData parseMultipart(UploadSetting uploadSetting) throws IORuntimeException { final MultipartFormData formData = new MultipartFormData(uploadSetting); try { formData.parseRequestStream(getBodyStream(), getCharset()); } catch (IOException e) { throw new IORuntimeException(e); } return formData; } }
dromara/hutool
hutool-http/src/main/java/cn/hutool/http/server/HttpServerRequest.java
1,110
package cn.hutool.core.lang.id; import cn.hutool.core.util.RandomUtil; import java.security.SecureRandom; import java.util.Random; /** * NanoId,一个小型、安全、对 URL友好的唯一字符串 ID 生成器,特点: * * <ul> * <li>安全:它使用加密、强大的随机 API,并保证符号的正确分配</li> * <li>体积小:只有 258 bytes 大小(压缩后)、无依赖</li> * <li>紧凑:它使用比 UUID (A-Za-z0-9_~)更多的符号</li> * </ul> * * <p> * 此实现的逻辑基于JavaScript的NanoId实现,见:https://github.com/ai/nanoid * * @author David Klebanoff */ public class NanoId { /** * 默认随机数生成器,使用{@link SecureRandom}确保健壮性 */ private static final SecureRandom DEFAULT_NUMBER_GENERATOR = RandomUtil.getSecureRandom(); /** * 默认随机字母表,使用URL安全的Base64字符 */ private static final char[] DEFAULT_ALPHABET = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); /** * 默认长度 */ public static final int DEFAULT_SIZE = 21; /** * 生成伪随机的NanoId字符串,长度为默认的{@link #DEFAULT_SIZE},使用密码安全的伪随机生成器 * * @return 伪随机的NanoId字符串 */ public static String randomNanoId() { return randomNanoId(DEFAULT_SIZE); } /** * 生成伪随机的NanoId字符串 * * @param size ID长度 * @return 伪随机的NanoId字符串 */ public static String randomNanoId(int size) { return randomNanoId(null, null, size); } /** * 生成伪随机的NanoId字符串 * * @param random 随机数生成器 * @param alphabet 随机字母表 * @param size ID长度 * @return 伪随机的NanoId字符串 */ public static String randomNanoId(Random random, char[] alphabet, int size) { if (random == null) { random = DEFAULT_NUMBER_GENERATOR; } if (alphabet == null) { alphabet = DEFAULT_ALPHABET; } if (alphabet.length == 0 || alphabet.length >= 256) { throw new IllegalArgumentException("Alphabet must contain between 1 and 255 symbols."); } if (size <= 0) { throw new IllegalArgumentException("Size must be greater than zero."); } final int mask = (2 << (int) Math.floor(Math.log(alphabet.length - 1) / Math.log(2))) - 1; final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length); final StringBuilder idBuilder = new StringBuilder(); while (true) { final byte[] bytes = new byte[step]; random.nextBytes(bytes); for (int i = 0; i < step; i++) { final int alphabetIndex = bytes[i] & mask; if (alphabetIndex < alphabet.length) { idBuilder.append(alphabet[alphabetIndex]); if (idBuilder.length() == size) { return idBuilder.toString(); } } } } } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/lang/id/NanoId.java
1,111
package com.alibaba.otter.canal.common.zookeeper; import java.util.Map; import org.I0Itec.zkclient.IZkConnection; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.exception.ZkException; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.I0Itec.zkclient.serialize.ZkSerializer; import org.apache.zookeeper.CreateMode; import com.google.common.collect.MigrateMap; /** * 使用自定义的ZooKeeperx for zk connection * * @author jianghang 2012-7-10 下午02:31:15 * @version 1.0.0 */ public class ZkClientx extends ZkClient { // 对于zkclient进行一次缓存,避免一个jvm内部使用多个zk connection private static Map<String, ZkClientx> clients = MigrateMap.makeComputingMap(ZkClientx::new); public static ZkClientx getZkClient(String servers) { return clients.get(servers); } public static void clearClients() { clients.clear(); } public ZkClientx(String serverstring){ this(serverstring, Integer.MAX_VALUE); } public ZkClientx(String zkServers, int connectionTimeout){ this(new ZooKeeperx(zkServers), connectionTimeout); } public ZkClientx(String zkServers, int sessionTimeout, int connectionTimeout){ this(new ZooKeeperx(zkServers, sessionTimeout), connectionTimeout); } public ZkClientx(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer){ this(new ZooKeeperx(zkServers, sessionTimeout), connectionTimeout, zkSerializer); } private ZkClientx(IZkConnection connection, int connectionTimeout){ this(connection, connectionTimeout, new ByteSerializer()); } private ZkClientx(IZkConnection zkConnection, int connectionTimeout, ZkSerializer zkSerializer){ super(zkConnection, connectionTimeout, zkSerializer); } /** * Create a persistent Sequential node. * * @param path * @param createParents if true all parent dirs are created as well and no * {@link ZkNodeExistsException} is thrown in case the path already exists * @throws ZkInterruptedException if operation was interrupted, or a * required reconnection got interrupted * @throws IllegalArgumentException if called from anything except the * ZooKeeper event thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException if any other exception occurs */ public String createPersistentSequential(String path, boolean createParents) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { try { return create(path, null, CreateMode.PERSISTENT_SEQUENTIAL); } catch (ZkNoNodeException e) { if (!createParents) { throw e; } String parentDir = path.substring(0, path.lastIndexOf('/')); createPersistent(parentDir, createParents); return createPersistentSequential(path, createParents); } } /** * Create a persistent Sequential node. * * @param path * @param data * @param createParents if true all parent dirs are created as well and no * {@link ZkNodeExistsException} is thrown in case the path already exists * @throws ZkInterruptedException if operation was interrupted, or a * required reconnection got interrupted * @throws IllegalArgumentException if called from anything except the * ZooKeeper event thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException if any other exception occurs */ public String createPersistentSequential(String path, Object data, boolean createParents) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { try { return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL); } catch (ZkNoNodeException e) { if (!createParents) { throw e; } String parentDir = path.substring(0, path.lastIndexOf('/')); createPersistent(parentDir, createParents); return createPersistentSequential(path, data, createParents); } } /** * Create a persistent Sequential node. * * @param path * @param data * @param createParents if true all parent dirs are created as well and no * {@link ZkNodeExistsException} is thrown in case the path already exists * @throws ZkInterruptedException if operation was interrupted, or a * required reconnection got interrupted * @throws IllegalArgumentException if called from anything except the * ZooKeeper event thread * @throws ZkException if any ZooKeeper exception occurred * @throws RuntimeException if any other exception occurs */ public void createPersistent(String path, Object data, boolean createParents) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { try { create(path, data, CreateMode.PERSISTENT); } catch (ZkNodeExistsException e) { if (!createParents) { throw e; } } catch (ZkNoNodeException e) { if (!createParents) { throw e; } String parentDir = path.substring(0, path.lastIndexOf('/')); createPersistent(parentDir, createParents); createPersistent(path, data, createParents); } } }
alibaba/canal
common/src/main/java/com/alibaba/otter/canal/common/zookeeper/ZkClientx.java
1,112
package io.mycat.route; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.MycatServer; import io.mycat.config.ErrorCode; import io.mycat.route.parser.druid.DruidSequenceHandler; public class MyCATSequnceProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(MyCATSequnceProcessor.class); //使用Druid解析器实现sequence处理 @兵临城下 private static final DruidSequenceHandler sequenceHandler = new DruidSequenceHandler(MycatServer .getInstance().getConfig().getSystem().getSequenceHandlerType(),MycatServer.getInstance().getConfig().getSystem().getSequnceHandlerPattern()); private static class InnerMyCATSequnceProcessor{ private static MyCATSequnceProcessor INSTANCE = new MyCATSequnceProcessor(); } public static MyCATSequnceProcessor getInstance(){ return InnerMyCATSequnceProcessor.INSTANCE; } private MyCATSequnceProcessor() { } /** * 锁的粒度控制到序列级别.一个序列一把锁. * 如果是 db 方式, 可以 给 mycat_sequence表的 name 列 加索引.可以借助mysql 行级锁 提高并发 * @param pair */ public void executeSeq(SessionSQLPair pair) { try { /*// @micmiu 扩展NodeToString实现自定义全局序列号 NodeToString strHandler = new ExtNodeToString4SEQ(MycatServer .getInstance().getConfig().getSystem() .getSequenceHandlerType()); // 如果存在sequence 转化sequence为实际数值 String charset = pair.session.getSource().getCharset(); QueryTreeNode ast = SQLParserDelegate.parse(pair.sql, charset == null ? "utf-8" : charset); String sql = strHandler.toString(ast); if (sql.toUpperCase().startsWith("SELECT")) { String value=sql.substring("SELECT".length()).trim(); outRawData(pair.session.getSource(),value); return; }*/ String charset = pair.session.getSource().getCharset(); String executeSql = sequenceHandler.getExecuteSql(pair,charset == null ? "utf-8":charset); pair.session.getSource().routeEndExecuteSQL(executeSql, pair.type,pair.schema); } catch (Exception e) { LOGGER.error("MyCATSequenceProcessor.executeSeq(SesionSQLPair)",e); pair.session.getSource().writeErrMessage(ErrorCode.ER_YES,"mycat sequnce err." + e); return; } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/route/MyCATSequnceProcessor.java
1,113
/* * Copyright 2017 JessYan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jess.arms.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.View; /** * ================================================ * 处理高斯模糊的工具类 * <p> * Created by JessYan on 03/06/2014. * <a href="mailto:[email protected]">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public class FastBlur { private FastBlur() { throw new IllegalStateException("you can't instantiate me!"); } public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) { // Stack Blur v1.0 from // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html // // Java Author: Mario Klingemann <mario at quasimondo.com> // http://incubator.quasimondo.com // created Feburary 29, 2004 // Android port : Yahel Bouaziz <yahel at kayenko.com> // http://www.kayenko.com // ported april 5th, 2012 // This is a compromise between Gaussian Blur and Box blur // It creates much better looking blurs than Box Blur, but is // 7x faster than my Gaussian Blur implementation. // // I called it Stack Blur because this describes best how this // filter works internally: it creates a kind of moving stack // of colors whilst scanning through the image. Thereby it // just has to add one new block of color to the right side // of the stack and remove the leftmost color. The remaining // colors on the topmost layer of the stack are either added on // or reduced by one, depending on if they are on the right or // on the left side of the stack. // // If you are using this algorithm in your code please add // the following line: // // Stack Blur Algorithm by Mario Klingemann <[email protected]> Bitmap bitmap; if (canReuseInBitmap) { bitmap = sentBitmap; } else { bitmap = sentBitmap.copy(sentBitmap.getConfig(), true); } if (radius < 1) { return (null); } int w = bitmap.getWidth(); int h = bitmap.getHeight(); int[] pix = new int[w * h]; bitmap.getPixels(pix, 0, w, 0, 0, w, h); int wm = w - 1; int hm = h - 1; int wh = w * h; int div = radius + radius + 1; int[] r = new int[wh]; int[] g = new int[wh]; int[] b = new int[wh]; int rsum, gsum, bsum, x, y, i, p, yp, yi, yw; int[] vmin = new int[Math.max(w, h)]; int divsum = (div + 1) >> 1; divsum *= divsum; int[] dv = new int[256 * divsum]; for (i = 0; i < 256 * divsum; i++) { dv[i] = (i / divsum); } yw = yi = 0; int[][] stack = new int[div][3]; int stackpointer; int stackstart; int[] sir; int rbs; int r1 = radius + 1; int routsum, goutsum, boutsum; int rinsum, ginsum, binsum; for (y = 0; y < h; y++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; for (i = -radius; i <= radius; i++) { p = pix[yi + Math.min(wm, Math.max(i, 0))]; sir = stack[i + radius]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rbs = r1 - Math.abs(i); rsum += sir[0] * rbs; gsum += sir[1] * rbs; bsum += sir[2] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } } stackpointer = radius; for (x = 0; x < w; x++) { r[yi] = dv[rsum]; g[yi] = dv[gsum]; b[yi] = dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (y == 0) { vmin[x] = Math.min(x + radius + 1, wm); } p = pix[yw + vmin[x]]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[(stackpointer) % div]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi++; } yw += w; } for (x = 0; x < w; x++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; yp = -radius * w; for (i = -radius; i <= radius; i++) { yi = Math.max(0, yp) + x; sir = stack[i + radius]; sir[0] = r[yi]; sir[1] = g[yi]; sir[2] = b[yi]; rbs = r1 - Math.abs(i); rsum += r[yi] * rbs; gsum += g[yi] * rbs; bsum += b[yi] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } if (i < hm) { yp += w; } } yi = x; stackpointer = radius; for (y = 0; y < h; y++) { // Preserve alpha channel: ( 0xff000000 & pix[yi] ) pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w; } p = x + vmin[y]; sir[0] = r[p]; sir[1] = g[p]; sir[2] = b[p]; rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[stackpointer]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi += w; } } bitmap.setPixels(pix, 0, w, 0, 0, w, h); return (bitmap); } /** * 给 {@link View} 设置高斯模糊背景图片 * * @param context * @param bkg * @param view */ public static void blur(Context context, Bitmap bkg, View view) { long startMs = System.currentTimeMillis(); float radius = 15; float scaleFactor = 8; //放大到整个view的大小 bkg = DrawableProvider.getReSizeBitmap(bkg, view.getMeasuredWidth(), view.getMeasuredHeight()); Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor) , (int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(overlay); canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor); canvas.scale(1 / scaleFactor, 1 / scaleFactor); Paint paint = new Paint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(bkg, 0, 0, paint); overlay = FastBlur.doBlur(overlay, (int) radius, true); view.setBackgroundDrawable(new BitmapDrawable(context.getResources(), overlay)); Log.w("test", "cost " + (System.currentTimeMillis() - startMs) + "ms"); } /** * 将 {@link Bitmap} 高斯模糊并返回 * * @param bkg * @param width * @param height * @return */ public static Bitmap blurBitmap(Bitmap bkg, int width, int height) { long startMs = System.currentTimeMillis(); float radius = 15;//越大模糊效果越大 float scaleFactor = 8; //放大到整个view的大小 bkg = DrawableProvider.getReSizeBitmap(bkg, width, height); Bitmap overlay = Bitmap.createBitmap((int) (width / scaleFactor) , (int) (height / scaleFactor), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(overlay); canvas.scale(1 / scaleFactor, 1 / scaleFactor); Paint paint = new Paint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(bkg, 0, 0, paint); overlay = FastBlur.doBlur(overlay, (int) radius, true); Log.w("test", "cost " + (System.currentTimeMillis() - startMs) + "ms"); return overlay; } }
JessYanCoding/MVPArms
arms/src/main/java/com/jess/arms/utils/FastBlur.java
1,114
package com.macro.mall; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.CompilationUnit; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.internal.DefaultCommentGenerator; import org.mybatis.generator.internal.util.StringUtility; import java.util.Properties; /** * 自定义注释生成器 * Created by macro on 2018/4/26. */ public class CommentGenerator extends DefaultCommentGenerator { private boolean addRemarkComments = false; private static final String EXAMPLE_SUFFIX="Example"; private static final String MAPPER_SUFFIX="Mapper"; private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty"; /** * 设置用户配置的参数 */ @Override public void addConfigurationProperties(Properties properties) { super.addConfigurationProperties(properties); this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments")); } /** * 给字段添加注释 */ @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { String remarks = introspectedColumn.getRemarks(); //根据参数和备注信息判断是否添加swagger注解信息 if(addRemarkComments&&StringUtility.stringHasValue(remarks)){ // addFieldJavaDoc(field, remarks); //数据库中特殊字符需要转义 if(remarks.contains("\"")){ remarks = remarks.replace("\"","'"); } //给model的字段添加swagger注解 field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")"); } } /** * 给model的字段添加注释 */ private void addFieldJavaDoc(Field field, String remarks) { //文档注释开始 field.addJavaDocLine("/**"); //获取数据库字段的备注信息 String[] remarkLines = remarks.split(System.getProperty("line.separator")); for(String remarkLine:remarkLines){ field.addJavaDocLine(" * "+remarkLine); } addJavadocTag(field, false); field.addJavaDocLine(" */"); } @Override public void addJavaFileComment(CompilationUnit compilationUnit) { super.addJavaFileComment(compilationUnit); //只在model中添加swagger注解类的导入 if(!compilationUnit.getType().getFullyQualifiedName().contains(MAPPER_SUFFIX)&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){ compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME)); } } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/CommentGenerator.java
1,120
package me.zhyd.oauth.utils; import java.nio.charset.Charset; /** * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.0.0 */ public class StringUtils { public static boolean isEmpty(String str) { return null == str || str.isEmpty(); } public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * 如果给定字符串{@code str}中不包含{@code appendStr},则在{@code str}后追加{@code appendStr}; * 如果已包含{@code appendStr},则在{@code str}后追加{@code otherwise} * * @param str 给定的字符串 * @param appendStr 需要追加的内容 * @param otherwise 当{@code appendStr}不满足时追加到{@code str}后的内容 * @return 追加后的字符串 */ public static String appendIfNotContain(String str, String appendStr, String otherwise) { if (isEmpty(str) || isEmpty(appendStr)) { return str; } if (str.contains(appendStr)) { return str.concat(otherwise); } return str.concat(appendStr); } /** * 编码字符串 * * @param str 字符串 * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 * @return 编码后的字节码 */ public static byte[] bytes(CharSequence str, Charset charset) { if (str == null) { return null; } if (null == charset) { return str.toString().getBytes(); } return str.toString().getBytes(charset); } /** * 解码字节码 * * @param data 字符串 * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 * @return 解码后的字符串 */ public static String str(byte[] data, Charset charset) { if (data == null) { return null; } if (null == charset) { return new String(data); } return new String(data, charset); } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/utils/StringUtils.java
1,121
package org.nutz.ioc; import java.lang.annotation.Annotation; /** * 容器更高级的方法 * * @author zozoh([email protected]) * */ public interface Ioc2 extends Ioc { /** * 这是更高级的 Ioc 获取对象的方法,它传给 Ioc 容器一个上下文环境。 <br> * 容器以此作为参考,决定如何构建对象,或者将对象缓存在何处 * * @param type * 对象的类型 * @param name * 对象的名称 * @param context * 对象的上下文环境 * @return 对象本身 * * @see org.nutz.ioc.Ioc */ <T> T get(Class<T> type, String name, IocContext context); /** * 获取容器的上下文对象 * * @return 当前容器的上下文对象 */ IocContext getIocContext(); /** * 增加 ValueProxyMaker * * @see org.nutz.ioc.ValueProxy * @see org.nutz.ioc.ValueProxyMaker */ void addValueProxyMaker(ValueProxyMaker vpm); String[] getNamesByType(Class<?> klass, IocContext context); <T> T getByType(Class<T> type, IocContext context); String[] getNamesByAnnotation(Class<? extends Annotation> klass, IocContext context); Class<?> getType(String beanName, IocContext context) throws ObjectLoadException; }
nutzam/nutz
src/org/nutz/ioc/Ioc2.java
1,122
package com.alibaba.arthas.spring; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.core.env.ConfigurableEnvironment; import com.taobao.arthas.agent.attach.ArthasAgent; /** * * @author hengyunabc 2020-06-22 * */ @ConditionalOnProperty(name = "spring.arthas.enabled", matchIfMissing = true) @EnableConfigurationProperties({ ArthasProperties.class }) public class ArthasConfiguration { private static final Logger logger = LoggerFactory.getLogger(ArthasConfiguration.class); @Autowired ConfigurableEnvironment environment; /** * <pre> * 1. 提取所有以 arthas.* 开头的配置项,再统一转换为Arthas配置 * 2. 避免某些配置在新版本里支持,但在ArthasProperties里没有配置的情况。 * </pre> */ @ConfigurationProperties(prefix = "arthas") @ConditionalOnMissingBean(name="arthasConfigMap") @Bean public HashMap<String, String> arthasConfigMap() { return new HashMap<String, String>(); } @ConditionalOnMissingBean @Bean public ArthasAgent arthasAgent(@Autowired @Qualifier("arthasConfigMap") Map<String, String> arthasConfigMap, @Autowired ArthasProperties arthasProperties) throws Throwable { arthasConfigMap = StringUtils.removeDashKey(arthasConfigMap); ArthasProperties.updateArthasConfigMapDefaultValue(arthasConfigMap); /** * @see org.springframework.boot.context.ContextIdApplicationContextInitializer#getApplicationId(ConfigurableEnvironment) */ String appName = environment.getProperty("spring.application.name"); if (arthasConfigMap.get("appName") == null && appName != null) { arthasConfigMap.put("appName", appName); } // 给配置全加上前缀 Map<String, String> mapWithPrefix = new HashMap<String, String>(arthasConfigMap.size()); for (Entry<String, String> entry : arthasConfigMap.entrySet()) { mapWithPrefix.put("arthas." + entry.getKey(), entry.getValue()); } final ArthasAgent arthasAgent = new ArthasAgent(mapWithPrefix, arthasProperties.getHome(), arthasProperties.isSlientInit(), null); arthasAgent.init(); logger.info("Arthas agent start success."); return arthasAgent; } }
alibaba/arthas
arthas-spring-boot-starter/src/main/java/com/alibaba/arthas/spring/ArthasConfiguration.java
1,123
/** * Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.log; /** * The six logging levels used by Log are (in order): * 1. TRACE (the least serious) * 2. DEBUG * 3. INFO * 4. WARN * 5. ERROR * 6. FATAL (the most serious) */ public abstract class Log { private static ILogFactory defaultLogFactory = null; static { init(); } static void init() { if (defaultLogFactory == null) { try { Class.forName("org.apache.log4j.Logger"); Class<?> log4jLogFactoryClass = Class.forName("com.jfinal.log.Log4jLogFactory"); defaultLogFactory = (ILogFactory)log4jLogFactoryClass.newInstance(); // return new Log4jLogFactory(); } catch (Exception e) { defaultLogFactory = new JdkLogFactory(); } } } static void setDefaultLogFactory(ILogFactory defaultLogFactory) { if (defaultLogFactory == null) { throw new IllegalArgumentException("defaultLogFactory can not be null."); } Log.defaultLogFactory = defaultLogFactory; } public static Log getLog(Class<?> clazz) { return defaultLogFactory.getLog(clazz); } public static Log getLog(String name) { return defaultLogFactory.getLog(name); } public abstract void debug(String message); public abstract void debug(String message, Throwable t); public abstract void info(String message); public abstract void info(String message, Throwable t); public abstract void warn(String message); public abstract void warn(String message, Throwable t); public abstract void error(String message); public abstract void error(String message, Throwable t); public abstract void fatal(String message); public abstract void fatal(String message, Throwable t); public abstract boolean isDebugEnabled(); public abstract boolean isInfoEnabled(); public abstract boolean isWarnEnabled(); public abstract boolean isErrorEnabled(); public abstract boolean isFatalEnabled(); // ------------------------------------------------------- /* * 以下 3 个方法为 jfinal 4.8 新增日志级别:trace * 1:为了兼容用户已经扩展出来的 Log 实现,给出了默认实现 * 2:某些日志系统(如 log4j,参考 Log4jLog)需要覆盖以下 * 方法,才能保障日志信息中的类名正确 */ public boolean isTraceEnabled() { return isDebugEnabled(); } public void trace(String message) { debug(message); } public void trace(String message, Throwable t) { debug(message, t); } // ------------------------------------------------------- /* * 以下为 jfinal 4.8 新增的支持可变参数的方法 * 1:为了兼容用户已经扩展出来的 Log 实现,给出了默认实现 * * 2:默认实现通过 String.format(...) 实现的占位符功能与 * slf4j 的占位符用法不同,因此在使用中要保持使用其中某一种, * 否则建议使用其它方法替代下面的 6 个方法 * 注意:jfinal 内部未使用日志的可变参数方法,所以支持各类 * 日志切换使用 * * 3:某些日志系统(如 log4j,参考 Log4jLog)需要覆盖以下方法,才能 * 保障日志信息中的类名正确 */ /** * 判断可变参数是否以 Throwable 结尾 */ protected boolean endsWithThrowable(Object... args) { return args != null && args.length != 0 && args[args.length - 1] instanceof Throwable; } /** * parse(...) 方法必须与 if (endsWithThrowable(...)) 配合使用, * 确保可变参数 Object... args 中的最后一个元素为 Throwable 类型 */ protected LogInfo parse(String format, Object... args) { LogInfo li = new LogInfo(); // 最后一个参数已确定为 Throwable li.throwable = (Throwable)args[args.length - 1]; // 其它参数与 format 一起格式化成 message if (args.length > 1) { Object[] temp = new Object[args.length - 1]; for (int i=0; i<temp.length; i++) { temp[i] = args[i]; } li.message = String.format(format, temp); } else { li.message = format; } return li; } public void trace(String format, Object... args) { if (isTraceEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); trace(li.message, li.throwable); } else { trace(String.format(format, args)); } } } public void debug(String format, Object... args) { if (isDebugEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); debug(li.message, li.throwable); } else { debug(String.format(format, args)); } } } public void info(String format, Object... args) { if (isInfoEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); info(li.message, li.throwable); } else { info(String.format(format, args)); } } } public void warn(String format, Object... args) { if (isWarnEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); warn(li.message, li.throwable); } else { warn(String.format(format, args)); } } } public void error(String format, Object... args) { if (isErrorEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); error(li.message, li.throwable); } else { error(String.format(format, args)); } } } public void fatal(String format, Object... args) { if (isFatalEnabled()) { if (endsWithThrowable(args)) { LogInfo li = parse(format, args); fatal(li.message, li.throwable); } else { fatal(String.format(format, args)); } } } }
jfinal/jfinal
src/main/java/com/jfinal/log/Log.java
1,124
package com.zheng.common.util; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; /** * 验证码工具类 * Created by ZhangShuzheng on 2017/6/28. */ public class CaptchaUtil { // 图片的宽度。 private int width = 160; // 图片的高度。 private int height = 40; // 验证码字符个数 private int codeCount = 4; // 验证码干扰线数 private int lineCount = 20; // 验证码 private String code = null; // 验证码图片Buffer private BufferedImage buffImg = null; Random random = new Random(); public CaptchaUtil() { creatImage(); } public CaptchaUtil(int width, int height) { this.width = width; this.height = height; creatImage(); } public CaptchaUtil(int width, int height, int codeCount) { this.width = width; this.height = height; this.codeCount = codeCount; creatImage(); } public CaptchaUtil(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(); } // 生成图片 private void creatImage() { // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 //Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 float yawpRate = 0.01f;// 噪声率 int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } String str1 = randomStr(codeCount);// 得到随机字符 this.code = str1; for (int i = 0; i < codeCount; i++) { String strRand = str1.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } // 得到随机字符 private String randomStr(int n) { String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; String str2 = ""; int len = str1.length() - 1; double r; for (int i = 0; i < n; i++) { r = (Math.random()) * len; str2 = str2 + str1.charAt((int) r); } return str2; } // 得到随机颜色 private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色 if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 产生随机字体 */ private Font getFont(int size) { Random random = new Random(); Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, size); font[1] = new Font("Antique Olive Compact", Font.PLAIN, size); font[2] = new Font("Fixedsys", Font.PLAIN, size); font[3] = new Font("Wide Latin", Font.PLAIN, size); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size); return font[random.nextInt(5)]; } // 扭曲方法 private void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code.toLowerCase(); } // /** // * 验证码 // * @param request // * @param response // * @param session // * @throws IOException // */ // @RequestMapping("/code.jpg") // public void getCode3(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { // int width = NumberUtils.toInt(request.getParameter("width"), 100); // int height = NumberUtils.toInt(request.getParameter("height"), 30); // int codeCount = NumberUtils.toInt(request.getParameter("codeCount"), 4); // int lineCount = NumberUtils.toInt(request.getParameter("lineCount"), 10); // if (width > 1000) width = 100; // if (height > 300) height = 30; // if (codeCount > 10) codeCount = 4; // if (lineCount > 100) lineCount = 10; // // 设置响应的类型格式为图片格式 // response.setContentType("image/jpeg"); // // 禁止图像缓存。 // response.setHeader("Pragma", "no-cache"); // response.setHeader("Cache-Control", "no-cache"); // response.setDateHeader("Expires", 0); // // 自定义参数 // CaptchaUtil code = new CaptchaUtil(width, height, codeCount, lineCount); // String sessionId = session.getId(); // RedisUtil.set("captcha_" + sessionId, code.getCode(), 60 * 30); // code.write(response.getOutputStream()); // } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/CaptchaUtil.java
1,125
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson.orm; import java.util.List; import java.util.Map; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; /**SQL配置 * @author Lemon */ public interface SQLConfig<T extends Object> { String DATABASE_MYSQL = "MYSQL"; // https://www.mysql.com String DATABASE_POSTGRESQL = "POSTGRESQL"; // https://www.postgresql.org String DATABASE_SQLSERVER = "SQLSERVER"; // https://www.microsoft.com/en-us/sql-server String DATABASE_ORACLE = "ORACLE"; // https://www.oracle.com/database String DATABASE_DB2 = "DB2"; // https://www.ibm.com/products/db2 String DATABASE_MARIADB = "MARIADB"; // https://mariadb.org String DATABASE_TIDB = "TIDB"; // https://www.pingcap.com/tidb String DATABASE_DAMENG = "DAMENG"; // https://www.dameng.com String DATABASE_KINGBASE = "KINGBASE"; // https://www.kingbase.com.cn String DATABASE_ELASTICSEARCH = "ELASTICSEARCH"; // https://www.elastic.co/guide/en/elasticsearch/reference/7.4/xpack-sql.html String DATABASE_CLICKHOUSE = "CLICKHOUSE"; // https://clickhouse.com String DATABASE_HIVE = "HIVE"; // https://hive.apache.org String DATABASE_PRESTO = "PRESTO"; // Facebook PrestoDB https://prestodb.io String DATABASE_TRINO = "TRINO"; // PrestoSQL https://trino.io String DATABASE_SNOWFLAKE = "SNOWFLAKE"; // https://www.snowflake.com String DATABASE_DATABRICKS = "DATABRICKS"; // https://www.databricks.com String DATABASE_CASSANDRA = "CASSANDRA"; // https://cassandra.apache.org String DATABASE_MILVUS = "MILVUS"; // https://milvus.io String DATABASE_INFLUXDB = "INFLUXDB"; // https://www.influxdata.com/products/influxdb-overview String DATABASE_TDENGINE = "TDENGINE"; // https://tdengine.com String DATABASE_REDIS = "REDIS"; // https://redisql.com String DATABASE_MONGODB = "MONGODB"; // https://www.mongodb.com/docs/atlas/data-federation/query/query-with-sql String DATABASE_KAFKA = "KAFKA"; // https://github.com/APIJSON/APIJSON-Demo/tree/master/APIJSON-Java-Server/APIJSONDemo-MultiDataSource-Kafka String DATABASE_MQ = "MQ"; // String SCHEMA_INFORMATION = "information_schema"; //MySQL, PostgreSQL, SQL Server 都有的系统模式 String SCHEMA_SYS = "sys"; //SQL Server 系统模式 String TABLE_SCHEMA = "table_schema"; String TABLE_NAME = "table_name"; int TYPE_CHILD = 0; int TYPE_ITEM = 1; int TYPE_ITEM_CHILD_0 = 2; Parser<T> getParser(); SQLConfig setParser(Parser<T> parser); ObjectParser getObjectParser(); SQLConfig setObjectParser(ObjectParser objectParser); int getVersion(); SQLConfig setVersion(int version); String getTag(); SQLConfig setTag(String tag); boolean isMySQL(); boolean isPostgreSQL(); boolean isSQLServer(); boolean isOracle(); boolean isDb2(); boolean isMariaDB(); boolean isTiDB(); boolean isDameng(); boolean isKingBase(); boolean isElasticsearch(); boolean isClickHouse(); boolean isHive(); boolean isPresto(); boolean isTrino(); boolean isSnowflake(); boolean isDatabricks(); boolean isCassandra(); boolean isMilvus(); boolean isInfluxDB(); boolean isTDengine(); boolean isRedis(); boolean isMongoDB(); boolean isKafka(); boolean isMQ(); // 暂时只兼容以上几种 // boolean isSQL(); // boolean isTSQL(); // boolean isPLSQL(); // boolean isAnsiSQL(); /**用来给 Table, Column 等系统属性表来绕过 MAX_SQL_COUNT 等限制 * @return */ boolean limitSQLCount(); /**是否开启 WITH AS 表达式来简化 SQL 和提升性能 * @return */ boolean isWithAsEnable(); /**允许增删改部分失败 * @return */ boolean allowPartialUpdateFailed(); @NotNull String getIdKey(); @NotNull String getUserIdKey(); /**获取数据库版本号,可通过判断版本号解决一些 JDBC 驱动连接数据库的兼容问题 * MYSQL: 8.0, 5.7, 5.6 等; PostgreSQL: 11, 10, 9.6 等 * @return */ String getDBVersion(); @NotNull default int[] getDBVersionNums() { String dbVersion = StringUtil.getNoBlankString(getDBVersion()); if (dbVersion.isEmpty()) { return new int[]{0}; } int index = dbVersion.indexOf("-"); if (index > 0) { dbVersion = dbVersion.substring(0, index); } String[] ss = dbVersion.split("[.]"); int[] nums = new int[Math.max(1, ss.length)]; for (int i = 0; i < ss.length; i++) { nums[i] = Integer.valueOf(ss[i]); } return nums; } /**获取数据库地址 * @return */ String getDBUri(); /**获取数据库账号 * @return */ String getDBAccount(); /**获取数据库密码 * @return */ String getDBPassword(); /**获取SQL语句 * @return * @throws Exception */ String getSQL(boolean prepared) throws Exception; boolean isTest(); SQLConfig setTest(boolean test); int getType(); SQLConfig setType(int type); int getCount(); SQLConfig setCount(int count); int getPage(); SQLConfig setPage(int page); int getQuery(); SQLConfig setQuery(int query); Boolean getCompat(); SQLConfig setCompat(Boolean compat); int getPosition(); SQLConfig setPosition(int position); int getCache(); SQLConfig setCache(int cache); boolean isExplain(); SQLConfig setExplain(boolean explain); RequestMethod getMethod(); SQLConfig setMethod(RequestMethod method); Object getId(); SQLConfig setId(Object id); Object getIdIn(); SQLConfig setIdIn(Object idIn); Object getUserId(); SQLConfig setUserId(Object userId); Object getUserIdIn(); SQLConfig setUserIdIn(Object userIdIn); String getRole(); SQLConfig setRole(String role); public boolean isDistinct(); public SQLConfig setDistinct(boolean distinct); String getDatabase(); SQLConfig setDatabase(String database); String getSQLSchema(); String getSchema(); SQLConfig setSchema(String schema); String getDatasource(); SQLConfig setDatasource(String datasource); String getQuote(); List<String> getJson(); SQLConfig setJson(List<String> json); /**请求传进来的Table名 * @return * @see {@link #getSQLTable()} */ String getTable(); SQLConfig setTable(String table); /**数据库里的真实Table名 * 通过 {@link AbstractSQLConfig.TABLE_KEY_MAP} 映射 * @return */ String getSQLTable(); String getTablePath(); Map<String, String> getKeyMap(); SQLConfig setKeyMap(Map<String, String> keyMap); List<String> getRaw(); SQLConfig setRaw(List<String> raw); Subquery getFrom(); SQLConfig setFrom(Subquery from); List<String> getColumn(); SQLConfig setColumn(List<String> column); List<List<Object>> getValues(); SQLConfig setValues(List<List<Object>> values); Map<String, Object> getContent(); SQLConfig setContent(Map<String, Object> content); Map<String, List<String>> getCombineMap(); SQLConfig setCombineMap(Map<String, List<String>> combineMap); String getCombine(); SQLConfig setCombine(String combine); Map<String, String> getCast(); SQLConfig setCast(Map<String, String> cast); List<String> getNull(); SQLConfig setNull(List<String> nulls); Map<String, Object> getWhere(); SQLConfig setWhere(Map<String, Object> where); String getGroup(); SQLConfig setGroup(String group); Map<String, Object> getHaving(); SQLConfig setHaving(Map<String, Object> having); String getHavingCombine(); SQLConfig setHavingCombine(String havingCombine); String getOrder(); SQLConfig setOrder(String order); /** * exactMatch = false * @param key * @return */ Object getWhere(String key); /** * @param key * @param exactMatch * @return */ Object getWhere(String key, boolean exactMatch); /** * @param key * @param value * @return */ SQLConfig putWhere(String key, Object value, boolean prior); boolean isPrepared(); SQLConfig setPrepared(boolean prepared); boolean isMain(); SQLConfig setMain(boolean main); List<Object> getPreparedValueList(); SQLConfig setPreparedValueList(List<Object> preparedValueList); String getAlias(); SQLConfig setAlias(String alias); String getWhereString(boolean hasPrefix) throws Exception; String getRawSQL(String key, Object value) throws Exception; String getRawSQL(String key, Object value, boolean throwWhenMissing) throws Exception; boolean isKeyPrefix(); SQLConfig setKeyPrefix(boolean keyPrefix); List<Join> getJoinList(); SQLConfig setJoinList(List<Join> joinList); boolean hasJoin(); String getSubqueryString(Subquery subquery) throws Exception; SQLConfig setProcedure(String procedure); List<Object> getWithAsExprPreparedValueList(); SQLConfig setWithAsExprPreparedValueList(List<Object> withAsExprePreparedValueList); boolean isFakeDelete(); Map<String, Object> onFakeDelete(Map<String, Object> map); }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/SQLConfig.java
1,126
package org.ansj.util; import org.ansj.app.crf.SplitWord; import org.ansj.dic.DicReader; import org.ansj.dic.impl.Jdbc2Stream; import org.ansj.domain.AnsjItem; import org.ansj.exception.LibraryException; import org.ansj.library.*; import org.ansj.recognition.impl.StopRecognition; import org.nlpcn.commons.lang.tire.domain.Forest; import org.nlpcn.commons.lang.tire.domain.SmartForest; import org.nlpcn.commons.lang.util.FileFinder; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.ObjConver; import org.nlpcn.commons.lang.util.StringUtil; import org.nlpcn.commons.lang.util.logging.Log; import org.nlpcn.commons.lang.util.logging.LogFactory; import java.io.*; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; /** * 这个类储存一些公用变量. * * @author ansj */ public class MyStaticValue { public static final Log LOG = LogFactory.getLog(MyStaticValue.class); // 是否开启人名识别 public static Boolean isNameRecognition = true; // 是否开启数字识别 public static Boolean isNumRecognition = true; // 是否数字和量词合并 public static Boolean isQuantifierRecognition = true; // 是否显示真实词语 public static Boolean isRealName = false; /** * 标记是否是新词 */ public static boolean isNewWord = true; /** * 是否用户辞典不加载相同的词 */ public static boolean isSkipUserDefine = false; public static final Map<String, String> ENV = new HashMap<>(); static { /** * 配置文件变量 */ ResourceBundle rb = null; try { rb = ResourceBundle.getBundle("ansj_library"); } catch (Exception e) { try { File find = FileFinder.find("ansj_library.properties", 1); if (find != null && find.isFile()) { rb = new PropertyResourceBundle(IOUtil.getReader(find.getAbsolutePath(), System.getProperty("file.encoding"))); LOG.info("load ansj_library not find in classPath ! i find it in " + find.getAbsolutePath() + " make sure it is your config!"); } } catch (Exception e1) { LOG.warn("not find ansj_library.properties. reason: " + e1.getMessage()); } } if (rb == null) { try { rb = ResourceBundle.getBundle("library"); } catch (Exception e) { try { File find = FileFinder.find("library.properties", 2); if (find != null && find.isFile()) { rb = new PropertyResourceBundle(IOUtil.getReader(find.getAbsolutePath(), System.getProperty("file.encoding"))); LOG.info("load library not find in classPath ! i find it in " + find.getAbsolutePath() + " make sure it is your config!"); } } catch (Exception e1) { LOG.warn("not find library.properties. reason: " + e1.getMessage()); } } } if (rb == null) { LOG.warn("not find library.properties in classpath use it by default !"); } else { for (String key : rb.keySet()) { ENV.put(key, rb.getString(key)); try { String value = rb.getString(key); if (value.startsWith("jdbc:")) { //给jdbc窜中密码做一个加密,不让密码明文在日志中 value = Jdbc2Stream.encryption(value); } LOG.info("init " + key + " to env value is : " + value); Field field = MyStaticValue.class.getField(key); field.set(null, ObjConver.conversion(rb.getString(key), field.getType())); } catch (Exception e) { } } } } /** * 人名词典 * * @return */ public static BufferedReader getPersonReader() { return DicReader.getReader("person/person.dic"); } /** * 机构名词典 * * @return */ public static BufferedReader getCompanReader() { return DicReader.getReader("company/company.data"); } /** * 机构名词典 * * @return */ public static BufferedReader getNewWordReader() { return DicReader.getReader("newWord/new_word_freq.dic"); } /** * 核心词典 * * @return */ public static BufferedReader getArraysReader() { return DicReader.getReader("arrays.dic"); } /** * 数字词典 * * @return */ public static BufferedReader getNumberReader() { return DicReader.getReader("numberLibrary.dic"); } /** * 词性表 * * @return */ public static BufferedReader getNatureMapReader() { return DicReader.getReader("nature/nature.map"); } /** * 词性关联表 * * @return */ public static BufferedReader getNatureTableReader() { return DicReader.getReader("nature/nature.table"); } /** * 人名识别 * * @return */ public static BufferedReader getPersonDicReader() throws FileNotFoundException, UnsupportedEncodingException { return IOUtil.getReader(new SequenceInputStream(DicReader.getInputStream("person/person.txt"), DicReader.getInputStream("person/person_split.txt")), "UTF-8"); } /** * 人名识别 * * @return */ public static BufferedReader getForeignDicReader() throws FileNotFoundException, UnsupportedEncodingException { return IOUtil.getReader(new SequenceInputStream(DicReader.getInputStream("person/foreign.txt"), DicReader.getInputStream("person/person_split.txt")), "UTF-8"); } public static BufferedReader getNatureClassSuffix() { return DicReader.getReader("nature_class_suffix.txt"); } /** * 词与词之间的关联表数据 * * @return */ public static void initBigramTables() { try (BufferedReader reader = IOUtil.getReader(DicReader.getInputStream("bigramdict.dic"), "UTF-8")) { String temp = null; String[] strs = null; int freq = 0; while ((temp = reader.readLine()) != null) { if (StringUtil.isBlank(temp)) { continue; } strs = temp.split("\t"); freq = Integer.parseInt(strs[1]); strs = strs[0].split("@"); AnsjItem fromItem = DATDictionary.getItem(strs[0]); AnsjItem toItem = DATDictionary.getItem(strs[1]); if (fromItem == AnsjItem.NULL && strs[0].contains("#")) { fromItem = AnsjItem.BEGIN; } if (toItem == AnsjItem.NULL && strs[1].contains("#")) { toItem = AnsjItem.END; } if (fromItem == AnsjItem.NULL || toItem == AnsjItem.NULL) { continue; } if (fromItem.bigramEntryMap == null) { fromItem.bigramEntryMap = new HashMap<Integer, Integer>(); } fromItem.bigramEntryMap.put(toItem.getIndex(), freq); } } catch (NumberFormatException e) { LOG.warn("数字格式异常", e); } catch (UnsupportedEncodingException e) { LOG.warn("不支持的编码", e); } catch (IOException e) { LOG.warn("IO异常", e); } } /* * 外部引用为了实例化加载变量 */ public static Log getLog(Class<?> clazz) { return LogFactory.getLog(clazz); } /** * 增加一个词典 * * @param key * @param path * @param value */ public static void putLibrary(String key, String path, Object value) { if (key.startsWith(DicLibrary.DEFAULT)) { DicLibrary.put(key, path, (Forest) value); } else if (key.startsWith(StopLibrary.DEFAULT)) { StopLibrary.put(key, path, (StopRecognition) value); } else if (key.startsWith(SynonymsLibrary.DEFAULT)) { SynonymsLibrary.put(key, path, (SmartForest) value); } else if (key.startsWith(AmbiguityLibrary.DEFAULT)) { AmbiguityLibrary.put(key, path, (Forest) value); } else if (key.startsWith(CrfLibrary.DEFAULT)) { CrfLibrary.put(key, path, (SplitWord) value); } else { throw new LibraryException(key + " type err must start with dic,stop,ambiguity,synonyms"); } ENV.put(key, path); } /** * 懒加载一个词典 * * @param key * @param path */ public static void putLibrary(String key, String path) { if (key.startsWith(DicLibrary.DEFAULT)) { DicLibrary.put(key, path); } else if (key.startsWith(StopLibrary.DEFAULT)) { StopLibrary.put(key, path); } else if (key.startsWith(SynonymsLibrary.DEFAULT)) { SynonymsLibrary.put(key, path); } else if (key.startsWith(AmbiguityLibrary.DEFAULT)) { AmbiguityLibrary.put(key, path); } else if (key.startsWith(CrfLibrary.DEFAULT)) { CrfLibrary.put(key, path); } else { throw new LibraryException(key + " type err must start with dic,stop,ambiguity,synonyms"); } ENV.put(key, path); } /** * 删除一个词典 * * @param key */ public static void removeLibrary(String key) { if (key.startsWith(DicLibrary.DEFAULT)) { DicLibrary.remove(key); } else if (key.startsWith(StopLibrary.DEFAULT)) { StopLibrary.remove(key); } else if (key.startsWith(SynonymsLibrary.DEFAULT)) { SynonymsLibrary.remove(key); } else if (key.startsWith(AmbiguityLibrary.DEFAULT)) { AmbiguityLibrary.remove(key); } else if (key.startsWith(CrfLibrary.DEFAULT)) { CrfLibrary.remove(key); } else { throw new LibraryException(key + " type err must start with dic,stop,ambiguity,synonyms"); } ENV.remove(key); } /** * 重置一个词典 * * @param key */ public static void reloadLibrary(String key) { if (key.startsWith(DicLibrary.DEFAULT)) { DicLibrary.reload(key); } else if (key.startsWith(StopLibrary.DEFAULT)) { StopLibrary.reload(key); } else if (key.startsWith(SynonymsLibrary.DEFAULT)) { SynonymsLibrary.reload(key); } else if (key.startsWith(AmbiguityLibrary.DEFAULT)) { AmbiguityLibrary.reload(key); } else if (key.startsWith(CrfLibrary.DEFAULT)) { CrfLibrary.reload(key); } else { throw new LibraryException(key + " type err must start with dic,stop,ambiguity,synonyms"); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/util/MyStaticValue.java
1,127
package com.taobao.tddl.dbsync.binlog; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.taobao.tddl.dbsync.binlog.event.LogHeader; /** * Binary log event definitions. This includes generic code common to all types * of log events, as well as specific code for each type of log event. - All * numbers, whether they are 16-, 24-, 32-, or 64-bit numbers, are stored in * little endian, i.e., the least significant byte first, unless otherwise * specified. representation of unsigned integers, called Packed Integer. A * Packed Integer has the capacity of storing up to 8-byte integers, while small * integers still can use 1, 3, or 4 bytes. The value of the first byte * determines how to read the number, according to the following table: * <table> * <caption>Format of Packed Integer</caption> * <tr> * <th>First byte</th> * <th>Format</th> * </tr> * <tr> * <td>0-250</td> * <td>The first byte is the number (in the range 0-250), and no more bytes are * used.</td> * </tr> * <tr> * <td>252</td> * <td>Two more bytes are used. The number is in the range 251-0xffff.</td> * </tr> * <tr> * <td>253</td> * <td>Three more bytes are used. The number is in the range 0xffff-0xffffff.</td> * </tr> * <tr> * <td>254</td> * <td>Eight more bytes are used. The number is in the range * 0xffffff-0xffffffffffffffff.</td> * </tr> * </table> * - Strings are stored in various formats. The format of each string is * documented separately. * * @see mysql-5.1.60/sql/log_event.h * @author <a href="mailto:[email protected]">Changyuan.lh</a> * @version 1.0 */ public abstract class LogEvent { /* * 3 is MySQL 4.x; 4 is MySQL 5.0.0. Compared to version 3, version 4 has: - * a different Start_log_event, which includes info about the binary log * (sizes of headers); this info is included for better compatibility if the * master's MySQL version is different from the slave's. - all events have a * unique ID (the triplet (server_id, timestamp at server start, other) to * be sure an event is not executed more than once in a multimaster setup, * example: M1 / \ v v M2 M3 \ / v v S if a query is run on M1, it will * arrive twice on S, so we need that S remembers the last unique ID it has * processed, to compare and know if the event should be skipped or not. * Example of ID: we already have the server id (4 bytes), plus: * timestamp_when_the_master_started (4 bytes), a counter (a sequence number * which increments every time we write an event to the binlog) (3 bytes). * Q: how do we handle when the counter is overflowed and restarts from 0 ? * - Query and Load (Create or Execute) events may have a more precise * timestamp (with microseconds), number of matched/affected/warnings rows * and fields of session variables: SQL_MODE, FOREIGN_KEY_CHECKS, * UNIQUE_CHECKS, SQL_AUTO_IS_NULL, the collations and charsets, the * PASSWORD() version (old/new/...). */ public static final int BINLOG_VERSION = 4; /* Default 5.0 server version */ public static final String SERVER_VERSION = "5.0"; /** * Event header offsets; these point to places inside the fixed header. */ public static final int EVENT_TYPE_OFFSET = 4; public static final int SERVER_ID_OFFSET = 5; public static final int EVENT_LEN_OFFSET = 9; public static final int LOG_POS_OFFSET = 13; public static final int FLAGS_OFFSET = 17; /* event-specific post-header sizes */ // where 3.23, 4.x and 5.0 agree public static final int QUERY_HEADER_MINIMAL_LEN = (4 + 4 + 1 + 2); // where 5.0 differs: 2 for len of N-bytes vars. public static final int QUERY_HEADER_LEN = (QUERY_HEADER_MINIMAL_LEN + 2); /* Enumeration type for the different types of log events. */ public static final int UNKNOWN_EVENT = 0; public static final int START_EVENT_V3 = 1; public static final int QUERY_EVENT = 2; public static final int STOP_EVENT = 3; public static final int ROTATE_EVENT = 4; public static final int INTVAR_EVENT = 5; public static final int LOAD_EVENT = 6; public static final int SLAVE_EVENT = 7; public static final int CREATE_FILE_EVENT = 8; public static final int APPEND_BLOCK_EVENT = 9; public static final int EXEC_LOAD_EVENT = 10; public static final int DELETE_FILE_EVENT = 11; /** * NEW_LOAD_EVENT is like LOAD_EVENT except that it has a longer sql_ex, * allowing multibyte TERMINATED BY etc; both types share the same class * (Load_log_event) */ public static final int NEW_LOAD_EVENT = 12; public static final int RAND_EVENT = 13; public static final int USER_VAR_EVENT = 14; public static final int FORMAT_DESCRIPTION_EVENT = 15; public static final int XID_EVENT = 16; public static final int BEGIN_LOAD_QUERY_EVENT = 17; public static final int EXECUTE_LOAD_QUERY_EVENT = 18; public static final int TABLE_MAP_EVENT = 19; /** * These event numbers were used for 5.1.0 to 5.1.15 and are therefore * obsolete. */ public static final int PRE_GA_WRITE_ROWS_EVENT = 20; public static final int PRE_GA_UPDATE_ROWS_EVENT = 21; public static final int PRE_GA_DELETE_ROWS_EVENT = 22; /** * These event numbers are used from 5.1.16 and forward */ public static final int WRITE_ROWS_EVENT_V1 = 23; public static final int UPDATE_ROWS_EVENT_V1 = 24; public static final int DELETE_ROWS_EVENT_V1 = 25; /** * Something out of the ordinary happened on the master */ public static final int INCIDENT_EVENT = 26; /** * Heartbeat event to be send by master at its idle time to ensure master's * online status to slave */ public static final int HEARTBEAT_LOG_EVENT = 27; /** * In some situations, it is necessary to send over ignorable data to the * slave: data that a slave can handle in case there is code for handling * it, but which can be ignored if it is not recognized. */ public static final int IGNORABLE_LOG_EVENT = 28; public static final int ROWS_QUERY_LOG_EVENT = 29; /** Version 2 of the Row events */ public static final int WRITE_ROWS_EVENT = 30; public static final int UPDATE_ROWS_EVENT = 31; public static final int DELETE_ROWS_EVENT = 32; public static final int GTID_LOG_EVENT = 33; public static final int ANONYMOUS_GTID_LOG_EVENT = 34; public static final int PREVIOUS_GTIDS_LOG_EVENT = 35; /* MySQL 5.7 events */ public static final int TRANSACTION_CONTEXT_EVENT = 36; public static final int VIEW_CHANGE_EVENT = 37; /* Prepared XA transaction terminal event similar to Xid */ public static final int XA_PREPARE_LOG_EVENT = 38; /** * Extension of UPDATE_ROWS_EVENT, allowing partial values according to * binlog_row_value_options. */ public static final int PARTIAL_UPDATE_ROWS_EVENT = 39; /* mysql 8.0.20 */ public static final int TRANSACTION_PAYLOAD_EVENT = 40; /* mysql 8.0.26 */ public static final int HEARTBEAT_LOG_EVENT_V2 = 41; public static final int MYSQL_ENUM_END_EVENT = 42; // mariaDb 5.5.34 /* New MySQL/Sun events are to be added right above this comment */ public static final int MYSQL_EVENTS_END = 49; public static final int MARIA_EVENTS_BEGIN = 160; /* New Maria event numbers start from here */ public static final int ANNOTATE_ROWS_EVENT = 160; /* * Binlog checkpoint event. Used for XA crash recovery on the master, not * used in replication. A binlog checkpoint event specifies a binlog file * such that XA crash recovery can start from that file - and it is * guaranteed to find all XIDs that are prepared in storage engines but not * yet committed. */ public static final int BINLOG_CHECKPOINT_EVENT = 161; /* * Gtid event. For global transaction ID, used to start a new event group, * instead of the old BEGIN query event, and also to mark stand-alone * events. */ public static final int GTID_EVENT = 162; /* * Gtid list event. Logged at the start of every binlog, to record the * current replication state. This consists of the last GTID seen for each * replication domain. */ public static final int GTID_LIST_EVENT = 163; public static final int START_ENCRYPTION_EVENT = 164; // mariadb 10.10.1 /* * Compressed binlog event. Note that the order between WRITE/UPDATE/DELETE * events is significant; this is so that we can convert from the compressed to * the uncompressed event type with (type-WRITE_ROWS_COMPRESSED_EVENT + * WRITE_ROWS_EVENT) and similar for _V1. */ public static final int QUERY_COMPRESSED_EVENT = 165; public static final int WRITE_ROWS_COMPRESSED_EVENT_V1 = 166; public static final int UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167; public static final int DELETE_ROWS_COMPRESSED_EVENT_V1 = 168; public static final int WRITE_ROWS_COMPRESSED_EVENT = 169; public static final int UPDATE_ROWS_COMPRESSED_EVENT = 170; public static final int DELETE_ROWS_COMPRESSED_EVENT = 171; /** end marker */ public static final int ENUM_END_EVENT = 171; /** * 1 byte length, 1 byte format Length is total length in bytes, including 2 * byte header Length values 0 and 1 are currently invalid and reserved. */ public static final int EXTRA_ROW_INFO_LEN_OFFSET = 0; public static final int EXTRA_ROW_INFO_FORMAT_OFFSET = 1; public static final int EXTRA_ROW_INFO_HDR_BYTES = 2; public static final int EXTRA_ROW_INFO_MAX_PAYLOAD = (255 - EXTRA_ROW_INFO_HDR_BYTES); // Events are without checksum though its generator public static final int BINLOG_CHECKSUM_ALG_OFF = 0; // is checksum-capable New Master (NM). // CRC32 of zlib algorithm. public static final int BINLOG_CHECKSUM_ALG_CRC32 = 1; // the cut line: valid alg range is [1, 0x7f]. public static final int BINLOG_CHECKSUM_ALG_ENUM_END = 2; // special value to tag undetermined yet checksum public static final int BINLOG_CHECKSUM_ALG_UNDEF = 255; // or events from checksum-unaware servers public static final int CHECKSUM_CRC32_SIGNATURE_LEN = 4; public static final int BINLOG_CHECKSUM_ALG_DESC_LEN = 1; /** * defined statically while there is just one alg implemented */ public static final int BINLOG_CHECKSUM_LEN = CHECKSUM_CRC32_SIGNATURE_LEN; /* MySQL or old MariaDB slave with no announced capability. */ public static final int MARIA_SLAVE_CAPABILITY_UNKNOWN = 0; /* MariaDB >= 5.3, which understands ANNOTATE_ROWS_EVENT. */ public static final int MARIA_SLAVE_CAPABILITY_ANNOTATE = 1; /* * MariaDB >= 5.5. This version has the capability to tolerate events * omitted from the binlog stream without breaking replication (MySQL slaves * fail because they mis-compute the offsets into the master's binlog). */ public static final int MARIA_SLAVE_CAPABILITY_TOLERATE_HOLES = 2; /* MariaDB >= 10.0, which knows about binlog_checkpoint_log_event. */ public static final int MARIA_SLAVE_CAPABILITY_BINLOG_CHECKPOINT = 3; /* MariaDB >= 10.0.1, which knows about global transaction id events. */ public static final int MARIA_SLAVE_CAPABILITY_GTID = 4; /* Our capability. */ public static final int MARIA_SLAVE_CAPABILITY_MINE = MARIA_SLAVE_CAPABILITY_GTID; /** * For an event, 'e', carrying a type code, that a slave, 's', does not * recognize, 's' will check 'e' for LOG_EVENT_IGNORABLE_F, and if the flag * is set, then 'e' is ignored. Otherwise, 's' acknowledges that it has * found an unknown event in the relay log. */ public static final int LOG_EVENT_IGNORABLE_F = 0x80; /** enum_field_types */ public static final int MYSQL_TYPE_DECIMAL = 0; public static final int MYSQL_TYPE_TINY = 1; public static final int MYSQL_TYPE_SHORT = 2; public static final int MYSQL_TYPE_LONG = 3; public static final int MYSQL_TYPE_FLOAT = 4; public static final int MYSQL_TYPE_DOUBLE = 5; public static final int MYSQL_TYPE_NULL = 6; public static final int MYSQL_TYPE_TIMESTAMP = 7; public static final int MYSQL_TYPE_LONGLONG = 8; public static final int MYSQL_TYPE_INT24 = 9; public static final int MYSQL_TYPE_DATE = 10; public static final int MYSQL_TYPE_TIME = 11; public static final int MYSQL_TYPE_DATETIME = 12; public static final int MYSQL_TYPE_YEAR = 13; public static final int MYSQL_TYPE_NEWDATE = 14; public static final int MYSQL_TYPE_VARCHAR = 15; public static final int MYSQL_TYPE_BIT = 16; public static final int MYSQL_TYPE_TIMESTAMP2 = 17; public static final int MYSQL_TYPE_DATETIME2 = 18; public static final int MYSQL_TYPE_TIME2 = 19; public static final int MYSQL_TYPE_TYPED_ARRAY = 20; public static final int MYSQL_TYPE_INVALID = 243; public static final int MYSQL_TYPE_BOOL = 244; public static final int MYSQL_TYPE_JSON = 245; public static final int MYSQL_TYPE_NEWDECIMAL = 246; public static final int MYSQL_TYPE_ENUM = 247; public static final int MYSQL_TYPE_SET = 248; public static final int MYSQL_TYPE_TINY_BLOB = 249; public static final int MYSQL_TYPE_MEDIUM_BLOB = 250; public static final int MYSQL_TYPE_LONG_BLOB = 251; public static final int MYSQL_TYPE_BLOB = 252; public static final int MYSQL_TYPE_VAR_STRING = 253; public static final int MYSQL_TYPE_STRING = 254; public static final int MYSQL_TYPE_GEOMETRY = 255; public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "Rotate"; case INTVAR_EVENT: return "Intvar"; case LOAD_EVENT: return "Load"; case NEW_LOAD_EVENT: return "New_load"; case SLAVE_EVENT: return "Slave"; case CREATE_FILE_EVENT: return "Create_file"; case APPEND_BLOCK_EVENT: return "Append_block"; case DELETE_FILE_EVENT: return "Delete_file"; case EXEC_LOAD_EVENT: return "Exec_load"; case RAND_EVENT: return "RAND"; case XID_EVENT: return "Xid"; case USER_VAR_EVENT: return "User var"; case FORMAT_DESCRIPTION_EVENT: return "Format_desc"; case TABLE_MAP_EVENT: return "Table_map"; case PRE_GA_WRITE_ROWS_EVENT: return "Write_rows_event_old"; case PRE_GA_UPDATE_ROWS_EVENT: return "Update_rows_event_old"; case PRE_GA_DELETE_ROWS_EVENT: return "Delete_rows_event_old"; case WRITE_ROWS_EVENT_V1: return "Write_rows_v1"; case UPDATE_ROWS_EVENT_V1: return "Update_rows_v1"; case DELETE_ROWS_EVENT_V1: return "Delete_rows_v1"; case BEGIN_LOAD_QUERY_EVENT: return "Begin_load_query"; case EXECUTE_LOAD_QUERY_EVENT: return "Execute_load_query"; case INCIDENT_EVENT: return "Incident"; case HEARTBEAT_LOG_EVENT: case HEARTBEAT_LOG_EVENT_V2: return "Heartbeat"; case IGNORABLE_LOG_EVENT: return "Ignorable"; case ROWS_QUERY_LOG_EVENT: return "Rows_query"; case WRITE_ROWS_EVENT: return "Write_rows"; case UPDATE_ROWS_EVENT: return "Update_rows"; case DELETE_ROWS_EVENT: return "Delete_rows"; case GTID_LOG_EVENT: return "Gtid"; case ANONYMOUS_GTID_LOG_EVENT: return "Anonymous_Gtid"; case PREVIOUS_GTIDS_LOG_EVENT: return "Previous_gtids"; case PARTIAL_UPDATE_ROWS_EVENT: return "Update_rows_partial"; case TRANSACTION_CONTEXT_EVENT : return "Transaction_context"; case VIEW_CHANGE_EVENT : return "view_change"; case XA_PREPARE_LOG_EVENT : return "Xa_prepare"; case TRANSACTION_PAYLOAD_EVENT : return "transaction_payload"; default: return "Unknown type:" + type; } } protected static final Log logger = LogFactory.getLog(LogEvent.class); protected final LogHeader header; /** * mysql半同步semi标识 * * <pre> * 0不需要semi ack 给mysql * 1需要semi ack给mysql * </pre> */ protected int semival; public int getSemival() { return semival; } public void setSemival(int semival) { this.semival = semival; } protected LogEvent(LogHeader header){ this.header = header; } /** * Return event header. */ public final LogHeader getHeader() { return header; } /** * The total size of this event, in bytes. In other words, this is the sum * of the sizes of Common-Header, Post-Header, and Body. */ public final int getEventLen() { return header.getEventLen(); } /** * Server ID of the server that created the event. */ public final long getServerId() { return header.getServerId(); } /** * The position of the next event in the master binary log, in bytes from * the beginning of the file. In a binlog that is not a relay log, this is * just the position of the next event, in bytes from the beginning of the * file. In a relay log, this is the position of the next event in the * master's binlog. */ public final long getLogPos() { return header.getLogPos(); } /** * The time when the query started, in seconds since 1970. */ public final long getWhen() { return header.getWhen(); } }
alibaba/canal
dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/LogEvent.java
1,130
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import org.jeecg.common.constant.enums.DySmsEnum; import org.jeecg.config.StaticConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created on 17/6/7. * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) * 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar * 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 * 国际短信发送请勿参照此DEMO * @author: jeecg-boot */ public class DySmsHelper { private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class); /**产品名称:云通信短信API产品,开发者无需替换*/ static final String PRODUCT = "Dysmsapi"; /**产品域名,开发者无需替换*/ static final String DOMAIN = "dysmsapi.aliyuncs.com"; /**TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)*/ static String accessKeyId; static String accessKeySecret; public static void setAccessKeyId(String accessKeyId) { DySmsHelper.accessKeyId = accessKeyId; } public static void setAccessKeySecret(String accessKeySecret) { DySmsHelper.accessKeySecret = accessKeySecret; } public static String getAccessKeyId() { return accessKeyId; } public static String getAccessKeySecret() { return accessKeySecret; } public static boolean sendSms(String phone, JSONObject templateParamJson, DySmsEnum dySmsEnum) throws ClientException { //可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //update-begin-author:taoyan date:20200811 for:配置类数据获取 StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class); //logger.info("阿里大鱼短信秘钥 accessKeyId:" + staticConfig.getAccessKeyId()); //logger.info("阿里大鱼短信秘钥 accessKeySecret:"+ staticConfig.getAccessKeySecret()); setAccessKeyId(staticConfig.getAccessKeyId()); setAccessKeySecret(staticConfig.getAccessKeySecret()); //update-end-author:taoyan date:20200811 for:配置类数据获取 //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN); IAcsClient acsClient = new DefaultAcsClient(profile); //验证json参数 validateParam(templateParamJson,dySmsEnum); //组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); //必填:待发送手机号 request.setPhoneNumbers(phone); //必填:短信签名-可在短信控制台中找到 request.setSignName(dySmsEnum.getSignName()); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode(dySmsEnum.getTemplateCode()); //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(templateParamJson.toJSONString()); //选填-上行短信扩展码(无特殊需求用户请忽略此字段) //request.setSmsUpExtendCode("90997"); //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 //request.setOutId("yourOutId"); boolean result = false; //hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); logger.info("短信接口返回的数据----------------"); logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}"); String ok = "OK"; if (ok.equals(sendSmsResponse.getCode())) { result = true; } return result; } private static void validateParam(JSONObject templateParamJson,DySmsEnum dySmsEnum) { String keys = dySmsEnum.getKeys(); String [] keyArr = keys.split(","); for(String item :keyArr) { if(!templateParamJson.containsKey(item)) { throw new RuntimeException("模板缺少参数:"+item); } } } // public static void main(String[] args) throws ClientException, InterruptedException { // JSONObject obj = new JSONObject(); // obj.put("code", "1234"); // sendSms("13800138000", obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE); // } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsHelper.java
1,131
package net.dubboclub.catmonitor; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.TimeoutException; import com.alibaba.dubbo.rpc.*; import com.alibaba.dubbo.rpc.support.RpcUtils; import com.dianping.cat.Cat; import com.dianping.cat.log.CatLogger; import com.dianping.cat.message.Event; import com.dianping.cat.message.Message; import com.dianping.cat.message.Transaction; import net.dubboclub.catmonitor.constants.CatConstants; import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.Map; /** * Created by bieber on 2015/11/4. */ @Activate(group = {Constants.PROVIDER, Constants.CONSUMER},order = -9000) public class CatTransaction implements Filter { private final static String DUBBO_BIZ_ERROR="DUBBO_BIZ_ERROR"; private final static String DUBBO_TIMEOUT_ERROR="DUBBO_TIMEOUT_ERROR"; private final static String DUBBO_REMOTING_ERROR="DUBBO_REMOTING_ERROR"; private static final ThreadLocal<Cat.Context> CAT_CONTEXT = new ThreadLocal<Cat.Context>(); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if(!DubboCat.isEnable()){ Result result = invoker.invoke(invocation); return result; } URL url = invoker.getUrl(); String sideKey = url.getParameter(Constants.SIDE_KEY); String loggerName = invoker.getInterface().getSimpleName()+"."+invocation.getMethodName(); String type = CatConstants.CROSS_CONSUMER; if(Constants.PROVIDER_SIDE.equals(sideKey)){ type= CatConstants.CROSS_SERVER; } boolean init = false; Transaction transaction = null; try{ transaction = Cat.newTransaction(type, loggerName); Cat.Context context = getContext(); if(Constants.CONSUMER_SIDE.equals(sideKey)){ createConsumerCross(url,transaction); Cat.logRemoteCallClient(context); }else{ createProviderCross(url,transaction); Cat.logRemoteCallServer(context); } setAttachment(context); init = true; } catch (Exception e) { CatLogger.getInstance().error("[DUBBO] DubboCat init error.", e); } Result result=null; try{ result = invoker.invoke(invocation); if (!init) { return result; } boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation); //异步的不能判断是否有异常,这样会阻塞住接口(<AsyncRpcResult>hasException->getRpcResult->resultFuture.get() if (isAsync) { transaction.setStatus(Message.SUCCESS); return result; } if(result.hasException()){ //给调用接口出现异常进行打点 Throwable throwable = result.getException(); Event event = null; if(RpcException.class==throwable.getClass()){ Throwable caseBy = throwable.getCause(); if(caseBy!=null&&caseBy.getClass()==TimeoutException.class){ event = Cat.newEvent(DUBBO_TIMEOUT_ERROR,loggerName); }else{ event = Cat.newEvent(DUBBO_REMOTING_ERROR,loggerName); } }else if(RemotingException.class.isAssignableFrom(throwable.getClass())){ event = Cat.newEvent(DUBBO_REMOTING_ERROR,loggerName); }else{ event = Cat.newEvent(DUBBO_BIZ_ERROR,loggerName); } event.setStatus(result.getException()); completeEvent(event); transaction.addChild(event); transaction.setStatus(result.getException().getClass().getSimpleName()); }else{ transaction.setStatus(Message.SUCCESS); } return result; }catch (RuntimeException e){ if (init) { Cat.logError(e); Event event; if (RpcException.class == e.getClass()) { Throwable caseBy = e.getCause(); if (caseBy != null && caseBy.getClass() == TimeoutException.class) { event = Cat.newEvent(DUBBO_TIMEOUT_ERROR, loggerName); } else { event = Cat.newEvent(DUBBO_REMOTING_ERROR, loggerName); } } else { event = Cat.newEvent(DUBBO_BIZ_ERROR, loggerName); } event.setStatus(e); completeEvent(event); transaction.addChild(event); transaction.setStatus(e.getClass().getSimpleName()); } if(result==null){ throw e; }else{ return result; } }finally { if (transaction != null) { transaction.complete(); } CAT_CONTEXT.remove(); } } static class DubboCatContext implements Cat.Context{ private Map<String,String> properties = new HashMap<String, String>(); @Override public void addProperty(String key, String value) { properties.put(key,value); } @Override public String getProperty(String key) { return properties.get(key); } } private String getProviderAppName(URL url){ String appName = url.getParameter(CatConstants.PROVIDER_APPLICATION_NAME); if(StringUtils.isEmpty(appName)){ String interfaceName = url.getParameter(Constants.INTERFACE_KEY); appName = interfaceName.substring(0,interfaceName.lastIndexOf('.')); } return appName; } private void setAttachment(Cat.Context context){ RpcContext.getContext().setAttachment(Cat.Context.ROOT,context.getProperty(Cat.Context.ROOT)); RpcContext.getContext().setAttachment(Cat.Context.CHILD,context.getProperty(Cat.Context.CHILD)); RpcContext.getContext().setAttachment(Cat.Context.PARENT,context.getProperty(Cat.Context.PARENT)); } private Cat.Context getContext(){ Cat.Context context = CAT_CONTEXT.get(); if(context==null){ context = initContext(); CAT_CONTEXT.set(context); } return context; } private Cat.Context initContext(){ Cat.Context context = new DubboCatContext(); Map<String,String> attachments = RpcContext.getContext().getAttachments(); if(attachments!=null&&attachments.size()>0){ for(Map.Entry<String,String> entry:attachments.entrySet()){ if(Cat.Context.CHILD.equals(entry.getKey())||Cat.Context.ROOT.equals(entry.getKey())||Cat.Context.PARENT.equals(entry.getKey())){ context.addProperty(entry.getKey(),entry.getValue()); } } } return context; } private void createConsumerCross(URL url,Transaction transaction){ Event crossAppEvent = Cat.newEvent(CatConstants.CONSUMER_CALL_APP,getProviderAppName(url)); Event crossServerEvent = Cat.newEvent(CatConstants.CONSUMER_CALL_SERVER,url.getHost()); Event crossPortEvent = Cat.newEvent(CatConstants.CONSUMER_CALL_PORT,url.getPort()+""); crossAppEvent.setStatus(Event.SUCCESS); crossServerEvent.setStatus(Event.SUCCESS); crossPortEvent.setStatus(Event.SUCCESS); completeEvent(crossAppEvent); completeEvent(crossPortEvent); completeEvent(crossServerEvent); transaction.addChild(crossAppEvent); transaction.addChild(crossPortEvent); transaction.addChild(crossServerEvent); } private void completeEvent(Event event){ event.complete(); } private void createProviderCross(URL url,Transaction transaction){ String consumerAppName = RpcContext.getContext().getAttachment(Constants.APPLICATION_KEY); if(StringUtils.isEmpty(consumerAppName)){ consumerAppName= RpcContext.getContext().getRemoteHost()+":"+ RpcContext.getContext().getRemotePort(); } Event crossAppEvent = Cat.newEvent(CatConstants.PROVIDER_CALL_APP,consumerAppName); Event crossServerEvent = Cat.newEvent(CatConstants.PROVIDER_CALL_SERVER, RpcContext.getContext().getRemoteHost()); crossAppEvent.setStatus(Event.SUCCESS); crossServerEvent.setStatus(Event.SUCCESS); completeEvent(crossAppEvent); completeEvent(crossServerEvent); transaction.addChild(crossAppEvent); transaction.addChild(crossServerEvent); } }
dianping/cat
integration/dubbo/src/main/java/net/dubboclub/catmonitor/CatTransaction.java
1,133
package com.scwang.refreshlayout.util; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.os.Build; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import androidx.annotation.FloatRange; import androidx.annotation.RequiresApi; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * 状态栏透明 * Created by scwang on 2016/10/26. */ @SuppressWarnings("unused") public class StatusBarUtil { public static int DEFAULT_COLOR = 0; public static float DEFAULT_ALPHA = 0;//Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 0.2f : 0.3f; public static final int MIN_API = 19; //<editor-fold desc="沉侵"> public static void immersive(Activity activity) { immersive(activity, DEFAULT_COLOR, DEFAULT_ALPHA); } public static void immersive(Activity activity, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { immersive(activity.getWindow(), color, alpha); } public static void immersive(Activity activity, int color) { immersive(activity.getWindow(), color, 1f); } public static void immersive(Window window) { immersive(window, DEFAULT_COLOR, DEFAULT_ALPHA); } public static void immersive(Window window, int color) { immersive(window, color, 1f); } public static void immersive(Window window, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(mixtureColor(color, alpha)); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } public static void color(Activity activity, int color) { Window window = activity.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(color); } //</editor-fold> //<editor-fold desc="DarkMode"> public static void darkMode(Activity activity, boolean dark) { if (isFlyMe4Later()) { darkModeForFlyMe4(activity.getWindow(), dark); } else if (isMIUI6Later()) { darkModeForMIUI6(activity.getWindow(), dark); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { darkModeForM(activity.getWindow(), dark); } } public static void darkModeCancel(Activity activity) { Window window = activity.getWindow(); if (isFlyMe4Later()) { darkModeForFlyMe4(window, false); } else if (isMIUI6Later()) { darkModeForMIUI6(window, false); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { darkModeForM(window, false); } } /** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void darkMode(Activity activity) { darkMode(activity.getWindow(), DEFAULT_COLOR, DEFAULT_ALPHA); } public static void darkMode(Activity activity, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { darkMode(activity.getWindow(), color, alpha); } public static void darkOnly(Activity activity) { Window window = activity.getWindow(); if (isFlyMe4Later()) { darkModeForFlyMe4(window, true); } else if (isMIUI6Later()) { darkModeForMIUI6(window, true); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { darkModeForM(window, true); } } /** 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void darkMode(Window window, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (isFlyMe4Later()) { darkModeForFlyMe4(window, true); immersive(window,color,alpha); } else if (isMIUI6Later()) { darkModeForMIUI6(window, true); immersive(window,color,alpha); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { darkModeForM(window, true); immersive(window, color, alpha); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); setTranslucentView((ViewGroup) window.getDecorView(), color, alpha); } // if (Build.VERSION.SDK_INT >= 21) { // window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // window.setStatusBarColor(Color.TRANSPARENT); // } else if (Build.VERSION.SDK_INT >= 19) { // window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // } // setTranslucentView((ViewGroup) window.getDecorView(), color, alpha); } //-------------------------> /** android 6.0设置字体颜色 */ @RequiresApi(Build.VERSION_CODES.M) private static void darkModeForM(Window window, boolean dark) { // window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // window.setStatusBarColor(Color.TRANSPARENT); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); if (dark) { systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else { systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } window.getDecorView().setSystemUiVisibility(systemUiVisibility); } /** * 设置Flyme4+的darkMode,darkMode时候字体颜色及icon变黑 * <a href="http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI">...</a> */ public static boolean darkModeForFlyMe4(Window window, boolean dark) { boolean result = false; if (window != null) { try { WindowManager.LayoutParams e = window.getAttributes(); Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON"); Field flyMeFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags"); darkFlag.setAccessible(true); flyMeFlags.setAccessible(true); int bit = darkFlag.getInt(null); int value = flyMeFlags.getInt(e); if (dark) { value |= bit; } else { value &= ~bit; } flyMeFlags.setInt(e, value); window.setAttributes(e); result = true; } catch (Exception var8) { Log.e("StatusBar", "darkIcon: failed"); } } return result; } /** * 设置MIUI6+的状态栏是否为darkMode,darkMode时候字体颜色及icon变黑 * <a href="http://dev.xiaomi.com/doc/p=4769/">...</a> */ public static boolean darkModeForMIUI6(Window window, boolean dark) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { darkModeForM(window, dark); } Class<? extends Window> clazz = window.getClass(); try { int darkModeFlag = 0; Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(window, dark ? darkModeFlag : 0, darkModeFlag); return true; } catch (Throwable e) { e.printStackTrace(); return false; } } /** 判断是否Flyme4以上 */ public static boolean isFlyMe4Later() { return Build.FINGERPRINT.contains("Flyme_OS_4") || Build.VERSION.INCREMENTAL.contains("Flyme_OS_4") || Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find(); } /** 判断是否为MIUI6以上 */ public static boolean isMIUI6Later() { try { Class<?> clz = Class.forName("android.os.SystemProperties"); Method mtd = clz.getMethod("get", String.class); String val = (String) mtd.invoke(null, "ro.miui.ui.version.name"); assert val != null; val = val.replaceAll("[vV]", ""); int version = Integer.parseInt(val); return version >= 6; } catch (Throwable e) { return false; } } //</editor-fold> /** 增加View的paddingTop,增加的值为状态栏高度 */ public static void setPadding(Context context, View view) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } /** 增加View的paddingTop,增加的值为状态栏高度 (智能判断,并设置高度)*/ public static void setPaddingSmart(Context context, View view) { ViewGroup.LayoutParams lp = view.getLayoutParams(); if (lp != null && lp.height > 0) { lp.height += getStatusBarHeight(context);//增高 } view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } /** 增加View的高度以及paddingTop,增加的值为状态栏高度.一般是在沉浸式全屏给ToolBar用的 */ public static void setHeightAndPadding(Context context, View view) { ViewGroup.LayoutParams lp = view.getLayoutParams(); lp.height += getStatusBarHeight(context);//增高 view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } /** 增加View上边距(MarginTop)一般是给高度为 WARP_CONTENT 的小控件用的*/ public static void setMargin(Context context, View view) { ViewGroup.LayoutParams lp = view.getLayoutParams(); if (lp instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams) lp).topMargin += getStatusBarHeight(context);//增高 } view.setLayoutParams(lp); } /** * 创建假的透明栏 */ public static void setTranslucentView(ViewGroup container, int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { int mixtureColor = mixtureColor(color, alpha); View translucentView = container.findViewById(android.R.id.custom); if (translucentView == null && mixtureColor != 0) { translucentView = new View(container.getContext()); translucentView.setId(android.R.id.custom); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext())); container.addView(translucentView, lp); } if (translucentView != null) { translucentView.setBackgroundColor(mixtureColor); } } public static int mixtureColor(int color, @FloatRange(from = 0.0, to = 1.0) float alpha) { int a = (color & 0xff000000) == 0 ? 0xff : color >>> 24; return (color & 0x00ffffff) | (((int) (a * alpha)) << 24); } /** 获取状态栏高度 */ public static int getStatusBarHeight(Context context) { int result = 24; int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { result = context.getResources().getDimensionPixelSize(resId); } else { result = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, result, Resources.getSystem().getDisplayMetrics()); } return result; } }
scwang90/SmartRefreshLayout
app/src/main/java/com/scwang/refreshlayout/util/StatusBarUtil.java
1,134
package com.macro.mall.service; import com.macro.mall.model.UmsMenu; import com.macro.mall.model.UmsResource; import com.macro.mall.model.UmsRole; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 后台角色管理Service * Created by macro on 2018/9/30. */ public interface UmsRoleService { /** * 添加角色 */ int create(UmsRole role); /** * 修改角色信息 */ int update(Long id, UmsRole role); /** * 批量删除角色 */ int delete(List<Long> ids); /** * 获取所有角色列表 */ List<UmsRole> list(); /** * 分页获取角色列表 */ List<UmsRole> list(String keyword, Integer pageSize, Integer pageNum); /** * 根据管理员ID获取对应菜单 */ List<UmsMenu> getMenuList(Long adminId); /** * 获取角色相关菜单 */ List<UmsMenu> listMenu(Long roleId); /** * 获取角色相关资源 */ List<UmsResource> listResource(Long roleId); /** * 给角色分配菜单 */ @Transactional int allocMenu(Long roleId, List<Long> menuIds); /** * 给角色分配资源 */ @Transactional int allocResource(Long roleId, List<Long> resourceIds); }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/UmsRoleService.java
1,137
/* * Copyright 2016 jeasonlzy(廖子尧) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lzy.okgo.db; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Pair; import com.lzy.okgo.utils.OkLogger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public abstract class BaseDao<T> { protected static String TAG; protected Lock lock; protected SQLiteOpenHelper helper; protected SQLiteDatabase database; public BaseDao(SQLiteOpenHelper helper) { TAG = getClass().getSimpleName(); lock = DBHelper.lock; this.helper = helper; this.database = openWriter(); } public SQLiteDatabase openReader() { return helper.getReadableDatabase(); } public SQLiteDatabase openWriter() { return helper.getWritableDatabase(); } protected final void closeDatabase(SQLiteDatabase database, Cursor cursor) { if (cursor != null && !cursor.isClosed()) cursor.close(); if (database != null && database.isOpen()) database.close(); } /** 插入一条记录 */ public boolean insert(T t) { if (t == null) return false; long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.insert(getTableName(), null, getContentValues(t)); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " insertT"); } return false; } /** 插入一条记录 */ public long insert(SQLiteDatabase database, T t) { return database.insert(getTableName(), null, getContentValues(t)); } /** 插入多条记录 */ public boolean insert(List<T> ts) { if (ts == null) return false; long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); for (T t : ts) { database.insert(getTableName(), null, getContentValues(t)); } database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " insertList"); } return false; } public boolean insert(SQLiteDatabase database, List<T> ts) { try { for (T t : ts) { database.insert(getTableName(), null, getContentValues(t)); } return true; } catch (Exception e) { OkLogger.printStackTrace(e); return false; } } /** 删除所有数据 */ public boolean deleteAll() { return delete(null, null); } /** 删除所有数据 */ public long deleteAll(SQLiteDatabase database) { return delete(database, null, null); } /** 根据条件删除数据库中的数据 */ public boolean delete(String whereClause, String[] whereArgs) { long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.delete(getTableName(), whereClause, whereArgs); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " delete"); } return false; } /** 根据条件删除数据库中的数据 */ public long delete(SQLiteDatabase database, String whereClause, String[] whereArgs) { return database.delete(getTableName(), whereClause, whereArgs); } public boolean deleteList(List<Pair<String, String[]>> where) { long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); for (Pair<String, String[]> pair : where) { database.delete(getTableName(), pair.first, pair.second); } database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " deleteList"); } return false; } /** * replace 语句有如下行为特点 * 1. replace语句会删除原有的一条记录, 并且插入一条新的记录来替换原记录。 * 2. 一般用replace语句替换一条记录的所有列, 如果在replace语句中没有指定某列, 在replace之后这列的值被置空 。 * 3. replace语句根据主键的值确定被替换的是哪一条记录 * 4. 如果执行replace语句时, 不存在要替换的记录, 那么就会插入一条新的记录。 * 5. replace语句不能根据where子句来定位要被替换的记录 * 6. 如果新插入的或替换的记录中, 有字段和表中的其他记录冲突, 那么会删除那条其他记录。 */ public boolean replace(T t) { if (t == null) return false; long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.replace(getTableName(), null, getContentValues(t)); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " replaceT"); } return false; } public long replace(SQLiteDatabase database, T t) { return database.replace(getTableName(), null, getContentValues(t)); } public boolean replace(ContentValues contentValues) { long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.replace(getTableName(), null, contentValues); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " replaceContentValues"); } return false; } public long replace(SQLiteDatabase database, ContentValues contentValues) { return database.replace(getTableName(), null, contentValues); } public boolean replace(List<T> ts) { if (ts == null) return false; long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); for (T t : ts) { database.replace(getTableName(), null, getContentValues(t)); } database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " replaceList"); } return false; } public boolean replace(SQLiteDatabase database, List<T> ts) { try { for (T t : ts) { database.replace(getTableName(), null, getContentValues(t)); } return true; } catch (Exception e) { OkLogger.printStackTrace(e); return false; } } /** 更新一条记录 */ public boolean update(T t, String whereClause, String[] whereArgs) { if (t == null) return false; long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.update(getTableName(), getContentValues(t), whereClause, whereArgs); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " updateT"); } return false; } /** 更新一条记录 */ public long update(SQLiteDatabase database, T t, String whereClause, String[] whereArgs) { return database.update(getTableName(), getContentValues(t), whereClause, whereArgs); } /** 更新一条记录 */ public boolean update(ContentValues contentValues, String whereClause, String[] whereArgs) { long start = System.currentTimeMillis(); lock.lock(); try { database.beginTransaction(); database.update(getTableName(), contentValues, whereClause, whereArgs); database.setTransactionSuccessful(); return true; } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " updateContentValues"); } return false; } /** 更新一条记录 */ public long update(SQLiteDatabase database, ContentValues contentValues, String whereClause, String[] whereArgs) { return database.update(getTableName(), contentValues, whereClause, whereArgs); } /** 查询并返回所有对象的集合 */ public List<T> queryAll(SQLiteDatabase database) { return query(database, null, null); } /** 按条件查询对象并返回集合 */ public List<T> query(SQLiteDatabase database, String selection, String[] selectionArgs) { return query(database, null, selection, selectionArgs, null, null, null, null); } /** 查询满足条件的一个结果 */ public T queryOne(SQLiteDatabase database, String selection, String[] selectionArgs) { List<T> query = query(database, null, selection, selectionArgs, null, null, null, "1"); if (query.size() > 0) return query.get(0); return null; } /** 按条件查询对象并返回集合 */ public List<T> query(SQLiteDatabase database, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { List<T> list = new ArrayList<>(); Cursor cursor = null; try { cursor = database.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy, limit); while (!cursor.isClosed() && cursor.moveToNext()) { list.add(parseCursorToBean(cursor)); } } catch (Exception e) { OkLogger.printStackTrace(e); } finally { closeDatabase(null, cursor); } return list; } /** 查询并返回所有对象的集合 */ public List<T> queryAll() { return query(null, null); } /** 按条件查询对象并返回集合 */ public List<T> query(String selection, String[] selectionArgs) { return query(null, selection, selectionArgs, null, null, null, null); } /** 查询满足条件的一个结果 */ public T queryOne(String selection, String[] selectionArgs) { long start = System.currentTimeMillis(); List<T> query = query(null, selection, selectionArgs, null, null, null, "1"); OkLogger.v(TAG, System.currentTimeMillis() - start + " queryOne"); return query.size() > 0 ? query.get(0) : null; } /** 按条件查询对象并返回集合 */ public List<T> query(String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { long start = System.currentTimeMillis(); lock.lock(); List<T> list = new ArrayList<>(); Cursor cursor = null; try { database.beginTransaction(); cursor = database.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy, limit); while (!cursor.isClosed() && cursor.moveToNext()) { list.add(parseCursorToBean(cursor)); } database.setTransactionSuccessful(); } catch (Exception e) { OkLogger.printStackTrace(e); } finally { closeDatabase(null, cursor); database.endTransaction(); lock.unlock(); OkLogger.v(TAG, System.currentTimeMillis() - start + " query"); } return list; } public interface Action { void call(SQLiteDatabase database); } /** 用于给外界提供事物开启的模板 */ public void startTransaction(Action action) { lock.lock(); try { database.beginTransaction(); action.call(database); database.setTransactionSuccessful(); } catch (Exception e) { OkLogger.printStackTrace(e); } finally { database.endTransaction(); lock.unlock(); } } /** 获取对应的表名 */ public abstract String getTableName(); public abstract void unInit(); /** 将Cursor解析成对应的JavaBean */ public abstract T parseCursorToBean(Cursor cursor); /** 需要替换的列 */ public abstract ContentValues getContentValues(T t); }
jeasonlzy/okhttp-OkGo
okgo/src/main/java/com/lzy/okgo/db/BaseDao.java
1,138
package decaf.translate; import java.util.Stack; import decaf.tree.Tree; import decaf.backend.OffsetCounter; import decaf.machdesc.Intrinsic; import decaf.symbol.Variable; import decaf.tac.Label; import decaf.tac.Temp; import decaf.type.BaseType; public class TransPass2 extends Tree.Visitor { private Translater tr; private Temp currentThis; private Stack<Label> loopExits; public TransPass2(Translater tr) { this.tr = tr; loopExits = new Stack<Label>(); } @Override public void visitClassDef(Tree.ClassDef classDef) { for (Tree f : classDef.fields) { f.accept(this); } } @Override public void visitMethodDef(Tree.MethodDef funcDefn) { if (!funcDefn.statik) { currentThis = ((Variable) funcDefn.symbol.getAssociatedScope() .lookup("this")).getTemp(); } tr.beginFunc(funcDefn.symbol); funcDefn.body.accept(this); tr.endFunc(); currentThis = null; } @Override public void visitTopLevel(Tree.TopLevel program) { for (Tree.ClassDef cd : program.classes) { cd.accept(this); } } @Override public void visitVarDef(Tree.VarDef varDef) { if (varDef.symbol.isLocalVar()) { Temp t = Temp.createTempI4(); t.sym = varDef.symbol; varDef.symbol.setTemp(t); } } @Override public void visitBinary(Tree.Binary expr) { expr.left.accept(this); expr.right.accept(this); switch (expr.tag) { case Tree.PLUS: expr.val = tr.genAdd(expr.left.val, expr.right.val); break; case Tree.MINUS: expr.val = tr.genSub(expr.left.val, expr.right.val); break; case Tree.MUL: expr.val = tr.genMul(expr.left.val, expr.right.val); break; case Tree.DIV: expr.val = tr.genDiv(expr.left.val, expr.right.val); break; case Tree.MOD: expr.val = tr.genMod(expr.left.val, expr.right.val); break; case Tree.AND: expr.val = tr.genLAnd(expr.left.val, expr.right.val); break; case Tree.OR: expr.val = tr.genLOr(expr.left.val, expr.right.val); break; case Tree.LT: expr.val = tr.genLes(expr.left.val, expr.right.val); break; case Tree.LE: expr.val = tr.genLeq(expr.left.val, expr.right.val); break; case Tree.GT: expr.val = tr.genGtr(expr.left.val, expr.right.val); break; case Tree.GE: expr.val = tr.genGeq(expr.left.val, expr.right.val); break; case Tree.EQ: case Tree.NE: genEquNeq(expr); break; } } private void genEquNeq(Tree.Binary expr) { if (expr.left.type.equal(BaseType.STRING) || expr.right.type.equal(BaseType.STRING)) { tr.genParm(expr.left.val); tr.genParm(expr.right.val); expr.val = tr.genDirectCall(Intrinsic.STRING_EQUAL.label, BaseType.BOOL); if(expr.tag == Tree.NE){ expr.val = tr.genLNot(expr.val); } } else { if(expr.tag == Tree.EQ) expr.val = tr.genEqu(expr.left.val, expr.right.val); else expr.val = tr.genNeq(expr.left.val, expr.right.val); } } @Override public void visitAssign(Tree.Assign assign) { assign.left.accept(this); assign.expr.accept(this); switch (assign.left.lvKind) { case ARRAY_ELEMENT: Tree.Indexed arrayRef = (Tree.Indexed) assign.left; Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(arrayRef.index.val, esz); Temp base = tr.genAdd(arrayRef.array.val, t); tr.genStore(assign.expr.val, base, 0); break; case MEMBER_VAR: Tree.Ident varRef = (Tree.Ident) assign.left; tr.genStore(assign.expr.val, varRef.owner.val, varRef.symbol .getOffset()); break; case PARAM_VAR: case LOCAL_VAR: tr.genAssign(((Tree.Ident) assign.left).symbol.getTemp(), assign.expr.val); break; } } @Override public void visitLiteral(Tree.Literal literal) { switch (literal.typeTag) { case Tree.INT: literal.val = tr.genLoadImm4(((Integer)literal.value).intValue()); break; case Tree.BOOL: literal.val = tr.genLoadImm4((Boolean)(literal.value) ? 1 : 0); break; default: literal.val = tr.genLoadStrConst((String)literal.value); } } @Override public void visitExec(Tree.Exec exec) { exec.expr.accept(this); } @Override public void visitUnary(Tree.Unary expr) { expr.expr.accept(this); switch (expr.tag){ case Tree.NEG: expr.val = tr.genNeg(expr.expr.val); break; case Tree.NOT: expr.val = tr.genLNot(expr.expr.val); break; case Tree.POSTINC: //后++ expr.val = tr.genAdd(expr.expr.val, tr.genLoadImm4(0)); Temp realAns = tr.genAdd(expr.expr.val, tr.genLoadImm4(1)); expr.expr.accept(this); switch (((Tree.LValue)expr.expr).lvKind) { case ARRAY_ELEMENT: Tree.Indexed arrayRef = (Tree.Indexed) expr.expr; Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(arrayRef.index.val, esz); Temp base = tr.genAdd(arrayRef.array.val, t); tr.genStore(realAns, base, 0); break; case MEMBER_VAR: Tree.Ident varRef = (Tree.Ident) expr.expr; tr.genStore(realAns, varRef.owner.val, varRef.symbol .getOffset()); break; case PARAM_VAR: case LOCAL_VAR: tr.genAssign(((Tree.Ident) expr.expr).symbol.getTemp(), realAns); break; } break; case Tree.PREINC: // 前++ expr.val = tr.genAdd(expr.expr.val, tr.genLoadImm4(1)); Temp realAns2 = tr.genAdd(expr.expr.val, tr.genLoadImm4(1)); expr.expr.accept(this); switch (((Tree.LValue)expr.expr).lvKind) { case ARRAY_ELEMENT: Tree.Indexed arrayRef = (Tree.Indexed) expr.expr; Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(arrayRef.index.val, esz); Temp base = tr.genAdd(arrayRef.array.val, t); tr.genStore(realAns2, base, 0); break; case MEMBER_VAR: Tree.Ident varRef = (Tree.Ident) expr.expr; tr.genStore(realAns2, varRef.owner.val, varRef.symbol .getOffset()); break; case PARAM_VAR: case LOCAL_VAR: tr.genAssign(((Tree.Ident) expr.expr).symbol.getTemp(), realAns2); break; } break; case Tree.POSTDEC: //后-- expr.val = tr.genSub(expr.expr.val, tr.genLoadImm4(0)); Temp realAns3 = tr.genSub(expr.expr.val, tr.genLoadImm4(1)); expr.expr.accept(this); switch (((Tree.LValue)expr.expr).lvKind) { case ARRAY_ELEMENT: Tree.Indexed arrayRef = (Tree.Indexed) expr.expr; Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(arrayRef.index.val, esz); Temp base = tr.genAdd(arrayRef.array.val, t); tr.genStore(realAns3, base, 0); break; case MEMBER_VAR: Tree.Ident varRef = (Tree.Ident) expr.expr; tr.genStore(realAns3, varRef.owner.val, varRef.symbol .getOffset()); break; case PARAM_VAR: case LOCAL_VAR: tr.genAssign(((Tree.Ident) expr.expr).symbol.getTemp(), realAns3); break; } break; case Tree.PREDEC: // 前-- expr.val = tr.genSub(expr.expr.val, tr.genLoadImm4(1)); Temp realAns4 = tr.genSub(expr.expr.val, tr.genLoadImm4(1)); expr.expr.accept(this); switch (((Tree.LValue)expr.expr).lvKind) { case ARRAY_ELEMENT: Tree.Indexed arrayRef = (Tree.Indexed) expr.expr; Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(arrayRef.index.val, esz); Temp base = tr.genAdd(arrayRef.array.val, t); tr.genStore(realAns4, base, 0); break; case MEMBER_VAR: Tree.Ident varRef = (Tree.Ident) expr.expr; tr.genStore(realAns4, varRef.owner.val, varRef.symbol .getOffset()); break; case PARAM_VAR: case LOCAL_VAR: tr.genAssign(((Tree.Ident) expr.expr).symbol.getTemp(), realAns4); break; } break; default: break; } } @Override public void visitNull(Tree.Null nullExpr) { nullExpr.val = tr.genLoadImm4(0); } @Override public void visitBlock(Tree.Block block) { for (Tree s : block.block) { s.accept(this); } } @Override public void visitThisExpr(Tree.ThisExpr thisExpr) { thisExpr.val = currentThis; } @Override public void visitReadIntExpr(Tree.ReadIntExpr readIntExpr) { readIntExpr.val = tr.genIntrinsicCall(Intrinsic.READ_INT); } @Override public void visitReadLineExpr(Tree.ReadLineExpr readStringExpr) { readStringExpr.val = tr.genIntrinsicCall(Intrinsic.READ_LINE); } @Override public void visitReturn(Tree.Return returnStmt) { if (returnStmt.expr != null) { returnStmt.expr.accept(this); tr.genReturn(returnStmt.expr.val); } else { tr.genReturn(null); } } @Override public void visitPrint(Tree.Print printStmt) { for (Tree.Expr r : printStmt.exprs) { r.accept(this); tr.genParm(r.val); if (r.type.equal(BaseType.BOOL)) { tr.genIntrinsicCall(Intrinsic.PRINT_BOOL); } else if (r.type.equal(BaseType.INT)) { tr.genIntrinsicCall(Intrinsic.PRINT_INT); } else if (r.type.equal(BaseType.STRING)) { tr.genIntrinsicCall(Intrinsic.PRINT_STRING); } } } @Override public void visitIndexed(Tree.Indexed indexed) { indexed.array.accept(this); indexed.index.accept(this); tr.genCheckArrayIndex(indexed.array.val, indexed.index.val); Temp esz = tr.genLoadImm4(OffsetCounter.WORD_SIZE); Temp t = tr.genMul(indexed.index.val, esz); Temp base = tr.genAdd(indexed.array.val, t); indexed.val = tr.genLoad(base, 0); } @Override public void visitIdent(Tree.Ident ident) { if(ident.lvKind == Tree.LValue.Kind.MEMBER_VAR){ ident.owner.accept(this); } switch (ident.lvKind) { case MEMBER_VAR: ident.val = tr.genLoad(ident.owner.val, ident.symbol.getOffset()); break; default: ident.val = ident.symbol.getTemp(); break; } } @Override public void visitBreak(Tree.Break breakStmt) { tr.genBranch(loopExits.peek()); } @Override public void visitCallExpr(Tree.CallExpr callExpr) { if (callExpr.isArrayLength) { callExpr.receiver.accept(this); callExpr.val = tr.genLoad(callExpr.receiver.val, -OffsetCounter.WORD_SIZE); } else { if (callExpr.receiver != null) { callExpr.receiver.accept(this); } for (Tree.Expr expr : callExpr.actuals) { expr.accept(this); } if (callExpr.receiver != null) { tr.genParm(callExpr.receiver.val); } for (Tree.Expr expr : callExpr.actuals) { tr.genParm(expr.val); } if (callExpr.receiver == null) { callExpr.val = tr.genDirectCall( callExpr.symbol.getFuncty().label, callExpr.symbol .getReturnType()); } else { Temp vt = tr.genLoad(callExpr.receiver.val, 0); Temp func = tr.genLoad(vt, callExpr.symbol.getOffset()); callExpr.val = tr.genIndirectCall(func, callExpr.symbol .getReturnType()); } } } @Override public void visitForLoop(Tree.ForLoop forLoop) { if (forLoop.init != null) { forLoop.init.accept(this); } Label cond = Label.createLabel(); Label loop = Label.createLabel(); tr.genBranch(cond); tr.genMark(loop); if (forLoop.update != null) { forLoop.update.accept(this); } tr.genMark(cond); forLoop.condition.accept(this); Label exit = Label.createLabel(); tr.genBeqz(forLoop.condition.val, exit); loopExits.push(exit); if (forLoop.loopBody != null) { forLoop.loopBody.accept(this); } tr.genBranch(loop); loopExits.pop(); tr.genMark(exit); } @Override public void visitIf(Tree.If ifStmt) { ifStmt.condition.accept(this); if (ifStmt.falseBranch != null) { // 有else Label falseLabel = Label.createLabel(); tr.genBeqz(ifStmt.condition.val, falseLabel); ifStmt.trueBranch.accept(this); Label exit = Label.createLabel(); tr.genBranch(exit); tr.genMark(falseLabel); ifStmt.falseBranch.accept(this); tr.genMark(exit); } else if (ifStmt.trueBranch != null) { // 没有else 且if内有代码 Label exit = Label.createLabel(); tr.genBeqz(ifStmt.condition.val, exit); if (ifStmt.trueBranch != null) { ifStmt.trueBranch.accept(this); } tr.genMark(exit); } } @Override public void visitNewArray(Tree.NewArray newArray) { newArray.length.accept(this); newArray.val = tr.genNewArray(newArray.length.val); } @Override public void visitNewClass(Tree.NewClass newClass) { newClass.val = tr.genDirectCall(newClass.symbol.getNewFuncLabel(), BaseType.INT); tr.genAddToOri(newClass.symbol.numinstances, tr.genLoadImm4(1)); // numinstances } @Override public void visitWhileLoop(Tree.WhileLoop whileLoop) { Label loop = Label.createLabel(); tr.genMark(loop); whileLoop.condition.accept(this); Label exit = Label.createLabel(); tr.genBeqz(whileLoop.condition.val, exit); loopExits.push(exit); if (whileLoop.loopBody != null) { whileLoop.loopBody.accept(this); } tr.genBranch(loop); loopExits.pop(); tr.genMark(exit); } @Override public void visitTypeTest(Tree.TypeTest typeTest) { typeTest.instance.accept(this); typeTest.val = tr.genInstanceof(typeTest.instance.val, typeTest.symbol); } @Override public void visitTypeCast(Tree.TypeCast typeCast) { typeCast.expr.accept(this); if (!typeCast.expr.type.compatible(typeCast.symbol.getType())) { tr.genClassCast(typeCast.expr.val, typeCast.symbol); } typeCast.val = typeCast.expr.val; } /* * ?_: 仿照visitif的写法 * */ @Override public void visitQuestionAndColon(Tree.QuestionAndColon questionAndColon){ questionAndColon.left.accept(this); questionAndColon.val = tr.genLoadImm4(0); // 必须要给表达式初值 否则会出错 Label falseLabel = Label.createLabel(); tr.genBeqz(questionAndColon.left.val, falseLabel); // choose questionAndColon.middle.accept(this); tr.genAssign(questionAndColon.val, questionAndColon.middle.val); // 表达式赋值 Label exit = Label.createLabel(); tr.genBranch(exit); tr.genMark(falseLabel); questionAndColon.right.accept(this); tr.genAssign(questionAndColon.val, questionAndColon.right.val); // 表达式赋值 tr.genMark(exit); } /* * numinstances */ @Override public void visitNumTest(Tree.NumTest numTest){ numTest.val = numTest.symbol.numinstances; } /* * GuardedES */ /* * @Override public void visitGuardedES(Tree.GuardedES guardedES) { //Label falseLabel = Label.createLabel(); Label exit = Label.createLabel(); tr.genBeqz(guardedES.expr.val, exit); if (guardedES.tree != null) { guardedES.tree.accept(this); tr.genBranch(exit); } //tr.genMark(falseLabel); tr.genMark(exit); }; */ /* * GuardedIfStmt */ @Override public void visitGuardedIFStmt(Tree.GuardedIFStmt guardedIFStmt){ Label exit = Label.createLabel(); for(Tree.GuardedES i : guardedIFStmt.guardedES){ i.expr.accept(this); Label falseLabel = Label.createLabel(); tr.genBeqz(i.expr.val, falseLabel); i.tree.accept(this); tr.genBranch(exit); tr.genMark(falseLabel); tr.genMark(exit); } } /* * GuardedDOStmt */ @Override public void visitGuardedDOStmt(Tree.GuardedDOStmt guardedDOStmt){ Label loop = Label.createLabel(); tr.genMark(loop); Label exit = Label.createLabel(); loopExits.push(exit); for(Tree.GuardedES i : guardedDOStmt.guardedES){ Label exit1 = Label.createLabel(); i.expr.accept(this); tr.genBeqz(i.expr.val, exit1); if (i.tree != null) { i.tree.accept(this); } tr.genBranch(loop); tr.genMark(exit1); } loopExits.pop(); tr.genMark(exit); } }
PKUanonym/REKCARC-TSC-UHT
大三上/编译原理/hw/2015_刘智峰_PA/PA3/src/decaf/translate/TransPass2.java
1,139
package com.macro.mall.portal.component; import com.macro.mall.portal.domain.QueueEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 取消订单消息的发送者 * Created by macro on 2018/9/14. */ @Component public class CancelOrderSender { private static final Logger LOGGER = LoggerFactory.getLogger(CancelOrderSender.class); @Autowired private AmqpTemplate amqpTemplate; public void sendMessage(Long orderId,final long delayTimes){ //给延迟队列发送消息 amqpTemplate.convertAndSend(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange(), QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey(), orderId, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws AmqpException { //给消息设置延迟毫秒值 message.getMessageProperties().setExpiration(String.valueOf(delayTimes)); return message; } }); LOGGER.info("send orderId:{}",orderId); } }
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/component/CancelOrderSender.java
1,140
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.*; import com.macro.mall.service.UmsRoleService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 后台用户角色管理Controller * Created by macro on 2018/9/30. */ @Controller @Api(tags = "UmsRoleController") @Tag(name = "UmsRoleController", description = "后台用户角色管理") @RequestMapping("/role") public class UmsRoleController { @Autowired private UmsRoleService roleService; @ApiOperation("添加角色") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsRole role) { int count = roleService.create(role); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改角色") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsRole role) { int count = roleService.update(id, role); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除角色") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = roleService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取所有角色") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsRole>> listAll() { List<UmsRole> roleList = roleService.list(); return CommonResult.success(roleList); } @ApiOperation("根据角色名称分页获取角色列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsRole>> list(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsRole> roleList = roleService.list(keyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(roleList)); } @ApiOperation("修改角色状态") @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) { UmsRole umsRole = new UmsRole(); umsRole.setStatus(status); int count = roleService.update(id, umsRole); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取角色相关菜单") @RequestMapping(value = "/listMenu/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMenu>> listMenu(@PathVariable Long roleId) { List<UmsMenu> roleList = roleService.listMenu(roleId); return CommonResult.success(roleList); } @ApiOperation("获取角色相关资源") @RequestMapping(value = "/listResource/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listResource(@PathVariable Long roleId) { List<UmsResource> roleList = roleService.listResource(roleId); return CommonResult.success(roleList); } @ApiOperation("给角色分配菜单") @RequestMapping(value = "/allocMenu", method = RequestMethod.POST) @ResponseBody public CommonResult allocMenu(@RequestParam Long roleId, @RequestParam List<Long> menuIds) { int count = roleService.allocMenu(roleId, menuIds); return CommonResult.success(count); } @ApiOperation("给角色分配资源") @RequestMapping(value = "/allocResource", method = RequestMethod.POST) @ResponseBody public CommonResult allocResource(@RequestParam Long roleId, @RequestParam List<Long> resourceIds) { int count = roleService.allocResource(roleId, resourceIds); return CommonResult.success(count); } }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/controller/UmsRoleController.java
1,143
package cn.hutool.core.date; import java.time.DayOfWeek; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalUnit; import java.util.concurrent.TimeUnit; /** * {@link Temporal} 工具类封装 * * @author looly * @since 5.4.5 */ public class TemporalUtil { /** * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 * <p> * 返回结果为{@link Duration}对象,通过调用toXXX方法返回相差单位 * * @param startTimeInclude 开始时间(包含) * @param endTimeExclude 结束时间(不包含) * @return 时间差 {@link Duration}对象 */ public static Duration between(Temporal startTimeInclude, Temporal endTimeExclude) { return Duration.between(startTimeInclude, endTimeExclude); } /** * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 * <p> * 返回结果为时间差的long值 * * @param startTimeInclude 开始时间(包括) * @param endTimeExclude 结束时间(不包括) * @param unit 时间差单位 * @return 时间差 */ public static long between(Temporal startTimeInclude, Temporal endTimeExclude, ChronoUnit unit) { return unit.between(startTimeInclude, endTimeExclude); } /** * 将 {@link TimeUnit} 转换为 {@link ChronoUnit}. * * @param unit 被转换的{@link TimeUnit}单位,如果为{@code null}返回{@code null} * @return {@link ChronoUnit} * @since 5.7.16 */ public static ChronoUnit toChronoUnit(TimeUnit unit) throws IllegalArgumentException { if (null == unit) { return null; } switch (unit) { case NANOSECONDS: return ChronoUnit.NANOS; case MICROSECONDS: return ChronoUnit.MICROS; case MILLISECONDS: return ChronoUnit.MILLIS; case SECONDS: return ChronoUnit.SECONDS; case MINUTES: return ChronoUnit.MINUTES; case HOURS: return ChronoUnit.HOURS; case DAYS: return ChronoUnit.DAYS; default: throw new IllegalArgumentException("Unknown TimeUnit constant"); } } /** * 转换 {@link ChronoUnit} 到 {@link TimeUnit}. * * @param unit {@link ChronoUnit},如果为{@code null}返回{@code null} * @return {@link TimeUnit} * @throws IllegalArgumentException 如果{@link TimeUnit}没有对应单位抛出 * @since 5.7.16 */ public static TimeUnit toTimeUnit(ChronoUnit unit) throws IllegalArgumentException { if (null == unit) { return null; } switch (unit) { case NANOS: return TimeUnit.NANOSECONDS; case MICROS: return TimeUnit.MICROSECONDS; case MILLIS: return TimeUnit.MILLISECONDS; case SECONDS: return TimeUnit.SECONDS; case MINUTES: return TimeUnit.MINUTES; case HOURS: return TimeUnit.HOURS; case DAYS: return TimeUnit.DAYS; default: throw new IllegalArgumentException("ChronoUnit cannot be converted to TimeUnit: " + unit); } } /** * 日期偏移,根据field不同加不同值(偏移会修改传入的对象) * * @param <T> 日期类型,如LocalDate或LocalDateTime * @param time {@link Temporal} * @param number 偏移量,正数为向后偏移,负数为向前偏移 * @param field 偏移单位,见{@link ChronoUnit},不能为null * @return 偏移后的日期时间 */ @SuppressWarnings("unchecked") public static <T extends Temporal> T offset(T time, long number, TemporalUnit field) { if (null == time) { return null; } return (T) time.plus(number, field); } /** * 偏移到指定的周几 * * @param temporal 日期或者日期时间 * @param dayOfWeek 周几 * @param <T> 日期类型,如LocalDate或LocalDateTime * @param isPrevious 是否向前偏移,{@code true}向前偏移,{@code false}向后偏移。 * @return 偏移后的日期 * @since 5.8.0 */ @SuppressWarnings("unchecked") public <T extends Temporal> T offset(T temporal, DayOfWeek dayOfWeek, boolean isPrevious) { return (T) temporal.with(isPrevious ? TemporalAdjusters.previous(dayOfWeek) : TemporalAdjusters.next(dayOfWeek)); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/date/TemporalUtil.java
1,144
M 1521616414 tags: DP, Array, Game Theory, Memoization, MiniMax 给一串coins, 用values[]表示; 每个coin有自己的value. 先手/后手博弈, 每次只能 按照从左到右的顺序, 拿1个或者2个棋子, 最后看谁拿的总值最大. MiniMax的思考方法很神奇, 最后写出来的表达式很简单 #### DP, Game Theory 自考过程比较长 - 跟Coins in a line I 不一样: 每个coin的value不同. - 用到MiniMax的思想, 这里其实是MaxiMin. Reference: http://www.cnblogs.com/grandyang/p/5864323.html - Goal: 使得player拿到的coins value 最大化. - 设定dp[i]: 从index i 到 index n的最大值. 所以dp[0]就是我们先手在[0 ~ n]的最大取值 - 于此同时, 你的对手playerB也想最大化, 而你的选择又不得不被对手的选择所牵制. - 用MaxiMin的思想, 我们假设一个当下的状态, 假想对手playerB会做什么反应(从对手角度, 如何让我输) - 在劣势中(对手让我输的目标下)找到最大的coins value sum ##### 推算表达式 - Reference里面详细介绍了表达式如何推到出来, 简而言之: - 如果我选了i, 那么对手就只能选(i+1), (i+2) 两个位置, 而我在对方掌控时的局面就是min(dp[i+2], dp[i+3]) - 如果我选了i和(i+1), 那么对手就只能选(i+2), (i+3) 两个位置, 而我在对方掌控时的局面就是min(dp[i+3], dp[i+4]) - 大家都是可选1个或者2个coins - 目标是maximize上面两个最坏情况中的最好结果 ##### 简化表达式 - 更加简化一点: 如果我是先手, dp[i]代表我的最大值. - 取决于我拿了[i], 还是[i] + [i+1], 对手可能是dp[i + 1], 或者是dp[i+2] - 其实dp[i] = Math.max(sum - dp[i + 1], sum - dp[i + 2]); - 这里的sum[i] = [i ~ n] 的sum, 减去dp[i+1], 剩下就是dp[i]的值没错了 ##### Initialization - 这个做法是从最后往前推的, 注意initialize dp末尾的值. - dp = new int[n + 1]; dp[n] = 0; // [n ~ n]啥也不选的时候, 为0. - sum = new int[n + 1]; sum[n] = 0; // 啥也不选的时候, 自然等于0 - 然后记得initialize (n-1), (n-2) ##### 时间/空间 Time O(n) Space O(n): dp[], sum[] ``` /* There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins. Could you please decide the first player will win or lose? Have you met this question in a real interview? Example Given values array A = [1,2,2], return true. Given A = [1,2,4], return false. */ /* Thoughts 较为复杂, 写中文: - 跟Coins in a line I 不一样: 每个coin的value不同. - 用到MiniMax的思想, 这里其实是MaxiMin. Reference: http://www.cnblogs.com/grandyang/p/5864323.html - Goal: 使得player拿到的coins value 最大化. - 于此同时, 你的对手playerB也想最大化, 而你的选择又不得不被对手的选择所牵制. - 用MaxiMin的思想, 我们假设一个当下的状态, 假想对手playerB会做什么反应(从对手角度, 如何让我输) - 在劣势中(对手让我输的目标下)找到最大的coins value sum - 设定dp[i]: 从index i 到 index n的最大值. 所以dp[0]就是我们先手在[0 ~ n]的最大取值 Reference里面详细介绍了表达式如何推到出来, 简而言之: - 如果我选了i, 那么对手就只能选(i+1), (i+2) 两个位置, 而我在对方掌控时的局面就是min(dp[i+2], dp[i+3]) - 如果我选了i和(i+1), 那么对手就只能选(i+2), (i+3) 两个位置, 而我在对方掌控时的局面就是min(dp[i+3], dp[i+4]) - 大家都是可选1个或者2个coins - 目标是maximize上面两个最坏情况中的最好结果 更加简化一点: 如果我是先手, dp[i]代表我的最大值. 取决于我拿了[i], 还是[i] + [i+1], 对手可能是dp[i + 1], 或者是dp[i+2] 其实dp[i] = Math.max(sum - dp[i + 1], sum - dp[i + 2]); 这里的sum[i] = [i ~ n] 的sum, 减去dp[i+1], 剩下就是dp[i]的值没错了 Note: 这个做法是从最后往前推的, 注意initialize dp末尾的值. dp = new int[n + 1] dp[n] = 0; // [n ~ n]啥也不选的时候, 为0. sum = new int[n + 1] sum[n] = 0; // 啥也不选的时候, 自然等于0 然后initialize (n-1), (n-2) */ public class Solution { public boolean firstWillWin(int[] values) { if (values == null || values.length == 0) { return false; } if (values.length <= 2) { return true; } int n = values.length; int[] dp = new int[n + 1]; // max value for [i ~ n] int[] sum = new int[n + 1]; // sum of [i ~ n] // Init dp dp[n] = 0; dp[n - 1] = values[n - 1]; // only 1 item for max dp[n - 2] = values[n - 1] + values[n - 2]; // only 2 items, get all for max // Init Sum sum[n] = 0; sum[n - 1] = values[n - 1]; for (int i = n - 2; i >= 0; i--) { sum[i] = sum[i + 1] + values[i]; dp[i] = Math.max(sum[i] - dp[i + 1], sum[i] - dp[i + 2]); // Maximize the value during playerA's worst scenario } return sum[0] - dp[0] < dp[0]; } } ```
awangdev/leet-code
Java/Coins in a Line II.java
1,145
package io.mycat.catlets; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.sqlengine.mpp.OrderCol; import io.mycat.util.StringUtil; /** * 功能详细描述:分片join,单独的语句 * @author sohudo[http://blog.csdn.net/wind520] * @create 2015年02月01日 * @version 0.0.1 */ public class TableFilter { protected static final Logger LOGGER = LoggerFactory.getLogger(TableFilter.class); private LinkedHashMap<String,String> fieldAliasMap = new LinkedHashMap<String,String>(); private String tName; //table 名称 private String tAlia; //table别名 private String where=""; //where 条件 private String order=""; private String parenTable="";//左连接的join的表 private String joinParentkey="";//左连接的join字段 private String joinKey=""; //join字段 private TableFilter join; //右连接的join表 private TableFilter parent; //左连接的join的表 private int offset=0; private int rowCount=0; private boolean outJoin; private boolean allField; public TableFilter(String taName,String taAlia,boolean outJoin) { this.tName=taName; this.tAlia=taAlia; this.outJoin=outJoin; this.where=""; } /** * a.fieldName 获取表名称 * 返回 table 名称。 */ private String getTablefrom(String key){ if (key==null){ return ""; } else { int i=key.indexOf('.'); if (i==-1){ return key; } else { return key.substring(0, i); } } } /** * a.fieldName 获取字段 * 返回 fieldName */ private String getFieldfrom(String key){ if (key==null){ return ""; } else { int i=key.indexOf('.'); if (i==-1){ return key; } else { return key.substring(i + 1); } } } public void addField(String fieldName,String fieldAlia){ String atable=getTablefrom(fieldName); //表名称 String afield=getFieldfrom(fieldName); //字段 boolean allfield=afield.equals("*")?true:false; //是否有* if (atable.equals("*")) { fieldAliasMap.put(afield, null); // 放入字段 * 到 fieldMap中。 setAllField(allfield); if (join!=null) { join.addField(fieldName,null); //递归设置子表 join.setAllField(allfield); } } else { if (atable.equals(tAlia)) { //将字段放入对应的表中。 fieldAliasMap.put(afield, fieldAlia); setAllField(allfield); } else { if (join!=null) {//B表中查询 是否可以放入字段。 join.addField(fieldName,fieldAlia); join.setAllField(allfield); } } } } //解析字段 public void addField(String fieldName,String fieldAlia,String expr){ String atable=getTablefrom(fieldName); String afield=getFieldfrom(fieldName); boolean allfield=afield.equals("*")?true:false; if (atable.equals("*")) { fieldAliasMap.put(afield, null); setAllField(allfield); if (join!=null) { join.addField(fieldName,null); join.setAllField(allfield); } } else { if (atable.equals(tAlia)) { expr = expr.replace(fieldName, afield); fieldAliasMap.put(expr, fieldAlia); setAllField(allfield); } else { if (join!=null) { join.addField(fieldName,fieldAlia,expr); join.setAllField(allfield); } } } } public void addWhere(String fieldName,String value,String Operator,String and){ String atable=getTablefrom(fieldName); String afield=getFieldfrom(fieldName); if (atable.equals(tAlia)) { // 修复在拼接sql的时候少空格的bug where=unionsql(where,afield + " " + Operator + " " + value,and); } else { if (join!=null) { join.addWhere(fieldName,value,Operator,and); } } } public void addWhere(String fieldName,String condition,String and){ String atable=getTablefrom(fieldName); String afield=getFieldfrom(fieldName); condition = condition.replace(fieldName, afield); if (atable.equals(tAlia)) { where=unionsql(where,condition,and); } else { if (join!=null) { join.addWhere(fieldName,condition,and); } } } private String unionsql(String key,String value,String Operator){ if (key.trim().equals("")){ key=value; } else { key+=" "+Operator+" "+value; } return key; } LinkedHashMap<String, Integer> orderByCols = new LinkedHashMap<String, Integer>(); public void addOrders(int index, String fieldName,String des){ // String atable=getTablefrom(fieldName); String afield=getFieldfrom(fieldName); if (fieldInTable(fieldName)) { order=unionsql(order,afield+" "+des,","); //将order 类型加入到链表中. 還得看下是否使用別名 int orderType = StringUtil.isEmpty(des)||"asc".equals(des.toLowerCase().trim())?OrderCol.COL_ORDER_TYPE_ASC:OrderCol.COL_ORDER_TYPE_DESC; orderByCols.put(afield, encodeOrignOrderType(index, orderType)); } else { if (join!=null) { join.addOrders(index, fieldName,des); } } } /* * 判断字段是否在表中。 * */ private boolean fieldInTable(String fieldName) { String atable=getTablefrom(fieldName); if(atable.equals(tAlia) ){ return true; } if(StringUtil.isEmpty(atable)){ String afield=getFieldfrom(fieldName); for(String tableField : fieldAliasMap.keySet()) { if(afield.equals(fieldAliasMap.get(tableField))) { return true; } } } return false; } public LinkedHashMap<String, Integer> getOrderByCols(){ return orderByCols; } public void addLimit(int offset,int rowCount){ this.offset=offset; this.rowCount=rowCount; } public void setJoinKey(String fieldName,String value){ if (parent==null){ if (join!=null) { join.setJoinKey(fieldName,value); } } else { //1 ,fileName 为当前的joinKey //2 value 为当前的joinKey int i=joinLkey(fieldName,value); if (i==1){ joinParentkey=getFieldfrom(value); parenTable =getTablefrom(value); joinKey=getFieldfrom(fieldName); } else { if (i==2){ joinParentkey=getFieldfrom(fieldName); parenTable =getTablefrom(fieldName); joinKey=getFieldfrom(value); } else { if (join!=null) { join.setJoinKey(fieldName,value); } } } } } private String getChildJoinKey(boolean left){ if (join!=null){ if (left) { return join.joinParentkey; } else { return join.joinKey; } } else { return ""; } } public String getJoinKey(boolean left){ return getChildJoinKey(left); } private int joinLkey(String fieldName,String value){ String key1=getTablefrom(fieldName); String key2=getTablefrom(value); if (key1.equals(tAlia) ) { return 1; } if (key2.equals(tAlia) ) { return 2; } /* String bAlia=""; if (join!=null){ bAlia=join.getTableAlia(); } if (key1.equals(tAlia)&& key2.equals(bAlia) ) { return 1; } if (key2.equals(tAlia)&& key1.equals(bAlia) ) { return 2; } */ return 0; } public String getTableName(){ return tName; } public void setTableName(String value){ tName=value; } public String getTableAlia(){ return tAlia; } public void setTableAlia(String value){ tAlia=value; } public boolean getOutJoin(){ return outJoin; } public void setOutJoin(boolean value){ outJoin=value; } public boolean getAllField(){ return allField; } public void setAllField(boolean value){ allField=value; } public TableFilter getTableJoin(){ return join; } public void setTableJoin(TableFilter value){ join=value; join.setParent(this); } public TableFilter getParent() { return parent; } public void setParent(TableFilter parent) { this.parent = parent; } private String unionField(String field,String key,String Operator){ if (key.trim().equals("")){ key=field; } else { key=field+Operator+" "+key; } return key; } public String getSQL(){ String sql=""; Iterator<Entry<String, String>> iter = fieldAliasMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); String key = entry.getKey(); String val = entry.getValue(); if (val==null) { sql=unionsql(sql,getFieldfrom(key),","); } else { sql = unionsql(sql, getFieldfrom(key) + " as " + val, ","); } } if (parent==null){ // on/where 等于号左边的表 String parentJoinKey = getJoinKey(true); // fix sharejoin bug: // (AbstractConnection.java:458) -close connection,reason:program err:java.lang.IndexOutOfBoundsException: // 原因是左表的select列没有包含 join 列,在获取结果时报上面的错误 if(sql != null && parentJoinKey != null && sql.toUpperCase().indexOf(parentJoinKey.trim().toUpperCase()) == -1){ sql += ", " + parentJoinKey; } sql="select "+sql+" from "+tName; if (!(where.trim().equals(""))){ sql+=" where "+where.trim(); } } else { // on/where 等于号右边边的表 if (allField) { sql="select "+sql+" from "+tName; } else { sql=unionField("select "+joinKey,sql,","); sql=sql+" from "+tName; //sql="select "+joinKey+","+sql+" from "+tName; } if (!(where.trim().equals(""))){ sql+=" where "+where.trim()+" and ("+joinKey+" in %s )"; } else { sql+=" where "+joinKey+" in %s "; } } /* if (!(order.trim().equals(""))){ sql+=" order by "+order.trim(); } if (parent==null){ if ((rowCount>0)&& (offset>0)){ sql+=" limit "+offset+","+rowCount; } else { if (rowCount>0){ sql+=" limit "+rowCount; } } } */ return sql; } public int getOffset() { return offset; } public int getRowCount() { return rowCount; } public static int encodeOrignOrderType(int index , int orderType) { return index << 1 | orderType; } public static int decodeOrderType(int orignOrderType){ return orignOrderType & 1; } public static int decodeOrignOrder(int orignOrderType){ return orignOrderType >> 1; } public static void main(String[] args) { int val = encodeOrignOrderType(45, 1); System.out.println(decodeOrderType(val)); System.out.println(decodeOrignOrder(val)); } @Override public String toString() { return "TableFilter [fieldAliasMap=" + fieldAliasMap + ", tName=" + tName + ", tAlia=" + tAlia + ", where=" + where + ", order=" + order + ", parenTable=" + parenTable + ", joinParentkey=" + joinParentkey + ", joinKey=" + joinKey + ", join=" + join + ", offset=" + offset + ", rowCount=" + rowCount + ", outJoin=" + outJoin + ", allField=" + allField + "]"; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/catlets/TableFilter.java
1,148
public class BinarySearchTree { private Node tree; public Node find(int data) { Node p = tree; while (p != null) { if (data < p.data) p = p.left; else if (data > p.data) p = p.right; else return p; } return null; } public void insert(int data) { if (tree == null) { tree = new Node(data); return; } Node p = tree; while (p != null) { if (data > p.data) { if (p.right == null) { p.right = new Node(data); return; } p = p.right; } else { // data < p.data if (p.left == null) { p.left = new Node(data); return; } p = p.left; } } } public void delete(int data) { Node p = tree; // p指向要删除的节点,初始化指向根节点 Node pp = null; // pp记录的是p的父节点 while (p != null && p.data != data) { pp = p; if (data > p.data) p = p.right; else p = p.left; } if (p == null) return; // 没有找到 // 要删除的节点有两个子节点 if (p.left != null && p.right != null) { // 查找右子树中最小节点 Node minP = p.right; Node minPP = p; // minPP表示minP的父节点 while (minP.left != null) { minPP = minP; minP = minP.left; } p.data = minP.data; // 将minP的数据替换到p中 p = minP; // 下面就变成了删除minP了 pp = minPP; } // 删除节点是叶子节点或者仅有一个子节点 Node child; // p的子节点 if (p.left != null) child = p.left; else if (p.right != null) child = p.right; else child = null; if (pp == null) tree = child; // 删除的是根节点 else if (pp.left == p) pp.left = child; else pp.right = child; } public Node findMin() { if (tree == null) return null; Node p = tree; while (p.left != null) { p = p.left; } return p; } public Node findMax() { if (tree == null) return null; Node p = tree; while (p.right != null) { p = p.right; } return p; } public static class Node { private int data; private Node left; private Node right; public Node(int data) { this.data = data; } } }
wangzheng0822/algo
java/24_tree/BinarySearchTree.java
1,149
/** * File: hanota.java * Created Time: 2023-07-17 * Author: krahets ([email protected]) */ package chapter_divide_and_conquer; import java.util.*; public class hanota { /* 移动一个圆盘 */ static void move(List<Integer> src, List<Integer> tar) { // 从 src 顶部拿出一个圆盘 Integer pan = src.remove(src.size() - 1); // 将圆盘放入 tar 顶部 tar.add(pan); } /* 求解汉诺塔问题 f(i) */ static void dfs(int i, List<Integer> src, List<Integer> buf, List<Integer> tar) { // 若 src 只剩下一个圆盘,则直接将其移到 tar if (i == 1) { move(src, tar); return; } // 子问题 f(i-1) :将 src 顶部 i-1 个圆盘借助 tar 移到 buf dfs(i - 1, src, tar, buf); // 子问题 f(1) :将 src 剩余一个圆盘移到 tar move(src, tar); // 子问题 f(i-1) :将 buf 顶部 i-1 个圆盘借助 src 移到 tar dfs(i - 1, buf, src, tar); } /* 求解汉诺塔问题 */ static void solveHanota(List<Integer> A, List<Integer> B, List<Integer> C) { int n = A.size(); // 将 A 顶部 n 个圆盘借助 B 移到 C dfs(n, A, B, C); } public static void main(String[] args) { // 列表尾部是柱子顶部 List<Integer> A = new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1)); List<Integer> B = new ArrayList<>(); List<Integer> C = new ArrayList<>(); System.out.println("初始状态下:"); System.out.println("A = " + A); System.out.println("B = " + B); System.out.println("C = " + C); solveHanota(A, B, C); System.out.println("圆盘移动完成后:"); System.out.println("A = " + A); System.out.println("B = " + B); System.out.println("C = " + C); } }
krahets/hello-algo
codes/java/chapter_divide_and_conquer/hanota.java
1,150
package com.macro.mall.portal.config; import com.macro.mall.portal.domain.QueueEnum; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 消息队列相关配置 * Created by macro on 2018/9/14. */ @Configuration public class RabbitMqConfig { /** * 订单消息实际消费队列所绑定的交换机 */ @Bean DirectExchange orderDirect() { return ExchangeBuilder .directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange()) .durable(true) .build(); } /** * 订单延迟队列队列所绑定的交换机 */ @Bean DirectExchange orderTtlDirect() { return ExchangeBuilder .directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange()) .durable(true) .build(); } /** * 订单实际消费队列 */ @Bean public Queue orderQueue() { return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName()); } /** * 订单延迟队列(死信队列) */ @Bean public Queue orderTtlQueue() { return QueueBuilder .durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName()) .withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机 .withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键 .build(); } /** * 将订单队列绑定到交换机 */ @Bean Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){ return BindingBuilder .bind(orderQueue) .to(orderDirect) .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey()); } /** * 将订单延迟队列绑定到交换机 */ @Bean Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){ return BindingBuilder .bind(orderTtlQueue) .to(orderTtlDirect) .with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey()); } }
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/config/RabbitMqConfig.java
1,151
package com.crossoverjie.actual; /** * Function: 两个线程交替执行打印 1~100 * <p> * non blocking 版: * 两个线程轮询volatile变量(flag) * 线程一"看到"flag值为1时执行代码并将flag设置为0, * 线程二"看到"flag值为0时执行代码并将flag设置未1, * 2个线程不断轮询直到满足条件退出 * * @author twoyao * Date: 05/07/2018 * @since JDK 1.8 */ public class TwoThreadNonBlocking implements Runnable { /** * 当flag为1时只有奇数线程可以执行,并将其置为0 * 当flag为0时只有偶数线程可以执行,并将其置为1 */ private volatile static int flag = 1; private int start; private int end; private String name; private TwoThreadNonBlocking(int start, int end, String name) { this.name = name; this.start = start; this.end = end; } @Override public void run() { while (start <= end) { int f = flag; if ((start & 0x01) == f) { System.out.println(name + "+-+" + start); start += 2; // 因为只可能同时存在一个线程修改该值,所以不会存在竞争 flag ^= 0x1; } } } public static void main(String[] args) { new Thread(new TwoThreadNonBlocking(1, 100, "t1")).start(); new Thread(new TwoThreadNonBlocking(2, 100, "t2")).start(); } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/TwoThreadNonBlocking.java
1,154
package com.xkcoding.https.config; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * <p> * HTTPS 配置类 * </p> * * @author Chen.Chao * @date Created in 2020-01-12 10:31 */ @Configuration public class HttpsConfig { /** * 配置 http(80) -> 强制跳转到 https(443) */ @Bean public Connector connector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(80); connector.setSecure(false); connector.setRedirectPort(443); return connector; } @Bean public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(connector); return tomcat; } }
xkcoding/spring-boot-demo
demo-https/src/main/java/com/xkcoding/https/config/HttpsConfig.java
1,155
package org.ansj.app.crf; import org.ansj.app.crf.model.CRFModel; import org.ansj.app.crf.model.CRFppTxtModel; import org.ansj.app.crf.model.WapitiCRFModel; import org.nlpcn.commons.lang.tire.domain.SmartForest; import org.nlpcn.commons.lang.util.MapCount; import org.nlpcn.commons.lang.util.logging.Log; import org.nlpcn.commons.lang.util.logging.LogFactory; import java.io.*; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPOutputStream; public abstract class Model { public static final Log logger = LogFactory.getLog(Model.class); protected Config config; protected SmartForest<float[]> featureTree = null; protected float[][] status = new float[Config.TAG_NUM][Config.TAG_NUM]; public int allFeatureCount = 0; /** * 判断当前数据流是否是本实例 * * @param is * @return */ public abstract boolean checkModel(String modelPath) throws IOException; /** * 模型读取 * * @param path * @return * @return * @throws Exception */ public static Model load(String modelPath) throws Exception { Model model = new CRFModel(); if (model.checkModel(modelPath)) { return model.loadModel(modelPath); } model = new CRFppTxtModel(); if (model.checkModel(modelPath)) { return model.loadModel(modelPath); } model = new WapitiCRFModel(); if (model.checkModel(modelPath)) { return model.loadModel(modelPath); } throw new Exception("I did not know what type of model by file " + modelPath); } /** * 模型读取 * * @param path * @return * @return * @throws Exception */ public static Model load(Class<? extends Model> c, InputStream is) throws Exception { Model model = c.newInstance(); return model.loadModel(is); } /** * 不同的模型实现自己的加载模型类 * * @throws Exception */ public abstract Model loadModel(String modelPath) throws Exception; public abstract Model loadModel(InputStream is) throws Exception; /** * 获得特征所在权重数组 * * @param featureStr * @return */ public float[] getFeature(char... chars) { if (chars == null) { return null; } SmartForest<float[]> sf = featureTree; sf = sf.getBranch(chars); if (sf == null || sf.getParam() == null) { return null; } return sf.getParam(); } public Config getConfig() { return this.config; } /** * tag转移率 * * @param s1 * @param s2 * @return */ public float tagRate(int s1, int s2) { return status[s1][s2]; } /** * 增加特征到特征数中 * * @param cs * @param tempW */ protected static void printFeatureTree(String cs, float[] tempW) { String name = "*"; if (tempW.length == 4) { name = "U"; } name += "*" + (cs.charAt(cs.length() - 1) - Config.FEATURE_BEGIN + 1) + ":" + cs.substring(0, cs.length() - 1); for (int i = 0; i < tempW.length; i++) { if (tempW[i] != 0) { System.out.println(name + "\t" + Config.getTagName(i / 4 - 1) + "\t" + Config.getTagName(i % 4) + "\t" + tempW[i]); } } } /** * 将model序列化到硬盘 * * @param path * @throws IOException * @throws FileNotFoundException */ public void writeModel(String path) { try (FileOutputStream fso = new FileOutputStream(path)) { ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(fso)); oos.writeUTF(CRFModel.version); oos.writeObject(status); oos.writeObject(config.getTemplate()); Map<String, float[]> map = featureTree.toMap(); MapCount<Integer> mc = new MapCount<Integer>(); for (float[] v : map.values()) { mc.add(v.length); } for (Entry<Integer, Double> entry : mc.get().entrySet()) { int win = entry.getKey(); oos.writeInt(win);// 宽度 oos.writeInt(entry.getValue().intValue());// 个数 for (Entry<String, float[]> e : map.entrySet()) { if (e.getValue().length == win) { oos.writeUTF(e.getKey()); float[] value = e.getValue(); for (int i = 0; i < win; i++) { oos.writeFloat(value[i]); } } } } oos.writeInt(0); oos.writeInt(0); oos.flush(); oos.close(); } catch (FileNotFoundException e) { logger.warn("文件没有找到", e); } catch (IOException e) { logger.warn("IO异常", e); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/app/crf/Model.java
1,156
package com.zheng.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; /** * 启动解压zhengAdmin-x.x.x.jar到resources目录 * Created by shuzheng on 2016/12/18. */ public class ZhengAdminUtil implements InitializingBean, ServletContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(ZhengAdminUtil.class); @Override public void afterPropertiesSet() throws Exception { } @Override public void setServletContext(ServletContext servletContext) { LOGGER.info("===== 开始解压zheng-admin ====="); String version = PropertiesFileUtil.getInstance("zheng-admin-client").get("zheng.admin.version"); LOGGER.info("zheng-admin.jar 版本: {}", version); String jarPath = servletContext.getRealPath("/WEB-INF/lib/zheng-admin-" + version + ".jar"); LOGGER.info("zheng-admin.jar 包路径: {}", jarPath); String resources = servletContext.getRealPath("/") + "/resources/zheng-admin"; LOGGER.info("zheng-admin.jar 解压到: {}", resources); JarUtil.decompress(jarPath, resources); LOGGER.info("===== 解压zheng-admin完成 ====="); } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/ZhengAdminUtil.java
1,166
H 1521702603 tags: Array, DP, Game Theory, Interval DP, Memoization LeetCode: Predict the Winner 还是2个人拿n个coin, coin可以有不同的value. 只不过这次选手可以从任意的一头拿, 而不限制从一头拿. 算先手会不会赢? #### Memoization + Search - 跟Coins in a Line II 一样, MaxiMin的思想: 找到我的劣势中的最大值 - `dp[i][j] 代表在[i,j]区间上 选手最多能取的value 总和` - 同样, sum[i][j]表示[i] 到 [j]间的value总和 - 对手的最差情况, 也就是先手的最好情况: - dp[i][j] = sum[i][j] - Math.min(dp[i][j - 1], dp[i + 1][j]); - 这里需要search, 画出tree可以看明白是如何根据取前后而分段的. #### 博弈 + 区间DP, Interval DP - 因为是看区间[i,j]的情况, 所以可以想到是区间 DP - 这个方法需要复习, 跟数学表达式的推断相关联: S(x) = - S(y) + m. 参考下面的公式推导. - dp[i][j]表示 从index(i) 到 index(j), 先手可以拿到的最大值与对手的数字差. 也就是S(x). - 其中一个S(x) = dp[i][j] = a[i] - dp[i + 1][j] - m 取在开头, m 取在末尾的两种情况: - dp[i][j] = max{a[i] - dp[i + 1][j], a[j] - dp[i][j - 1]} - len = 1, 积分就是values[i] - 最后判断 dp[0][n] >= 0, 最大数字和之差大于0, 就赢. - 时间/空间 O(n^2) ##### 公式推导 - S(x) = X - Y, 找最大数字和之差, 这里X和Y是选手X的总分, 选手Y的总分. - 对于选手X而言: 如果S(x)最大值大于0, 就是赢了; 如果最大值都小于0, 就一定是输了. - 选手Y: S(y)来表示 对于Y, 最大数字和之差. S(y) = Y - X - 根据S(x) 来看, 如果从 数字和X里面, 拿出一个数字 m, 也就是 X = m + Xwithout(m) - S(x) = m + Xwithout(m) - Y = m + (Xwithout(m) - Y). - 如果我们从全局里面索性去掉m, 那么 S(y'') = Y - Xwithout(m) - 那么推算下来: S(x) = m + (Xwithout(m) - Y) = m - (Y - Xwithout(m)) = m - S(y'') - 在这个问题里面, 我们model X 和 Y的时候, 其实都是 dp[i][j], 而区别在于先手/后手. - 将公式套用, 某一个S(x) = a[i] - dp[i + 1][j], 也就是m=a[i], 而 S(y'') = dp[i + 1][j] ##### 注意 - 如果考虑计算先手[i, j]之间的最大值, 然后可能还需要两个数组, 最后用于比较先手和opponent的得分大小 => 那么就要多开维. - 我们这里考虑的数字差, 刚好让人不需要计算先手的得分总值, 非常巧妙. - Trick: 利用差值公式, 推导有点难想到. ##### 区间型动态规划 - 找出[i, j]区间内的性质: dp[i][j]下标表示区间范围 [i, j] - 子问题: 砍头, 砍尾, 砍头砍尾 - loop应该基于区间的length - template: 考虑len = 1, len = 2; 设定i的时候一定是 i <= n - len; 设定j的时候, j = len + i - 1; ``` /* There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins. Could you please decide the first player will win or lose? Example Given array A = [3,2,2], return true. Given array A = [1,2,4], return true. Given array A = [1,20,4], return false. Challenge Follow Up Question: If n is even. Is there any hacky algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time? Tags Array Dynamic Programming Game Theory */ /* 博弈. 这题, 是区间型. 区间型标志: 每人每次只能取第一个数,或者最后一个数 翻译: 每次砍头, 或者砍尾 trick, 记录自己的数字与对手的数字和之差: S(x) = X - Y, 找最大数字差. 如果最大值都大于0, 就是赢了; 如果小于0, 就输了. 这里我们用S(x)表示对于x先手而言的数字差, S(y)表示对于opponent y 先手而言的数字差. 假设x先手的时候, S(x) = X - Y. 这一步拿掉了大小为m的coin. 当opponent变成先手时候, 剩下的coins 被分割成x’, y’, 就有subset的S’(y) = y’ - x’ Overall S(y) = Y - X = y’ - x’ - m = S’(y) - m 同时S(x) = X - Y = -(S’(y) - m) = m - S’(y) 注意: 这里的S’(y)面对的是拿过coins剩下的局面. dp[i][j]表示 从index(i) 到 index(j), 先手可以拿到的最大值与对手的数字差. 也就是S(x) = X - Y. 那么S(x) = X - Y = a[i] - dp[i + 1][j]; // 砍头 X = a[i]. 那里第i个coin dp[i + 1][j]: opponent从 i 位之后能积累的最大值 a[j] - dp[i][j - 1]//砍尾 dp[i][j] = max{a[i] - dp[i + 1][j], a[j] - dp[i][j - 1]} 最后看dp[0][n] >= 0 */ public class Solution { public boolean firstWillWin(int[] values) { if (values == null || values.length == 0) { return false; } int n = values.length; int[][] dp = new int[n][n]; // len = 1 for (int i = 0; i < n; i++) { dp[i][i] = values[i]; } // len = 2 for (int len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { int j = len + i - 1; dp[i][j] = Math.max(values[i] - dp[i + 1][j], values[j] - dp[i][j - 1]); } } return dp[0][n - 1] >= 0; } } /* Thoughts: MiniMax concept, memoization dp. dp[i][j]: max sum of values a player can get in range [i, j] sum[i][j]: sum of value in range [i, j] dp[i][j] = sum[i][j] - Math.min(dp[i + 1][j], dp[i][j - 1]); */ public class Solution { public boolean firstWillWin(int[] values) { if (values == null || values.length == 0) { return false; } int n = values.length; int[][] sum = new int[n + 1][n + 1]; int[][] dp = new int[n + 1][n + 1]; boolean[][] visited = new boolean[n + 1][n + 1]; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (i == j) { sum[i][j] = values[i]; } else { sum[i][j] = sum[i][j - 1] + values[j]; } } } // total int total = 0; for (int value : values) { total += value; } search(0, n - 1, visited, dp, sum, values); return dp[0][n - 1] > total / 2; } private void search(int i, int j, boolean[][] visited, int[][] dp, int[][] sum, int[] values) { if (visited[i][j]) { return; } visited[i][j] = true; if (i == j) { dp[i][j] = values[i]; } else if (i > j) { dp[i][j] = 0; } else if (i + 1 == j) { dp[i][j] = Math.max(values[i], values[j]); } else { search(i + 1, j, visited, dp, sum, values); search(i, j - 1, visited, dp, sum, values); dp[i][j] = sum[i][j] - Math.min(dp[i + 1][j], dp[i][j - 1]); } } } //using flat to mark visited; actually dp[i][j] > 0 will mean visited, since coin value > 0 public class Solution { public boolean firstWillWin(int[] values) { if (values == null || values.length == 0) { return false; } int n = values.length; int[][] sum = new int[n + 1][n + 1]; int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (i == j) { sum[i][j] = values[i]; } else { sum[i][j] = sum[i][j - 1] + values[j]; } } } // total int total = 0; for (int value : values) { total += value; } search(0, n - 1, dp, sum, values); return dp[0][n - 1] > total / 2; } private void search(int i, int j, int[][] dp, int[][] sum, int[] values) { if (dp[i][j] > 0) { return; } if (i == j) { dp[i][j] = values[i]; } else if (i > j) { dp[i][j] = 0; } else if (i + 1 == j) { dp[i][j] = Math.max(values[i], values[j]); } else { search(i + 1, j, dp, sum, values); search(i, j - 1, dp, sum, values); dp[i][j] = sum[i][j] - Math.min(dp[i + 1][j], dp[i][j - 1]); } } } ```
awangdev/leet-code
Java/Coins in a Line III.java
1,167
M 1529974964 tags: Array, PreSum, Hash Table 给一个int[][] matrix, 找一个sub matrix, where the sum == 0. #### PreSum的思想 - 算出一个右下角点(i,j)到(0,0)的大小: 上一块 + 左一块 + curr node - overlap area - preSum[i][j]: sum from (0,0) to (i-1,j-1) - same approach as `subarray sum`: use hashmap to store diff->index; if diff re-appears, that means sum of 0 has occurred - sequence of calculation: 1. iterate over start row. 2. iterate over end row. 3. iterate over col number (this is where hashmap is stored based on) - the iteration over col is like a screening: find previous sum and determine result - Note: 其实并没有真的去找 `== 0` 的解答,而是根据特性来判断 `剩下的/后来加上的一定是0` ``` /* Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number. Example: [ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ] return [(1,1), (2,2)] Challenge O(n^3) time. */ class Solution { public int[][] submatrixSum(int[][] nums) { int[][] rst = new int[2][2]; // check input if (validateInput(nums)) { return rst; } int m = nums.length, n = nums[0].length; // calculate presum int[][] preSum = new int[m + 1][n + 1]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { preSum[i+1][j+1] = preSum[i][j+1] + preSum[i+1][j] + nums[i][j] - preSum[i][j]; } } // iterations for (int start = 0; start < m; start++) { for (int end = start + 1; end <= m; end++) { Map<Integer, Integer> map = new HashMap<>(); for (int col = 0; col <= n; col++) { int diff = preSum[end][col] - preSum[start][col]; if (map.containsKey(diff)) { rst[0][0] = start; rst[0][1] = map.get(diff); rst[1][0] = end - 1; rst[1][1] = col - 1; return rst; } map.put(diff, col); } } } return rst; } private boolean validateInput(int[][] nums) { if (nums == null || nums.length == 0 || nums[0] == null || nums[0].length == 0) { return true; } return false; } } ```
awangdev/leet-code
Java/Submatrix Sum.java
1,168
package cn.hutool.core.lang; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; /** * {@link ParameterizedType} 接口实现,用于重新定义泛型类型 * * @author looly * @since 4.5.7 */ public class ParameterizedTypeImpl implements ParameterizedType, Serializable { private static final long serialVersionUID = 1L; private final Type[] actualTypeArguments; private final Type ownerType; private final Type rawType; /** * 构造 * * @param actualTypeArguments 实际的泛型参数类型 * @param ownerType 拥有者类型 * @param rawType 原始类型 */ public ParameterizedTypeImpl(Type[] actualTypeArguments, Type ownerType, Type rawType) { this.actualTypeArguments = actualTypeArguments; this.ownerType = ownerType; this.rawType = rawType; } @Override public Type[] getActualTypeArguments() { return actualTypeArguments; } @Override public Type getOwnerType() { return ownerType; } @Override public Type getRawType() { return rawType; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); final Type useOwner = this.ownerType; final Class<?> raw = (Class<?>) this.rawType; if (useOwner == null) { buf.append(raw.getName()); } else { if (useOwner instanceof Class<?>) { buf.append(((Class<?>) useOwner).getName()); } else { buf.append(useOwner.toString()); } buf.append('.').append(raw.getSimpleName()); } appendAllTo(buf.append('<'), ", ", this.actualTypeArguments).append('>'); return buf.toString(); } /** * 追加 {@code types} 到 {@code buf},使用 {@code sep} 分隔 * * @param buf 目标 * @param sep 分隔符 * @param types 加入的类型 * @return {@code buf} */ private static StringBuilder appendAllTo(final StringBuilder buf, final String sep, final Type... types) { if (ArrayUtil.isNotEmpty(types)) { boolean isFirst = true; for (Type type : types) { if (isFirst) { isFirst = false; } else { buf.append(sep); } String typeStr; if(type instanceof Class) { typeStr = ((Class<?>)type).getName(); }else { typeStr = StrUtil.toString(type); } buf.append(typeStr); } } return buf; } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/lang/ParameterizedTypeImpl.java
1,169
package com.blankj.subutil.util; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Log; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.RomUtils; import com.blankj.utilcode.util.Utils; import java.util.List; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/05/20 * desc : utils about app store * </pre> */ public final class AppStoreUtils { private static final String TAG = "AppStoreUtils"; private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending"; /** * 获取跳转到应用商店的 Intent * * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent() { return getAppStoreIntent(Utils.getApp().getPackageName(), false); } /** * 获取跳转到应用商店的 Intent * * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) { return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore); } /** * 获取跳转到应用商店的 Intent * * @param packageName 包名 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName) { return getAppStoreIntent(packageName, false); } /** * 获取跳转到应用商店的 Intent * <p>优先跳转到手机自带的应用市场</p> * * @param packageName 包名 * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) { if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场 Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName); if (samsungAppStoreIntent != null) return samsungAppStoreIntent; } if (RomUtils.isLeeco()) {// 乐视单独处理跳转乐视市场 Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName); if (leecoAppStoreIntent != null) return leecoAppStoreIntent; } Uri uri = Uri.parse("market://details?id=" + packageName); Intent intent = new Intent(); intent.setData(uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfos == null || resolveInfos.size() == 0) { Log.e(TAG, "No app store!"); return null; } Intent googleIntent = null; for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.packageName; if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) { if (AppUtils.isAppSystem(pkgName)) { intent.setPackage(pkgName); return intent; } } else { intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME); googleIntent = intent; } } if (isIncludeGooglePlayStore && googleIntent != null) { return googleIntent; } intent.setPackage(resolveInfos.get(0).activityInfo.packageName); return intent; } private static Intent getSamsungAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main"); intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static Intent getLeecoAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity"); intent.setAction("com.letv.app.appstore.appdetailactivity"); intent.putExtra("packageName", packageName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static int getAvailableIntentSize(final Intent intent) { return Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size(); } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/AppStoreUtils.java
1,170
import java.util.ArrayList; /** * @author Anonymous * @since 2019/11/23 */ /** * public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = * null; * * public TreeNode(int val) { this.val = val; * * } * * } */ public class Solution { private ArrayList<ArrayList<Integer>> res = new ArrayList<>(); /** * 找出二叉树中和为某一值的路径(必须从根节点到叶节点) * * @param root 二叉树的根结点 * @param target 目标值 * @return 结果list */ public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { findPath(root, target, new ArrayList<>()); return res; } private void findPath(TreeNode root, int target, ArrayList<Integer> list) { if (root == null) { return; } list.add(root.val); target -= root.val; if (target == 0 && root.left == null && root.right == null) { res.add(new ArrayList<>(list)); } else { findPath(root.left, target, list); findPath(root.right, target, list); } list.remove(list.size() - 1); } }
geekxh/hello-algorithm
算法读物/剑指offer/34_PathInTree/Solution.java
1,202
/** * File: hash_map.java * Created Time: 2022-12-04 * Author: krahets ([email protected]) */ package chapter_hashing; import java.util.*; import utils.*; public class hash_map { public static void main(String[] args) { /* 初始化哈希表 */ Map<Integer, String> map = new HashMap<>(); /* 添加操作 */ // 在哈希表中添加键值对 (key, value) map.put(12836, "小哈"); map.put(15937, "小啰"); map.put(16750, "小算"); map.put(13276, "小法"); map.put(10583, "小鸭"); System.out.println("\n添加完成后,哈希表为\nKey -> Value"); PrintUtil.printHashMap(map); /* 查询操作 */ // 向哈希表中输入键 key ,得到值 value String name = map.get(15937); System.out.println("\n输入学号 15937 ,查询到姓名 " + name); /* 删除操作 */ // 在哈希表中删除键值对 (key, value) map.remove(10583); System.out.println("\n删除 10583 后,哈希表为\nKey -> Value"); PrintUtil.printHashMap(map); /* 遍历哈希表 */ System.out.println("\n遍历键值对 Key->Value"); for (Map.Entry<Integer, String> kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } System.out.println("\n单独遍历键 Key"); for (int key : map.keySet()) { System.out.println(key); } System.out.println("\n单独遍历值 Value"); for (String val : map.values()) { System.out.println(val); } } }
krahets/hello-algo
codes/java/chapter_hashing/hash_map.java
1,203
package cn.hutool.json; import cn.hutool.core.util.StrUtil; import java.io.Serializable; /** * 用于定义{@code null},与Javascript中null相对应<br> * Java中的{@code null}值在js中表示为undefined。 * * @author Looly */ public class JSONNull implements Serializable { private static final long serialVersionUID = 2633815155870764938L; /** * {@code NULL} 对象用于减少歧义来表示Java 中的{@code null} <br> * {@code NULL.equals(null)} 返回 {@code true}. <br> * {@code NULL.toString()} 返回 {@code "null"}. */ public static final JSONNull NULL = new JSONNull(); /** * A Null object is equal to the null value and to itself. * 对象与其本身和{@code null}值相等 * * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object or null. */ @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object object) { return object == null || (object == this); } /** * Get the "null" string value. * 获得“null”字符串 * * @return The string "null". */ @Override public String toString() { return StrUtil.NULL; } }
dromara/hutool
hutool-json/src/main/java/cn/hutool/json/JSONNull.java
1,206
E tags: Tree, DFS 给一个inputSum, 然后dfs, 找到是否有一条path, 得出的path sum 跟 inputSum 一样. #### DFS - 确定好结尾条件: `is leaf` && `val == sum`. - 每一层减掉node.val, 然后dfs. - 写一写: `root == null => false` 对parent nodes的影响. 这里发现没影响, 所以可以简化成用1个functionDFS. ``` /* Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /* Thoughts: DFS on the function itself, keep subtracting the root.val. when root == null && sum == 0, return true; */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && sum == root.val) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } } ```
awangdev/leet-code
Java/112. Path Sum.java
1,207
import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.toshiba.mwcloud.gs.ColumnInfo; import com.toshiba.mwcloud.gs.Container; import com.toshiba.mwcloud.gs.ContainerInfo; import com.toshiba.mwcloud.gs.GSType; import com.toshiba.mwcloud.gs.GridStore; import com.toshiba.mwcloud.gs.GridStoreFactory; import com.toshiba.mwcloud.gs.Row; public class PutRow { public static void main(String[] args){ try { //=============================================== // クラスタに接続する //=============================================== // 接続情報を指定する (マルチキャスト方式) Properties prop = new Properties(); prop.setProperty("notificationAddress", "239.0.0.1"); prop.setProperty("notificationPort", "31999"); prop.setProperty("clusterName", "myCluster"); prop.setProperty("database", "public"); prop.setProperty("user", "admin"); prop.setProperty("password", "admin"); prop.setProperty("applicationName", "SampleJava"); // GridStoreオブジェクトを生成する GridStore store = GridStoreFactory.getInstance().getGridStore(prop); // コンテナ作成や取得などの操作を行うと、クラスタに接続される store.getContainer("dummyContainer"); //=============================================== // コレクションを作成する //=============================================== ContainerInfo containerInfo = new ContainerInfo(); List<ColumnInfo> columnList = new ArrayList<ColumnInfo>(); columnList.add(new ColumnInfo("id", GSType.INTEGER)); columnList.add(new ColumnInfo("productName", GSType.STRING)); columnList.add(new ColumnInfo("count", GSType.INTEGER)); containerInfo.setColumnInfoList(columnList); containerInfo.setRowKeyAssigned(true); String containerName = "SampleJava_PutRow"; store.putCollection(containerName, containerInfo, false); System.out.println("Create Collection name="+containerName); //=============================================== // ロウを登録する //=============================================== //(1) Containerオブジェクトの取得 Container<?, Row> container = store.getContainer(containerName); if ( container == null ){ throw new Exception("Container not found."); } //(2) 空のロウオブジェクトの作成 Row row = container.createRow(); //(3) ロウオブジェクトにカラム値をセット row.setInteger(0, 0); row.setString(1, "display"); row.setInteger(2, 150); //(4) ロウの登録 container.put(row); System.out.println("Put Row num=1"); //=============================================== // 終了処理 //=============================================== container.close(); store.close(); System.out.println("success!"); } catch ( Exception e ){ e.printStackTrace(); } } }
griddb/griddb
sample/guide/ja/PutRow.java
1,209
package org.nutz.lang; import java.util.ArrayList; import java.util.List; /** * A group of helper functions to counting some ... * * @author zozoh([email protected]) * @author pw */ public abstract class Maths { /** * 返回最大的一个 * * @param nums * 需要比较的数组 * @return 最大值 */ public static int max(int... nums) { return takeOne(new CompareSomeThing() { @Override public boolean compare(int arg0, int arg1) { return arg0 > arg1; } }, nums); } /** * 返回最小的一个 * * @param nums * 需要比较的数组 * @return 最小值 */ public static int min(int... nums) { return takeOne(new CompareSomeThing() { @Override public boolean compare(int arg0, int arg1) { return arg0 < arg1; } }, nums); } private interface CompareSomeThing { public boolean compare(int arg0, int arg1); } private static int takeOne(CompareSomeThing cp, int... nums) { if (null == nums || nums.length == 0) return 0; int re = nums[0]; for (int i = 1; i < nums.length; i++) { if (cp.compare(nums[i], re)) re = nums[i]; } return re; } /** * Convert a binary string to a integer * * @param s * binary string * @return integer */ public static int bit(String s) { return Integer.valueOf(s, 2); } /** * Test current bit is match the given mask at least one bit or not. * * @param bs * integer, bit map * @param mask * another bit map * @return if one of bit value is '1' in mask, and it is also is '1' in bs * return true, else false */ public static boolean isMask(int bs, int mask) { return 0 != (mask & bs); } public static boolean isNoMask(int bs, int mask) { return 0 == (bs & mask); } /** * Test current bit is all match the give mask. * * @param bs * integer, bit map * @param mask * another bit map * @return if all bit value is '1' in mask, and it is also is '1' in bs * return true, else false */ public static boolean isMaskAll(int bs, int mask) { return 0 == ~((~mask) | bs); } /** * Get part of one integer as a new integer * * @param bs * original integer * @param low * the low bit position (inclusive), 0 base * @param high * the high bit position (exclusive), 0 base * @return new integer */ public static int extract(int bs, int low, int high) { bs = bs >> low; int mask = 0; for (int i = 0; i < (high - low); i++) { mask += 1 << i; } return bs & mask; } /** * 获得字符数组的全排列 * * @param arr * 字符数组 * @return 全排列 */ public static String[] permutation(char... arr) { return permutation(arr.length, arr); } /** * 按照指定长度, 获得字符数组的全排列 * * @param arr * 字符数组 * @return 全排列 */ public static String[] permutation(int length, char... arr) { if (arr == null || arr.length == 0 || length <= 0 || length > arr.length) { return null; } List<String> slist = new ArrayList<String>(); char[] b = new char[length]; // 辅助空间,保存待输出组合数 getCombination(slist, arr, length, 0, b, 0); return slist.toArray(new String[]{}); } /** * 坐标点旋转计算方法。 * * 坐标点(x1,y1)绕另一个坐标点(x2,y2)旋转角度(a)后的新坐标 * * * @param x1 * 被计算点横坐标 * @param y1 * 被计算点纵坐标 * @param x2 * 圆心横坐标 * @param y2 * 圆心纵坐标 * @param a * 角度 * @return (x3,y3) */ public static int[] rotateXY(int x1, int y1, int x2, int y2, double a) { double l = (a * Math.PI) / 180; double cosv = Math.cos(l); double sinv = Math.sin(l); int newX = (int) ((x1 - x2) * cosv - (y1 - y2) * sinv + x2); int newY = (int) ((x1 - x2) * sinv + (y1 - y2) * cosv + y2); return new int[]{newX, newY}; } // --------------------------- 以下为几个辅助方法 private static void getCombination(List<String> slist, char[] a, int n, int begin, char[] b, int index) { if (n == 0) {// 如果够n个数了,输出b数组 getAllPermutation(slist, b, 0);// 得到b的全排列 return; } for (int i = begin; i < a.length; i++) { b[index] = a[i]; getCombination(slist, a, n - 1, i + 1, b, index + 1); } } private static void getAllPermutation(List<String> slist, char[] a, int index) { /* 与a的元素个数相同则输出 */ if (index == a.length - 1) { slist.add(String.valueOf(a)); return; } for (int i = index; i < a.length; i++) { swap(a, index, i); getAllPermutation(slist, a, index + 1); swap(a, index, i); } } private static void swap(char[] arr, int i, int j) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
nutzam/nutz
src/org/nutz/lang/Maths.java
1,214
package com.alibaba.druid.filter.mysql8datetime; import com.alibaba.druid.filter.FilterAdapter; import com.alibaba.druid.filter.FilterChain; import com.alibaba.druid.proxy.jdbc.ResultSetProxy; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Timestamp; import java.time.LocalDateTime; /** * 针对mysql jdbc 8.0.23及以上版本,如果调用方没有使用orm框架,而是直接调用ResultSet的getObject方法,则针对DATETIME类型的字段,得到的对象从TimeStamp类型变成了LocalDateTime类型,导致调用方出现类型转换异常 * 通过Filter控制将对象类型转换成原来的类型 * * @author lizongbo * @see <a href="https://dev.mysql.com/doc/relnotes/connector-j/8.0/en/news-8-0-23.html">MySQL 8.0.23 更新说明</a> */ public class MySQL8DateTimeSqlTypeFilter extends FilterAdapter { /** * 针对mysql jdbc 8.0.23及以上版本,通过该方法控制将对象类型转换成原来的类型 * * @param chain chain the FilterChain object that represents the filter chain * @param result the ResultSetProxy object that represents the result set * @param columnIndex the index of the column to retrieve * @return an Object holding the column value, or {@code null} if the value is SQL NULL * @throws SQLException if a database access error occurs or the columnIndex is invalid * @see java.sql.ResultSet#getObject(int) */ @Override public Object resultSet_getObject(FilterChain chain, ResultSetProxy result, int columnIndex) throws SQLException { return getObjectReplaceLocalDateTime(super.resultSet_getObject(chain, result, columnIndex)); } /** * 针对mysql jdbc 8.0.23及以上版本,通过该方法控制将对象类型转换成原来的类型 * * @param chain chain the FilterChain object that represents the filter chain * @param result the ResultSetProxy object that represents the result set * @param columnLabel the label of the column to retrieve * @return an Object holding the column value, or {@code null} if the value is SQL NULL * @throws SQLException if a database access error occurs or the columnLabel is invalid * @see java.sql.ResultSet#getObject(String) */ @Override public Object resultSet_getObject(FilterChain chain, ResultSetProxy result, String columnLabel) throws SQLException { return getObjectReplaceLocalDateTime(super.resultSet_getObject(chain, result, columnLabel)); } /** * Replaces a LocalDateTime object with its equivalent Timestamp object. * If the input object is not an instance of LocalDateTime, it is returned as is. * This method is specifically designed to handle cases where upgrading to MySQL JDBC 8.0.23 or above * requires converting LocalDateTime objects back to the older compatible type. * * @param obj the object to be checked and possibly replaced * @return the replaced object if it is a LocalDateTime, or the original object otherwise */ public static Object getObjectReplaceLocalDateTime(Object obj) { if (!(obj instanceof LocalDateTime)) { return obj; } // 针对升级到了mysql jdbc 8.0.23以上的情况,转换回老的兼容类型 return Timestamp.valueOf((LocalDateTime) obj); } /** * Retrieves the metadata for the result set, including information about the columns and their properties. * This method wraps the original result set metadata with a custom implementation that handles MySQL 8.0.23 or above * compatibility for LocalDateTime objects. * * @param chain the FilterChain object that represents the filter chain * @param resultSet the ResultSetProxy object that represents the result set * @return a ResultSetMetaData object containing the metadata for the result set * @throws SQLException if a database access error occurs */ @Override public ResultSetMetaData resultSet_getMetaData(FilterChain chain, ResultSetProxy resultSet) throws SQLException { return new MySQL8DateTimeResultSetMetaData(chain.resultSet_getMetaData(resultSet)); } }
alibaba/druid
core/src/main/java/com/alibaba/druid/filter/mysql8datetime/MySQL8DateTimeSqlTypeFilter.java
1,215
/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.config; import cn.hutool.core.lang.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import reactor.util.annotation.Nullable; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * @author Zheng Jie * @date 2018-11-24 */ @Slf4j @Configuration @EnableCaching @ConditionalOnClass(RedisOperations.class) @EnableConfigurationProperties(RedisProperties.class) public class RedisConfig extends CachingConfigurerSupport { /** * 设置 redis 数据默认过期时间,默认2小时 * 设置@cacheable 序列化方式 */ @Bean public RedisCacheConfiguration redisCacheConfiguration(){ FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); configuration = configuration.serializeValuesWith(RedisSerializationContext. SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2)); return configuration; } @SuppressWarnings("all") @Bean(name = "redisTemplate") @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); //序列化 FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); // value值的序列化采用fastJsonRedisSerializer template.setValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer); // fastjson 升级到 1.2.83 后需要指定序列化白名单 ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto"); // 模块内的实体类 ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.mnt.domain"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain"); // 模块内的 Dto ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.mnt.service.dto"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.service.dto"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.service.dto"); ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto"); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } /** * 自定义缓存key生成策略,默认将使用该策略 */ @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { Map<String,Object> container = new HashMap<>(8); Class<?> targetClassClass = target.getClass(); // 类地址 container.put("class",targetClassClass.toGenericString()); // 方法名称 container.put("methodName",method.getName()); // 包名称 container.put("package",targetClassClass.getPackage()); // 参数列表 for (int i = 0; i < params.length; i++) { container.put(String.valueOf(i),params[i]); } // 转为JSON字符串 String jsonString = JSON.toJSONString(container); // 做SHA256 Hash计算,得到一个SHA256摘要作为Key return DigestUtils.sha256Hex(jsonString); }; } @Bean @Override @SuppressWarnings({"all"}) public CacheErrorHandler errorHandler() { // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { log.error("Redis occur handleCacheGetError:key -> [{}]", key, e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.error("Redis occur handleCacheClearError:", e); } }; } } /** * Value 序列化 * * @author / * @param <T> */ class FastJsonRedisSerializer<T> implements RedisSerializer<T> { private final Class<T> clazz; FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8); } @Override public T deserialize(byte[] bytes) { if (bytes == null || bytes.length == 0) { return null; } String str = new String(bytes, StandardCharsets.UTF_8); return JSON.parseObject(str, clazz); } } /** * 重写序列化器 * * @author / */ class StringRedisSerializer implements RedisSerializer<Object> { private final Charset charset; StringRedisSerializer() { this(StandardCharsets.UTF_8); } private StringRedisSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public String deserialize(byte[] bytes) { return (bytes == null ? null : new String(bytes, charset)); } @Override public @Nullable byte[] serialize(Object object) { String string = JSON.toJSONString(object); if (org.apache.commons.lang3.StringUtils.isBlank(string)) { return null; } string = string.replace("\"", ""); return string.getBytes(charset); } }
elunez/eladmin
eladmin-common/src/main/java/me/zhengjie/config/RedisConfig.java
1,216
package io.virtualapp.gms; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import com.lody.virtual.client.core.InstallStrategy; import com.lody.virtual.client.core.VirtualCore; import com.lody.virtual.os.VEnvironment; import com.lody.virtual.remote.InstallResult; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import io.virtualapp.R; import io.virtualapp.abs.ui.VUiKit; import io.virtualapp.utils.DialogUtil; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; /** * @author weishu * @date 2018/6/9. */ public class FakeGms { private static final String TAG = "FakeGms"; private static final String GMS_CONFIG_URL = "http://vaexposed.weishu.me/gms.json"; private static final String GMS_PKG = "com.google.android.gms"; private static final String GSF_PKG = "com.google.android.gsf"; private static final String STORE_PKG = "com.android.vending"; private static final String FAKE_GAPPS_PKG = "com.thermatk.android.xf.fakegapps"; private static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void uninstallGms(Activity activity) { if (activity == null) { return; } AlertDialog failDialog = new AlertDialog.Builder(activity, R.style.Theme_AppCompat_DayNight_Dialog_Alert) .setTitle(R.string.uninstall_gms_title) .setMessage(R.string.uninstall_gms_content) .setPositiveButton(R.string.uninstall_gms_ok, ((dialog1, which1) -> { ProgressDialog dialog = new ProgressDialog(activity); dialog.show(); VUiKit.defer().when(() -> { VirtualCore.get().uninstallPackage(GMS_PKG); VirtualCore.get().uninstallPackage(GSF_PKG); VirtualCore.get().uninstallPackage(STORE_PKG); VirtualCore.get().uninstallPackage(FAKE_GAPPS_PKG); }).then((v) -> { dialog.dismiss(); AlertDialog hits = new AlertDialog.Builder(activity, R.style.Theme_AppCompat_DayNight_Dialog_Alert) .setTitle(R.string.uninstall_gms_title) .setMessage(R.string.uninstall_gms_success) .setPositiveButton(android.R.string.ok, null) .create(); DialogUtil.showDialog(hits); }).fail((v) -> { dialog.dismiss(); }); })) .setNegativeButton(android.R.string.cancel, null) .create(); DialogUtil.showDialog(failDialog); } public static boolean isAlreadyInstalled(Context context) { if (context == null) { return false; } boolean alreadyInstalled = true; if (!VirtualCore.get().isAppInstalled(GMS_PKG)) { alreadyInstalled = false; } if (!VirtualCore.get().isAppInstalled(GSF_PKG)) { alreadyInstalled = false; } if (!VirtualCore.get().isAppInstalled(STORE_PKG)) { alreadyInstalled = false; } if (!VirtualCore.get().isAppInstalled(FAKE_GAPPS_PKG)) { alreadyInstalled = false; } return alreadyInstalled; } public static void installGms(Activity activity) { if (activity == null) { return; } AlertDialog alertDialog = new AlertDialog.Builder(activity, R.style.Theme_AppCompat_DayNight_Dialog_Alert) .setTitle(R.string.install_gms_title) .setMessage(R.string.install_gms_content) .setPositiveButton(android.R.string.ok, ((dialog, which) -> { // show a loading dialog and start install gms. ProgressDialog progressDialog = new ProgressDialog(activity); progressDialog.setCancelable(false); progressDialog.show(); executorService.submit(() -> { String failMsg = installGmsInternal(activity, progressDialog); Log.i(TAG, "install gms result: " + failMsg); try { progressDialog.dismiss(); } catch (Throwable e) { e.printStackTrace(); } if (failMsg == null) { activity.runOnUiThread(() -> { AlertDialog failDialog = new AlertDialog.Builder(activity, R.style.Theme_AppCompat_DayNight_Dialog_Alert) .setTitle(R.string.install_gms_title) .setMessage(R.string.install_gms_success) .setPositiveButton(android.R.string.ok, null) .create(); DialogUtil.showDialog(failDialog); }); } else { activity.runOnUiThread(() -> { AlertDialog failDialog = new AlertDialog.Builder(activity, R.style.Theme_AppCompat_DayNight_Dialog_Alert) .setTitle(R.string.install_gms_fail_title) .setMessage(R.string.install_gms_fail_content) .setPositiveButton(R.string.install_gms_fail_ok, ((dialog1, which1) -> { try { Intent t = new Intent(Intent.ACTION_VIEW); t.setData(Uri.parse("https://github.com/android-hacker/VirtualXposed/wiki/Google-service-support")); activity.startActivity(t); } catch (Throwable ignored) { ignored.printStackTrace(); } })) .setNegativeButton(android.R.string.cancel, null) .create(); DialogUtil.showDialog(failDialog); }); } }); })) .setNegativeButton(android.R.string.cancel, null) .create(); DialogUtil.showDialog(alertDialog); } private static String installGmsInternal(Activity activity, ProgressDialog dialog) { File cacheDir = activity.getCacheDir(); // 下载配置文件,得到各自的URL OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(GMS_CONFIG_URL) .build(); updateMessage(activity, dialog, "Fetching gms config..."); Response response; try { response = client.newCall(request).execute(); } catch (IOException e) { return "Download gms config failed, please check your network, error: 0"; } if (!response.isSuccessful()) { return "Download gms config failed, please check your network, error: 1"; } Log.i(TAG, "response success: " + response.code()); if (200 != response.code()) { return "Download gms config failed, please check your network, error: 2"; } updateMessage(activity, dialog, "Parsing gms config..."); ResponseBody body = response.body(); if (body == null) { return "Download gms config failed, please check your network, error: 3"; } String string = null; try { string = body.string(); } catch (IOException e) { return "Download gms config failed, please check your network, error: 4"; } JSONObject jsonObject = null; try { jsonObject = new JSONObject(string); } catch (JSONException e) { return "Download gms config failed, please check your network, error: 5"; } String gmsCoreUrl = null; try { gmsCoreUrl = jsonObject.getString("gms"); } catch (JSONException e) { return "Download gms config failed, please check your network, error: 6"; } String gmsServiceUrl = null; try { gmsServiceUrl = jsonObject.getString("gsf"); } catch (JSONException e) { return "Download gms config failed, please check your network, error: 7"; } String storeUrl = null; try { storeUrl = jsonObject.getString("store"); } catch (JSONException e) { return "Download gms config failed, please check your network, error: 8"; } String fakeGappsUrl = null; try { fakeGappsUrl = jsonObject.getString("fakegapps"); } catch (JSONException e) { return "Download gms config failed, please check your network, error: 9"; } String yalpStoreUrl = null; try { yalpStoreUrl = jsonObject.getString("yalp"); } catch (JSONException e) { // ignore. Log.i(TAG, "Download gms config failed, please check your network"); } updateMessage(activity, dialog, "config parse success!"); File gmsCoreFile = new File(cacheDir, "gms.apk"); File gmsServiceFile = new File(cacheDir, "gsf.apk"); File storeFile = new File(cacheDir, "store.apk"); File fakeGappsFile = new File(cacheDir, "fakegapps.apk"); File yalpStoreFile = new File(cacheDir, "yalpStore.apk"); // clear old files. if (gmsCoreFile.exists()) { gmsCoreFile.delete(); } if (gmsServiceFile.exists()) { gmsServiceFile.delete(); } if (storeFile.exists()) { storeFile.delete(); } if (fakeGappsFile.exists()) { fakeGappsFile.delete(); } boolean downloadResult = downloadFile(gmsCoreUrl, gmsCoreFile, (progress) -> updateMessage(activity, dialog, "download gms core..." + progress + "%")); if (!downloadResult) { return "Download gms config failed, please check your network, error: 10"; } downloadResult = downloadFile(gmsServiceUrl, gmsServiceFile, (progress -> updateMessage(activity, dialog, "download gms service framework proxy.." + progress + "%"))); if (!downloadResult) { return "Download gms config failed, please check your network, error: 11"; } updateMessage(activity, dialog, "download gms store..."); downloadResult = downloadFile(storeUrl, storeFile, (progress -> updateMessage(activity, dialog, "download gms store.." + progress + "%"))); if (!downloadResult) { return "Download gms config failed, please check your network, error: 12"; } downloadResult = downloadFile(fakeGappsUrl, fakeGappsFile, (progress -> updateMessage(activity, dialog, "download gms Xposed module.." + progress + "%"))); if (!downloadResult) { return "Download gms config failed, please check your network, error: 13"; } if (yalpStoreUrl != null) { downloadFile(yalpStoreUrl,yalpStoreFile, (progress -> updateMessage(activity, dialog, "download yalp store.." + progress + "%"))); } updateMessage(activity, dialog, "installing gms core"); InstallResult installResult = VirtualCore.get().installPackage(gmsCoreFile.getAbsolutePath(), InstallStrategy.UPDATE_IF_EXIST); if (!installResult.isSuccess) { return "install gms core failed: " + installResult.error; } updateMessage(activity, dialog, "installing gms service framework..."); installResult = VirtualCore.get().installPackage(gmsServiceFile.getAbsolutePath(), InstallStrategy.UPDATE_IF_EXIST); if (!installResult.isSuccess) { return "install gms service framework failed: " + installResult.error; } updateMessage(activity, dialog, "installing gms store..."); installResult = VirtualCore.get().installPackage(storeFile.getAbsolutePath(), InstallStrategy.UPDATE_IF_EXIST); if (!installResult.isSuccess) { return "install gms store failed: " + installResult.error; } updateMessage(activity, dialog, "installing gms Xposed module..."); installResult = VirtualCore.get().installPackage(fakeGappsFile.getAbsolutePath(), InstallStrategy.UPDATE_IF_EXIST); if (!installResult.isSuccess) { return "install gms xposed module failed: " + installResult.error; } if (yalpStoreFile.exists()) { updateMessage(activity, dialog, "installing yalp store..."); VirtualCore.get().installPackage(yalpStoreFile.getAbsolutePath(), InstallStrategy.UPDATE_IF_EXIST); } // Enable the Xposed module. File dataDir = VEnvironment.getDataUserPackageDirectory(0, "de.robv.android.xposed.installer"); File modulePath = VEnvironment.getPackageResourcePath(FAKE_GAPPS_PKG); File configDir = new File(dataDir, "exposed_conf" + File.separator + "modules.list"); FileWriter writer = null; try { writer = new FileWriter(configDir, true); writer.append(modulePath.getAbsolutePath()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } // success!!! return null; } private static void updateMessage(Activity activity, ProgressDialog dialog, String msg) { if (activity == null || dialog == null || TextUtils.isEmpty(msg)) { return; } Log.i(TAG, "update dialog message: " + msg); activity.runOnUiThread(() -> { dialog.setMessage(msg); }); } public interface DownloadListener { void onProgress(int progress); } public static boolean downloadFile(String url, File outFile, DownloadListener listener) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); FileOutputStream fos = null; try { Response response = client.newCall(request).execute(); if (response.code() != 200) { return false; } ResponseBody body = response.body(); if (body == null) { return false; } long toal = body.contentLength(); long sum = 0; InputStream inputStream = body.byteStream(); fos = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int count = 0; while ((count = inputStream.read(buffer)) >= 0) { fos.write(buffer, 0, count); sum += count; int progress = (int) ((sum * 1.0) / toal * 100); if (listener != null) { listener.onProgress(progress); } } fos.flush(); return true; } catch (IOException e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
android-hacker/VirtualXposed
VirtualApp/app/src/main/java/io/virtualapp/gms/FakeGms.java
1,220
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class OmsOrder implements Serializable { @ApiModelProperty(value = "订单id") private Long id; private Long memberId; private Long couponId; @ApiModelProperty(value = "订单编号") private String orderSn; @ApiModelProperty(value = "提交时间") private Date createTime; @ApiModelProperty(value = "用户帐号") private String memberUsername; @ApiModelProperty(value = "订单总金额") private BigDecimal totalAmount; @ApiModelProperty(value = "应付金额(实际支付金额)") private BigDecimal payAmount; @ApiModelProperty(value = "运费金额") private BigDecimal freightAmount; @ApiModelProperty(value = "促销优化金额(促销价、满减、阶梯价)") private BigDecimal promotionAmount; @ApiModelProperty(value = "积分抵扣金额") private BigDecimal integrationAmount; @ApiModelProperty(value = "优惠券抵扣金额") private BigDecimal couponAmount; @ApiModelProperty(value = "管理员后台调整订单使用的折扣金额") private BigDecimal discountAmount; @ApiModelProperty(value = "支付方式:0->未支付;1->支付宝;2->微信") private Integer payType; @ApiModelProperty(value = "订单来源:0->PC订单;1->app订单") private Integer sourceType; @ApiModelProperty(value = "订单状态:0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单") private Integer status; @ApiModelProperty(value = "订单类型:0->正常订单;1->秒杀订单") private Integer orderType; @ApiModelProperty(value = "物流公司(配送方式)") private String deliveryCompany; @ApiModelProperty(value = "物流单号") private String deliverySn; @ApiModelProperty(value = "自动确认时间(天)") private Integer autoConfirmDay; @ApiModelProperty(value = "可以获得的积分") private Integer integration; @ApiModelProperty(value = "可以活动的成长值") private Integer growth; @ApiModelProperty(value = "活动信息") private String promotionInfo; @ApiModelProperty(value = "发票类型:0->不开发票;1->电子发票;2->纸质发票") private Integer billType; @ApiModelProperty(value = "发票抬头") private String billHeader; @ApiModelProperty(value = "发票内容") private String billContent; @ApiModelProperty(value = "收票人电话") private String billReceiverPhone; @ApiModelProperty(value = "收票人邮箱") private String billReceiverEmail; @ApiModelProperty(value = "收货人姓名") private String receiverName; @ApiModelProperty(value = "收货人电话") private String receiverPhone; @ApiModelProperty(value = "收货人邮编") private String receiverPostCode; @ApiModelProperty(value = "省份/直辖市") private String receiverProvince; @ApiModelProperty(value = "城市") private String receiverCity; @ApiModelProperty(value = "区") private String receiverRegion; @ApiModelProperty(value = "详细地址") private String receiverDetailAddress; @ApiModelProperty(value = "订单备注") private String note; @ApiModelProperty(value = "确认收货状态:0->未确认;1->已确认") private Integer confirmStatus; @ApiModelProperty(value = "删除状态:0->未删除;1->已删除") private Integer deleteStatus; @ApiModelProperty(value = "下单时使用的积分") private Integer useIntegration; @ApiModelProperty(value = "支付时间") private Date paymentTime; @ApiModelProperty(value = "发货时间") private Date deliveryTime; @ApiModelProperty(value = "确认收货时间") private Date receiveTime; @ApiModelProperty(value = "评价时间") private Date commentTime; @ApiModelProperty(value = "修改时间") private Date modifyTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getCouponId() { return couponId; } public void setCouponId(Long couponId) { this.couponId = couponId; } public String getOrderSn() { return orderSn; } public void setOrderSn(String orderSn) { this.orderSn = orderSn; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getMemberUsername() { return memberUsername; } public void setMemberUsername(String memberUsername) { this.memberUsername = memberUsername; } public BigDecimal getTotalAmount() { return totalAmount; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } public BigDecimal getPayAmount() { return payAmount; } public void setPayAmount(BigDecimal payAmount) { this.payAmount = payAmount; } public BigDecimal getFreightAmount() { return freightAmount; } public void setFreightAmount(BigDecimal freightAmount) { this.freightAmount = freightAmount; } public BigDecimal getPromotionAmount() { return promotionAmount; } public void setPromotionAmount(BigDecimal promotionAmount) { this.promotionAmount = promotionAmount; } public BigDecimal getIntegrationAmount() { return integrationAmount; } public void setIntegrationAmount(BigDecimal integrationAmount) { this.integrationAmount = integrationAmount; } public BigDecimal getCouponAmount() { return couponAmount; } public void setCouponAmount(BigDecimal couponAmount) { this.couponAmount = couponAmount; } public BigDecimal getDiscountAmount() { return discountAmount; } public void setDiscountAmount(BigDecimal discountAmount) { this.discountAmount = discountAmount; } public Integer getPayType() { return payType; } public void setPayType(Integer payType) { this.payType = payType; } public Integer getSourceType() { return sourceType; } public void setSourceType(Integer sourceType) { this.sourceType = sourceType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getOrderType() { return orderType; } public void setOrderType(Integer orderType) { this.orderType = orderType; } public String getDeliveryCompany() { return deliveryCompany; } public void setDeliveryCompany(String deliveryCompany) { this.deliveryCompany = deliveryCompany; } public String getDeliverySn() { return deliverySn; } public void setDeliverySn(String deliverySn) { this.deliverySn = deliverySn; } public Integer getAutoConfirmDay() { return autoConfirmDay; } public void setAutoConfirmDay(Integer autoConfirmDay) { this.autoConfirmDay = autoConfirmDay; } public Integer getIntegration() { return integration; } public void setIntegration(Integer integration) { this.integration = integration; } public Integer getGrowth() { return growth; } public void setGrowth(Integer growth) { this.growth = growth; } public String getPromotionInfo() { return promotionInfo; } public void setPromotionInfo(String promotionInfo) { this.promotionInfo = promotionInfo; } public Integer getBillType() { return billType; } public void setBillType(Integer billType) { this.billType = billType; } public String getBillHeader() { return billHeader; } public void setBillHeader(String billHeader) { this.billHeader = billHeader; } public String getBillContent() { return billContent; } public void setBillContent(String billContent) { this.billContent = billContent; } public String getBillReceiverPhone() { return billReceiverPhone; } public void setBillReceiverPhone(String billReceiverPhone) { this.billReceiverPhone = billReceiverPhone; } public String getBillReceiverEmail() { return billReceiverEmail; } public void setBillReceiverEmail(String billReceiverEmail) { this.billReceiverEmail = billReceiverEmail; } public String getReceiverName() { return receiverName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } public String getReceiverPhone() { return receiverPhone; } public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; } public String getReceiverPostCode() { return receiverPostCode; } public void setReceiverPostCode(String receiverPostCode) { this.receiverPostCode = receiverPostCode; } public String getReceiverProvince() { return receiverProvince; } public void setReceiverProvince(String receiverProvince) { this.receiverProvince = receiverProvince; } public String getReceiverCity() { return receiverCity; } public void setReceiverCity(String receiverCity) { this.receiverCity = receiverCity; } public String getReceiverRegion() { return receiverRegion; } public void setReceiverRegion(String receiverRegion) { this.receiverRegion = receiverRegion; } public String getReceiverDetailAddress() { return receiverDetailAddress; } public void setReceiverDetailAddress(String receiverDetailAddress) { this.receiverDetailAddress = receiverDetailAddress; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getConfirmStatus() { return confirmStatus; } public void setConfirmStatus(Integer confirmStatus) { this.confirmStatus = confirmStatus; } public Integer getDeleteStatus() { return deleteStatus; } public void setDeleteStatus(Integer deleteStatus) { this.deleteStatus = deleteStatus; } public Integer getUseIntegration() { return useIntegration; } public void setUseIntegration(Integer useIntegration) { this.useIntegration = useIntegration; } public Date getPaymentTime() { return paymentTime; } public void setPaymentTime(Date paymentTime) { this.paymentTime = paymentTime; } public Date getDeliveryTime() { return deliveryTime; } public void setDeliveryTime(Date deliveryTime) { this.deliveryTime = deliveryTime; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date receiveTime) { this.receiveTime = receiveTime; } public Date getCommentTime() { return commentTime; } public void setCommentTime(Date commentTime) { this.commentTime = commentTime; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberId=").append(memberId); sb.append(", couponId=").append(couponId); sb.append(", orderSn=").append(orderSn); sb.append(", createTime=").append(createTime); sb.append(", memberUsername=").append(memberUsername); sb.append(", totalAmount=").append(totalAmount); sb.append(", payAmount=").append(payAmount); sb.append(", freightAmount=").append(freightAmount); sb.append(", promotionAmount=").append(promotionAmount); sb.append(", integrationAmount=").append(integrationAmount); sb.append(", couponAmount=").append(couponAmount); sb.append(", discountAmount=").append(discountAmount); sb.append(", payType=").append(payType); sb.append(", sourceType=").append(sourceType); sb.append(", status=").append(status); sb.append(", orderType=").append(orderType); sb.append(", deliveryCompany=").append(deliveryCompany); sb.append(", deliverySn=").append(deliverySn); sb.append(", autoConfirmDay=").append(autoConfirmDay); sb.append(", integration=").append(integration); sb.append(", growth=").append(growth); sb.append(", promotionInfo=").append(promotionInfo); sb.append(", billType=").append(billType); sb.append(", billHeader=").append(billHeader); sb.append(", billContent=").append(billContent); sb.append(", billReceiverPhone=").append(billReceiverPhone); sb.append(", billReceiverEmail=").append(billReceiverEmail); sb.append(", receiverName=").append(receiverName); sb.append(", receiverPhone=").append(receiverPhone); sb.append(", receiverPostCode=").append(receiverPostCode); sb.append(", receiverProvince=").append(receiverProvince); sb.append(", receiverCity=").append(receiverCity); sb.append(", receiverRegion=").append(receiverRegion); sb.append(", receiverDetailAddress=").append(receiverDetailAddress); sb.append(", note=").append(note); sb.append(", confirmStatus=").append(confirmStatus); sb.append(", deleteStatus=").append(deleteStatus); sb.append(", useIntegration=").append(useIntegration); sb.append(", paymentTime=").append(paymentTime); sb.append(", deliveryTime=").append(deliveryTime); sb.append(", receiveTime=").append(receiveTime); sb.append(", commentTime=").append(commentTime); sb.append(", modifyTime=").append(modifyTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/OmsOrder.java
1,224
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.itcast_02; import javax.swing.JOptionPane; /** * * @author fqy */ public class OperatorJFrame extends javax.swing.JFrame { /** * Creates new form OperatorJFrame */ public OperatorJFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); firstNumber = new javax.swing.JTextField(); choiceOperator = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); secondNumber = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); resultNumber = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jiSuanButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("第一个操作数"); choiceOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-", "*", "/" })); jLabel2.setText("第二个操作数"); jLabel3.setText("="); jLabel4.setText("结果"); jiSuanButton.setText("计算"); jiSuanButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jiSuanButtonMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(firstNumber)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jiSuanButton) .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(firstNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jiSuanButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jiSuanButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jiSuanButtonMouseClicked /* 思路: 1:获取操作数和运算符 2:根据运算符,进行相应的运算 3:把运算的结果赋值给最后一个文本框 */ String firstNumberString = this.firstNumber.getText(); String operatorString = String.valueOf(this.choiceOperator.getSelectedItem()); String secondNumberString = this.secondNumber.getText(); //加入数据校验 String regex = "\\d+"; if (!firstNumberString.matches(regex)) { // System.out.println("你输入的数据有误"); //弹出一个框框 // public static void showMessageDialog(Component parentComponent,Object message) JOptionPane.showMessageDialog(this, "第一个操作数不是数字"); this.firstNumber.setText(""); //获得焦点 this.firstNumber.requestFocus(); return; } if (!secondNumberString.matches(regex)) { JOptionPane.showMessageDialog(this, "第二个操作数不是数字"); this.secondNumber.setText(""); //获得焦点 this.secondNumber.requestFocus(); return; } //把字符串转换为数据类型 int firstNumber = Integer.parseInt(firstNumberString); int secondNumber = Integer.parseInt(secondNumberString); //定义变量,用于保存运算的结果 int result = 0; switch (operatorString) { case "+": result = firstNumber + secondNumber; break; case "-": result = firstNumber - secondNumber; break; case "*": result = firstNumber * secondNumber; break; case "/": if (secondNumber == 0) { JOptionPane.showMessageDialog(this, "除数不能为0"); //获得焦点 this.secondNumber.requestFocus(); return; } else { result = firstNumber / secondNumber; } break; } //把运算的结果赋值给最后一个文本框 this.resultNumber.setText(String.valueOf(result)); }//GEN-LAST:event_jiSuanButtonMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new OperatorJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox choiceOperator; private javax.swing.JTextField firstNumber; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JButton jiSuanButton; private javax.swing.JTextField resultNumber; private javax.swing.JTextField secondNumber; // End of variables declaration//GEN-END:variables }
DuGuQiuBai/Java
day25/code/四则运算/src/cn/itcast_02/OperatorJFrame.java
1,226
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.itcast_03; import cn.itcast.util.MyLookAndFeel; import cn.itcast.util.UiUtil; import cn.itcast_02.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author fqy */ public class OperatorJFrame extends javax.swing.JFrame { /** * Creates new form OperatorJFrame */ public OperatorJFrame() { initComponents(); init(); } private void init() { this.setTitle("模拟四则运算"); UiUtil.setFrameIcon(this, "src\\cn\\itcast\\resource\\jjcc.jpg"); UiUtil.setFrameCenter(this); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); firstNumber = new javax.swing.JTextField(); choiceOperator = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); secondNumber = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); resultNumber = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jiSuanButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("第一个操作数"); choiceOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-", "*", "/" })); jLabel2.setText("第二个操作数"); jLabel3.setText("="); jLabel4.setText("结果"); jiSuanButton.setText("计算"); jiSuanButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jiSuanButtonMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(firstNumber)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jiSuanButton) .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(firstNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jiSuanButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jiSuanButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jiSuanButtonMouseClicked /* 思路: 1:获取操作数和运算符 2:根据运算符,进行相应的运算 3:把运算的结果赋值给最后一个文本框 */ String firstNumberString = this.firstNumber.getText(); String operatorString = String.valueOf(this.choiceOperator.getSelectedItem()); String secondNumberString = this.secondNumber.getText(); //加入数据校验 String regex = "\\d+"; if (!firstNumberString.matches(regex)) { // System.out.println("你输入的数据有误"); //弹出一个框框 // public static void showMessageDialog(Component parentComponent,Object message) JOptionPane.showMessageDialog(this, "第一个操作数不是数字"); this.firstNumber.setText(""); //获得焦点 this.firstNumber.requestFocus(); return; } if (!secondNumberString.matches(regex)) { JOptionPane.showMessageDialog(this, "第二个操作数不是数字"); this.secondNumber.setText(""); //获得焦点 this.secondNumber.requestFocus(); return; } //把字符串转换为数据类型 int firstNumber = Integer.parseInt(firstNumberString); int secondNumber = Integer.parseInt(secondNumberString); //定义变量,用于保存运算的结果 int result = 0; switch (operatorString) { case "+": result = firstNumber + secondNumber; break; case "-": result = firstNumber - secondNumber; break; case "*": result = firstNumber * secondNumber; break; case "/": if (secondNumber == 0) { JOptionPane.showMessageDialog(this, "除数不能为0"); //获得焦点 this.secondNumber.requestFocus(); return; } else { result = firstNumber / secondNumber; } break; } //把运算的结果赋值给最后一个文本框 this.resultNumber.setText(String.valueOf(result)); }//GEN-LAST:event_jiSuanButtonMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> try { //修改皮肤 UIManager.setLookAndFeel(MyLookAndFeel.LIQUIDINF); } catch (ClassNotFoundException ex) { Logger.getLogger(OperatorJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(OperatorJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(OperatorJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(OperatorJFrame.class.getName()).log(Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new OperatorJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox choiceOperator; private javax.swing.JTextField firstNumber; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JButton jiSuanButton; private javax.swing.JTextField resultNumber; private javax.swing.JTextField secondNumber; // End of variables declaration//GEN-END:variables }
DuGuQiuBai/Java
day25/code/四则运算/src/cn/itcast_03/OperatorJFrame.java
1,227
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.common.utils; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; /** * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类 * @author ThinkGem * @version 2014-4-15 */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 得到当前日期字符串 格式(yyyy-MM-dd) */ public static String getDate() { return getDate("yyyy-MM-dd"); } /** * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String getDate(String pattern) { return DateFormatUtils.format(new Date(), pattern); } /** * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String formatDate(Date date, Object... pattern) { String formatDate = null; if (pattern != null && pattern.length > 0) { formatDate = DateFormatUtils.format(date, pattern[0].toString()); } else { formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); } return formatDate; } /** * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss) */ public static String formatDateTime(Date date) { return formatDate(date, "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前时间字符串 格式(HH:mm:ss) */ public static String getTime() { return formatDate(new Date(), "HH:mm:ss"); } /** * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss) */ public static String getDateTime() { return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前年份字符串 格式(yyyy) */ public static String getYear() { return formatDate(new Date(), "yyyy"); } /** * 得到当前月份字符串 格式(MM) */ public static String getMonth() { return formatDate(new Date(), "MM"); } /** * 得到当天字符串 格式(dd) */ public static String getDay() { return formatDate(new Date(), "dd"); } /** * 得到当前星期字符串 格式(E)星期几 */ public static String getWeek() { return formatDate(new Date(), "E"); } /** * 日期型字符串转化为日期 格式 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" } */ public static Date parseDate(Object str) { if (str == null){ return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取过去的天数 * @param date * @return */ public static long pastDays(Date date) { long t = new Date().getTime()-date.getTime(); return t/(24*60*60*1000); } /** * 获取过去的小时 * @param date * @return */ public static long pastHour(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*60*1000); } /** * 获取过去的分钟 * @param date * @return */ public static long pastMinutes(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*1000); } /** * 转换为时间(天,时:分:秒.毫秒) * @param timeMillis * @return */ public static String formatDateTime(long timeMillis){ long day = timeMillis/(24*60*60*1000); long hour = (timeMillis/(60*60*1000)-day*24); long min = ((timeMillis/(60*1000))-day*24*60-hour*60); long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60); long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000); return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss; } /** * 获取两个日期之间的天数 * * @param before * @param after * @return */ public static double getDistanceOfTwoDate(Date before, Date after) { long beforeTime = before.getTime(); long afterTime = after.getTime(); return (afterTime - beforeTime) / (1000 * 60 * 60 * 24); } /** * 获取过去第几天的日期 * * @param past * @return */ public static String getPastDate(int past) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past); Date today = calendar.getTime(); String result = formatDate(today, "yyyyMMdd") ; return result; } /** * 获取未来 第 past 天的日期 * @param past * @return */ public static String getFetureDate(int past) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past); Date today = calendar.getTime(); String result = formatDate(today, "yyyyMMdd") ; return result; } /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // System.out.println(formatDate(parseDate("2010/3/6"))); // System.out.println(getDate("yyyy年MM月dd日 E")); // long time = new Date().getTime()-parseDate("2012-11-19").getTime(); // System.out.println(time/(24*60*60*1000)); } }
thinkgem/jeesite
src/main/java/com/thinkgem/jeesite/common/utils/DateUtils.java
1,229
/* * Copyright 2016 jeasonlzy(廖子尧) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lzy.demo.utils; import android.content.Context; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/8/17 * 描 述: * 修订历史: * ================================================ */ public class AnimHelper { private AnimHelper() { throw new RuntimeException("AnimHelper cannot be initialized!"); } public static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator(); public static final int DURATION = 300; public static void scaleShow(View view, ViewPropertyAnimatorListener listener) { ViewCompat.animate(view).scaleX(1.0f).scaleY(1.0f).alpha(1.0f).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static void scaleHide(View view, ViewPropertyAnimatorListener listener) { ViewCompat.animate(view).scaleX(0f).scaleY(0f).alpha(0f).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static void alphaShow(View view, ViewPropertyAnimatorListener listener) { ViewCompat.animate(view).alpha(1.0f).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static void alphaHide(View view, ViewPropertyAnimatorListener listener) { ViewCompat.animate(view).alpha(0f).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static void translateUp(View view, ViewPropertyAnimatorListener listener) { ViewCompat.animate(view).translationY(0).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static void translateDown(View view, ViewPropertyAnimatorListener listener) { int height = view.getHeight(); ViewGroup.LayoutParams params = view.getLayoutParams(); ViewGroup.MarginLayoutParams layoutParams = params instanceof ViewGroup.MarginLayoutParams ? ((ViewGroup.MarginLayoutParams) params) : null; if (layoutParams != null) height += layoutParams.bottomMargin; ViewCompat.animate(view).translationY(height).setDuration(DURATION).setListener(listener).setInterpolator(INTERPOLATOR).withLayer().start(); } public static float floatEvaluator(float originalSize, float finalSize, float percent) { return (finalSize - originalSize) * percent + originalSize; } public static int argbEvaluator(int startColor, int endColor, float percent) { int startA = (startColor >> 24) & 0xff; int startR = (startColor >> 16) & 0xff; int startG = (startColor >> 8) & 0xff; int startB = startColor & 0xff; int endA = (endColor >> 24) & 0xff; int endR = (endColor >> 16) & 0xff; int endG = (endColor >> 8) & 0xff; int endB = endColor & 0xff; return ((startA + (int) (percent * (endA - startA))) << 24) | ((startR + (int) (percent * (endR - startR))) << 16) | ((startG + (int) (percent * (endG - startG))) << 8) | ((startB + (int) (percent * (endB - startB)))); } public static float scaleEvaluator(float originalSize, float finalSize, float percent) { float calcSize = (finalSize - originalSize) * percent + originalSize; return calcSize / originalSize; } /** 获得状态栏的高度 */ public static int getStatusBarHeight(Context context) { int statusHeight = -1; try { Class<?> clazz = Class.forName("com.android.internal.R$dimen"); Object object = clazz.newInstance(); int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString()); statusHeight = context.getResources().getDimensionPixelSize(height); } catch (Exception e) { e.printStackTrace(); } return statusHeight; } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/utils/AnimHelper.java
1,231
package com.alibaba.otter.canal.meta; import java.util.List; import java.util.Map; import com.alibaba.otter.canal.common.CanalLifeCycle; import com.alibaba.otter.canal.meta.exception.CanalMetaManagerException; import com.alibaba.otter.canal.protocol.ClientIdentity; import com.alibaba.otter.canal.protocol.position.Position; import com.alibaba.otter.canal.protocol.position.PositionRange; /** * meta信息管理器 * * @author jianghang 2012-6-14 下午09:28:48 * @author zebin.xuzb * @version 1.0.0 */ public interface CanalMetaManager extends CanalLifeCycle { /** * 增加一个 client订阅 <br/> * 如果 client已经存在,则不做任何修改 */ void subscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 判断是否订阅 */ boolean hasSubscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 取消client订阅 */ void unsubscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 获取 cursor 游标 */ Position getCursor(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 更新 cursor 游标 */ void updateCursor(ClientIdentity clientIdentity, Position position) throws CanalMetaManagerException; /** * 根据指定的destination列出当前所有的clientIdentity信息 */ List<ClientIdentity> listAllSubscribeInfo(String destination) throws CanalMetaManagerException; /** * 获得该client最新的一个位置 */ PositionRange getFirstBatch(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 获得该clientId最新的一个位置 */ PositionRange getLastestBatch(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 为 client 产生一个唯一、递增的id */ Long addBatch(ClientIdentity clientIdentity, PositionRange positionRange) throws CanalMetaManagerException; /** * 指定batchId,插入batch数据 */ void addBatch(ClientIdentity clientIdentity, PositionRange positionRange, Long batchId) throws CanalMetaManagerException; /** * 根据唯一messageId,查找对应的数据起始信息 */ PositionRange getBatch(ClientIdentity clientIdentity, Long batchId) throws CanalMetaManagerException; /** * 对一个batch的确认 */ PositionRange removeBatch(ClientIdentity clientIdentity, Long batchId) throws CanalMetaManagerException; /** * 查询当前的所有batch信息 */ Map<Long, PositionRange> listAllBatchs(ClientIdentity clientIdentity) throws CanalMetaManagerException; /** * 清除对应的batch信息 */ void clearAllBatchs(ClientIdentity clientIdentity) throws CanalMetaManagerException; }
alibaba/canal
meta/src/main/java/com/alibaba/otter/canal/meta/CanalMetaManager.java
1,234
package com.macro.mall.service; import com.macro.mall.dto.UmsAdminParam; import com.macro.mall.dto.UpdateAdminPasswordParam; import com.macro.mall.model.UmsAdmin; import com.macro.mall.model.UmsResource; import com.macro.mall.model.UmsRole; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 后台用户管理Service * Created by macro on 2018/4/26. */ public interface UmsAdminService { /** * 根据用户名获取后台管理员 */ UmsAdmin getAdminByUsername(String username); /** * 注册功能 */ UmsAdmin register(UmsAdminParam umsAdminParam); /** * 登录功能 * @param username 用户名 * @param password 密码 * @return 生成的JWT的token */ String login(String username,String password); /** * 刷新token的功能 * @param oldToken 旧的token */ String refreshToken(String oldToken); /** * 根据用户id获取用户 */ UmsAdmin getItem(Long id); /** * 根据用户名或昵称分页查询用户 */ List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum); /** * 修改指定用户信息 */ int update(Long id, UmsAdmin admin); /** * 删除指定用户 */ int delete(Long id); /** * 修改用户角色关系 */ @Transactional int updateRole(Long adminId, List<Long> roleIds); /** * 获取用户对应角色 */ List<UmsRole> getRoleList(Long adminId); /** * 获取指定用户的可访问资源 */ List<UmsResource> getResourceList(Long adminId); /** * 修改密码 */ int updatePassword(UpdateAdminPasswordParam updatePasswordParam); /** * 获取用户信息 */ UserDetails loadUserByUsername(String username); /** * 获取缓存服务 */ UmsAdminCacheService getCacheService(); /** * 登出功能 * @param username 用户名 */ void logout(String username); }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/UmsAdminService.java
1,235
/** * File: coin_change_greedy.java * Created Time: 2023-07-20 * Author: krahets ([email protected]) */ package chapter_greedy; import java.util.Arrays; public class coin_change_greedy { /* 零钱兑换:贪心 */ static int coinChangeGreedy(int[] coins, int amt) { // 假设 coins 列表有序 int i = coins.length - 1; int count = 0; // 循环进行贪心选择,直到无剩余金额 while (amt > 0) { // 找到小于且最接近剩余金额的硬币 while (i > 0 && coins[i] > amt) { i--; } // 选择 coins[i] amt -= coins[i]; count++; } // 若未找到可行方案,则返回 -1 return amt == 0 ? count : -1; } public static void main(String[] args) { // 贪心:能够保证找到全局最优解 int[] coins = { 1, 5, 10, 20, 50, 100 }; int amt = 186; int res = coinChangeGreedy(coins, amt); System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt); System.out.println("凑到 " + amt + " 所需的最少硬币数量为 " + res); // 贪心:无法保证找到全局最优解 coins = new int[] { 1, 20, 50 }; amt = 60; res = coinChangeGreedy(coins, amt); System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt); System.out.println("凑到 " + amt + " 所需的最少硬币数量为 " + res); System.out.println("实际上需要的最少数量为 3 ,即 20 + 20 + 20"); // 贪心:无法保证找到全局最优解 coins = new int[] { 1, 49, 50 }; amt = 98; res = coinChangeGreedy(coins, amt); System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt); System.out.println("凑到 " + amt + " 所需的最少硬币数量为 " + res); System.out.println("实际上需要的最少数量为 2 ,即 49 + 49"); } }
krahets/hello-algo
codes/java/chapter_greedy/coin_change_greedy.java
1,237
package cn.hutool.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import cn.hutool.aop.aspects.Aspect; import cn.hutool.aop.proxy.ProxyFactory; import cn.hutool.core.util.ClassUtil; /** * 代理工具类 * @author Looly * */ public final class ProxyUtil { /** * 使用切面代理对象 * * @param <T> 切面对象类型 * @param target 目标对象 * @param aspectClass 切面对象类 * @return 代理对象 */ public static <T> T proxy(T target, Class<? extends Aspect> aspectClass){ return ProxyFactory.createProxy(target, aspectClass); } /** * 使用切面代理对象 * * @param <T> 被代理对象类型 * @param target 被代理对象 * @param aspect 切面对象 * @return 代理对象 */ public static <T> T proxy(T target, Aspect aspect){ return ProxyFactory.createProxy(target, aspect); } /** * 创建动态代理对象<br> * 动态代理对象的创建原理是:<br> * 假设创建的代理对象名为 $Proxy0<br> * 1、根据传入的interfaces动态生成一个类,实现interfaces中的接口<br> * 2、通过传入的classloder将刚生成的类加载到jvm中。即将$Proxy0类load<br> * 3、调用$Proxy0的$Proxy0(InvocationHandler)构造函数 创建$Proxy0的对象,并且用interfaces参数遍历其所有接口的方法,这些实现方法的实现本质上是通过反射调用被代理对象的方法<br> * 4、将$Proxy0的实例返回给客户端。 <br> * 5、当调用代理类的相应方法时,相当于调用 {@link InvocationHandler#invoke(Object, java.lang.reflect.Method, Object[])} 方法 * * * @param <T> 被代理对象类型 * @param classloader 被代理类对应的ClassLoader * @param invocationHandler {@link InvocationHandler} ,被代理类通过实现此接口提供动态代理功能 * @param interfaces 代理类中需要实现的被代理类的接口方法 * @return 代理类 */ @SuppressWarnings("unchecked") public static <T> T newProxyInstance(ClassLoader classloader, InvocationHandler invocationHandler, Class<?>... interfaces) { return (T) Proxy.newProxyInstance(classloader, interfaces, invocationHandler); } /** * 创建动态代理对象 * * @param <T> 被代理对象类型 * @param invocationHandler {@link InvocationHandler} ,被代理类通过实现此接口提供动态代理功能 * @param interfaces 代理类中需要实现的被代理类的接口方法 * @return 代理类 */ public static <T> T newProxyInstance(InvocationHandler invocationHandler, Class<?>... interfaces) { return newProxyInstance(ClassUtil.getClassLoader(), invocationHandler, interfaces); } }
dromara/hutool
hutool-aop/src/main/java/cn/hutool/aop/ProxyUtil.java
1,239
M 1524200994 tags: DP, Backpack DP 给i本书, 每本书有自己的重量 int[] A, 背包有自己的大小M, 看最多能放多少重量的书? #### Backpack DP 1 - 简单直白的思考 dp[i][m]: 前i本书, 背包大小为M的时候, 最多能装多种的书? - **注意**: 背包问题, 重量weight一定要是一维. - dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - A[i - 1]] + A[i - 1]); - 每一步都track 最大值 - 最后return dp[n][m] - 时间空间 O(mn) - Rolling array, 空间O(m) #### Backpack DP 2 - true/false求解, 稍微曲线救国: 重点是, 最后, 按照weight从大到小遍历, 第一个遇到true的, index就是最大值. - 考虑: 用i个item (可跳过地取), 是否能装到weight w? - 需要从'可能性'的角度考虑, 不要搞成单一的最大值问题. - 1. 背包可装的物品大小和总承重有关. - 2. 不要去找dp[i]前i个物品的最大总重, 找的不是这个. dp[i]及时找到可放的最大sum, 但是i+1可能有更好的值, 把dp[i+1]变得更大更合适. ##### 做法 - boolean[][] dp[i][j]表示: 有前i个item, 用他们可否组成size为j的背包? true/false. - (反过来考虑了,不是想是否超过size j, 而是考虑是否能拼出exact size == j) - **注意**: 虽然dp里面一直存在i的位置, 实际上考虑的是在i位置的时候, 看前i-1个item. ##### 多项式规律 - 1. picked A[i-1]: 就是A[i-1]被用过, weight j 应该减去A[i-1]. 那么dp[i][j]就取决于dp[i-1][j-A[i-1]]的结果. - 2. did not pick A[i-1]: 那就是说, 没用过A[i-1], 那么dp[i][j]就取决于上一行d[i-1][j] - dp[i][j] = dp[i - 1][j] || dp[i - 1][j - A[i - 1]] ##### 结尾 - 跑一遍dp 最下面一个row. 从末尾开始找, 最末尾的一个j (能让dp[i][j] == true)的, 就是最多能装的大小 :) - 时间,空间都是:O(mn) ``` /* Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack? Example If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 5], so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7] so that we can fulfill the backpack. You function should return the max size we can fill in the given backpack. Note You can not divide any item into small pieces. Challenge O(n x m) time and O(m) memory. O(n x m) memory is also acceptable if you do not know how to optimize memory. Tags Expand LintCode Copyright Dynamic Programming Backpack */ /* Thoughts: Backpack problem, always consider a dimension with weight/size. int dp[i][j]: with i items and backpack size/weight-limit of j, what's max weight can we put in? dp[i][j] depends on last item's size && what's the state with [i-1] items. dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - A[i - 1]] + A[i - 1]); dp[0][0] = 0; no book, 0 weight limit dp[0][j] = 0; no book, can't fill bag dp[i][0] = 0; i books, but weight-limit = 0, can't fill */ public class Solution { public int backPack(int m, int[] A) { if (A == null || A.length < 0) { return 0; } int n = A.length; int[][] dp = new int[n + 1][m + 1]; // Calculcate possibility for i items to fill up w weight for (int i = 1; i <= n; i++) { for (int j = 0; j <= m; j++) { // default: item(i-1) not used: dp[i][j] = dp[i - 1][j]; if (j - A[i - 1] >= 0) { // possible to use item(i-1) dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - A[i - 1]] + A[i - 1]); // use item(i-1) } } } return dp[n][m]; } } // Rolling array public class Solution { public int backPack(int m, int[] A) { if (A == null || A.length < 0) { return 0; } int n = A.length; int[][] dp = new int[2][m + 1]; // Calculcate possibility for i items to fill up w weight for (int i = 1; i <= n; i++) { for (int j = 0; j <= m; j++) { // default: item(i-1) not used: dp[i % 2][j] = dp[(i - 1) % 2][j]; if (j - A[i - 1] >= 0) { // possible to use item(i-1) dp[i % 2][j] = Math.max(dp[i % 2][j], dp[(i - 1) % 2][j - A[i - 1]] + A[i - 1]); // use item(i-1) } } } return dp[n % 2][m]; } } /* Thoughts: DO NOT try to find the maxSum using given values: this approach f[i] only returns max sum, but does not guarantee to pick the most sutible items that maximize f[n]. 1. Always consider weight 2. Consider it as a possibility problem based on weight 0 ~ m Using given items, can we fill backpack with size 0, size 1, size 2... size m - 1, and size m? We save these values with boolean dp[i][w]: using i items to fill size w, where i is the A index. Two conditions for calculating dp[i][w] 1. i - 1 items filled up w, so dp[i][w] = dp[i - 1][w]. No need to add A[i - 1]. 2. i - 1 items fileld up w - A[i - 1]; once adding A[i - 1], it'll fill up w. dp[i][w] = dp[i - 1][w - A[i - 1]], so we are counting on if i - 1 items filled up weight: w - A[i - 1]. We'll loop over j = 1 ~ m, and attempt to fill all sizes with i items. init: dp[0][0]: using 0 items to fill 0 space, sure. True. dp[0][1~m]: using 0 items to fill 1~m space, not gonna work. False. */ public class Solution { public int backPack(int m, int[] A) { if (A == null || A.length < 0) { return 0; } int n = A.length; boolean[][] dp = new boolean[n + 1][m + 1]; // weight 0 is a valid value. // items does not have 0's item, so we need to init dp based for all entries where i == 0 dp[0][0] = true; for (int j = 1; j <= m; j++) { dp[0][j] = false; } // Calculcate possibility for i items to fill up w weight for (int i = 1; i <= n; i++) { for (int j = 0; j <= m; j++) { // default: item(i-1) not used: dp[i][j] = dp[i - 1][j]; if (j - A[i - 1] >= 0) { // possible to use item(i-1) dp[i][j] |= dp[i - 1][j - A[i - 1]]; // use item(i-1) } } } // Find max weight size that makes dp[i][j] true for (int j = m; j >= 0; j--) { if (dp[n][j]) { return j; } } return 0; } } /* Thoughts: rolling array. Always use i, and i - 1 dp. can replace the two index with curr, pre */ public class Solution { public int backPack(int m, int[] A) { if (A == null || A.length < 0) { return 0; } int n = A.length; boolean[][] dp = new boolean[2][m + 1]; int curr = 0; int pre = 1; // weight 0 is a valid value. // items does not have 0's item, so we need to init dp based for all entries where i == 0 dp[curr][0] = true; for (int j = 1; j <= m; j++) { dp[curr][j] = false; } // Calculcate possibility for i items to fill up w weight for (int i = 1; i <= n; i++) { curr = pre; pre = 1 - curr; for (int j = 0; j <= m; j++) { // default: item(i-1) not used: dp[curr][j] = dp[pre][j]; if (j - A[i - 1] >= 0) { // possible to use item(i-1) dp[curr][j] |= dp[pre][j - A[i - 1]]; // use item(i-1) } } } // Find max weight size that makes dp[i][j] true for (int j = m; j >= 0; j--) { if (dp[curr][j]) { return j; } } return 0; } } /* Thoughts: Recap on 12.02.2015 State DP[i][j]: i is the index of Ai, and j is the size from (0 ~ m). It means: depending if we added A[i-1], can we full-fill j-space? Return ture/false. Note: that is, even j == 0, and I have a item with size == 0. There is nothing to add, which means the backpack can reach j == 0. True. However, if we have a item with size == 2, but I need to fill space == 1. I will either pick/not pick item of size 2; either way, can't fill a backpack with size 1. False; Function: DP[i][j] = DP[i - 1][j] || DP[i - 1][j - A[i - 1]]; // based on if previous value is true/false: 1. didn't really add A[i-1] || 2. added A[i-1]. Init: DP[0][0] = true; // 0 space and 0 items, true. All the rest are false; Return the very last j that makes dp[A.length][j] true. */ public class Solution { public int backPack(int m, int[] A) { if (A == null || A.length == 0 || m <= 0) { return 0; } boolean[][] dp = new boolean[A.length + 1][m + 1]; dp[0][0] = true; for (int i = 1; i <= A.length; i++) { for (int j = 0; j <= m; j++) { //j is large enough: if (j - A[i - 1] >= 0) { //not added A[i - 1] or added A[i - 1] dp[i][j] = dp[i - 1][j] || dp[i - 1][j - A[i - 1]]; } else {// j not large enough, ofcourse not adding A[i-1] dp[i][j] = dp[i - 1][j]; } } } //Largest possible size with dp[j] == true for (int j = m; j >= 0; j--) { if (dp[A.length][j]) { return j; } } return 0; } } /* 1D array: memory mxn, space m. Tricky tho ... Looking at the 2D version, we are really just checking the DP with fixed i=A.length. DP[j]: can we fit i items into j? DP[j] == false || DP[j - A[i - 1]]. Similar two cases: 1. Can't fit in, set false; 2. Can fit in, then just return if (j - A[i - 1]) works Core difference: only set the DP[j] when (j - A[i - 1] >= 0 && DP[j - A[i - 1]]): since we are running from m ~ 0, we don't want to override some existing values */ public class Solution { public int backPack(int m, int[] A) { if (A == null || m == 0) { return 0; } boolean[] DP = new boolean[m + 1]; DP[0] = true; for (int i = 1; i <= A.length; i++) { for (int j = m; j >= 0; j--) { if (j - A[i - 1] >= 0 && DP[j - A[i - 1]]) { DP[j] = true; } } } for (int j = m; j >= 0; j--) { if (DP[j]) { return j; } } return 0; } } ```
awangdev/leet-code
Java/Backpack.java
1,241
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.support.ibatis; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.ibatis.sqlmap.client.SqlMapExecutor; import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl; import com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl; import com.ibatis.sqlmap.engine.scope.SessionScope; import java.lang.reflect.Field; import java.lang.reflect.Method; public class IbatisUtils { private static Log LOG = LogFactory.getLog(IbatisUtils.class); private static boolean VERSION_2_3_4; private static Method methodGetId; private static Method methodGetResource; private static Field sessionField; static { try { Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass("com.ibatis.sqlmap.engine.mapping.result.AutoResultMap"); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals("setResultObjectValues")) { // ibatis 2.3.4 add method 'setResultObjectValues' VERSION_2_3_4 = true; break; } } } catch (Throwable e) { LOG.error("Error while initializing", e); } } public static boolean isVersion2_3_4() { return VERSION_2_3_4; } public static SqlMapExecutor setClientImpl(SqlMapExecutor session, SqlMapClientImplWrapper clientImplWrapper) { if (session == null || clientImplWrapper == null) { return session; } if (session.getClass() == SqlMapSessionImpl.class) { SqlMapSessionImpl sessionImpl = (SqlMapSessionImpl) session; set(sessionImpl, clientImplWrapper); } return session; } /** * 通过反射的方式得到id,能够兼容2.3.0和2.3.4 * * @param statement the statement object from which to retrieve the ID * @return the ID as a string, or null if an error occurs or if the ID is null */ protected static String getId(Object statement) { try { if (methodGetId == null) { Class<?> clazz = statement.getClass(); methodGetId = clazz.getMethod("getId"); } Object returnValue = methodGetId.invoke(statement); if (returnValue == null) { return null; } return returnValue.toString(); } catch (Exception ex) { LOG.error("createIdError", ex); return null; } } /** * 通过反射的方式得到resource,能够兼容2.3.0和2.3.4 * * @param statement the statement object from which to retrieve the resource * @return the resource as a string, or null if an error occurs */ protected static String getResource(Object statement) { try { if (methodGetResource == null) { methodGetResource = statement.getClass().getMethod("getResource"); } return (String) methodGetResource.invoke(statement); } catch (Exception ex) { return null; } } public static void set(SqlMapSessionImpl session, SqlMapClientImpl client) { if (sessionField == null) { for (Field field : SqlMapSessionImpl.class.getDeclaredFields()) { if (field.getName().equals("session") || field.getName().equals("sessionScope")) { sessionField = field; sessionField.setAccessible(true); break; } } } if (sessionField != null) { SessionScope sessionScope; try { sessionScope = (SessionScope) sessionField.get(session); if (sessionScope != null) { if (sessionScope.getSqlMapClient() != null && sessionScope.getSqlMapClient().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapClient(client); } if (sessionScope.getSqlMapExecutor() != null && sessionScope.getSqlMapExecutor().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapExecutor(client); } if (sessionScope.getSqlMapTxMgr() != null && sessionScope.getSqlMapTxMgr().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapTxMgr(client); } } } catch (Exception e) { LOG.error(e.getMessage(), e); } } } }
alibaba/druid
core/src/main/java/com/alibaba/druid/support/ibatis/IbatisUtils.java
1,243
package me.zhyd.oauth.utils; import java.nio.charset.StandardCharsets; import java.util.concurrent.ThreadLocalRandom; /** * 高性能的创建UUID的工具类,https://github.com/lets-mica/mica * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.9.3 */ public class UuidUtils { /** * All possible chars for representing a number as a String * copy from mica:https://github.com/lets-mica/mica/blob/master/mica-core/src/main/java/net/dreamlu/mica/core/utils/NumberUtil.java#L113 */ private final static byte[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /** * 生成uuid,采用 jdk 9 的形式,优化性能 * copy from mica:https://github.com/lets-mica/mica/blob/master/mica-core/src/main/java/net/dreamlu/mica/core/utils/StringUtil.java#L335 * <p> * 关于mica uuid生成方式的压测结果,可以参考:https://github.com/lets-mica/mica-jmh/wiki/uuid * * @return UUID */ public static String getUUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); long lsb = random.nextLong(); long msb = random.nextLong(); byte[] buf = new byte[32]; formatUnsignedLong(lsb, buf, 20, 12); formatUnsignedLong(lsb >>> 48, buf, 16, 4); formatUnsignedLong(msb, buf, 12, 4); formatUnsignedLong(msb >>> 16, buf, 8, 4); formatUnsignedLong(msb >>> 32, buf, 0, 8); return new String(buf, StandardCharsets.UTF_8); } /** * copy from mica:https://github.com/lets-mica/mica/blob/master/mica-core/src/main/java/net/dreamlu/mica/core/utils/StringUtil.java#L348 */ private static void formatUnsignedLong(long val, byte[] buf, int offset, int len) { int charPos = offset + len; int radix = 1 << 4; int mask = radix - 1; do { buf[--charPos] = DIGITS[((int) val) & mask]; val >>>= 4; } while (charPos > offset); } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/utils/UuidUtils.java
1,244
package io.mycat.util.dataMigrator; import java.io.File; import java.io.IOException; /** * 数据导入导出接口,mysql、oracle等数据库通过实现此接口提供具体的数据导入导出功能 * @author haonan108 * */ public interface DataIO { /** * 导入数据 * @param dn 导入到具体的数据库 * @param file 导入的文件 * @throws IOException * @throws InterruptedException */ void importData(TableMigrateInfo table,DataNode dn,String tableName,File file) throws IOException, InterruptedException; /** * 根据条件导出迁移数据 * @param dn 导出哪个具体的数据库 * @param tableName 导出的表名称 * @param export 文件导出到哪里 * @param condion 导出文件依赖的具体条件 * @return * @throws IOException * @throws InterruptedException */ File exportData(TableMigrateInfo table,DataNode dn,String tableName,File exportPath,File condion) throws IOException, InterruptedException; }
MyCATApache/Mycat-Server
src/main/java/io/mycat/util/dataMigrator/DataIO.java
1,245
/** * Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.kit; /** * 用于定制个性化 Ret * * <pre> * 例子: * CPI.setRetState("success", true, false); * 将 Ret 的状态字段名由 "state" 改为 "success",将状态值 "ok" 改为 true、"fail" 改为 false * * CPI.setRetState("code", 200, 500); * 将 Ret 的状态字段名由 "state" 改为 "code",将状态值 "ok" 改为 200、"fail" 改为 500 * * CPI.setRetMsgName("message") * 将 Ret 的消息字段名由 "msg" 改为 "message" * </pre> */ public class CPI { /** * 配置 Ret 的状态名、成功状态值、失败状态值,默认值分别为:"state"、"ok"、"fail" * <pre> * 例子: * CPI.setRetState("success", true, false); * 将 Ret 的状态字段名由 "state" 改为 "success",将状态值 "ok" 改为 true、"fail" 改为 false * * CPI.setRetState("code", 200, 500); * 将 Ret 的状态字段名由 "state" 改为 "code",将状态值 "ok" 改为 200、"fail" 改为 500 * </pre> */ public static void setRetState(String stateName, Object stateOkValue, Object stateFailValue) { if (StrKit.isBlank(stateName)) { throw new IllegalArgumentException("stateName 不能为空"); } if (stateOkValue == null) { throw new IllegalArgumentException("stateOkValue 不能为 null"); } if (stateFailValue == null) { throw new IllegalArgumentException("stateFailValue 不能为 null"); } Ret.STATE = stateName; Ret.STATE_OK = stateOkValue; Ret.STATE_FAIL = stateFailValue; } /** * 配置 Ret 的消息名,默认值为:"msg" * <pre> * 例子: * CPI.setRetMsgName("message") * 将 Ret 的消息字段名由 "msg" 改为 "message" * </pre> */ public static void setRetMsgName(String msgName) { if (StrKit.isBlank(msgName)) { throw new IllegalArgumentException("msgName 不能为空"); } Ret.MSG = msgName; } /** * 配置 Ret 的 data 名,默认值为:"data" * <pre> * 例子: * CPI.setRetDataName("body") * 将 Ret 的数据字段名由 "data" 改为 "body" * </pre> */ public static void setRetDataName(String dataName) { if (StrKit.isBlank(dataName)) { throw new IllegalArgumentException("dataName 不能为空"); } Ret.DATA = dataName; } /** * 配置 Ret 的 data 方法伴随 ok 状态,默认值为:true * <pre> * 例子: * CPI.setRetDataWithOkState(false) * 将 Ret 的 data 方法伴随 ok 状态,改为不伴随 ok 状态 * </pre> */ public static void setRetDataWithOkState(boolean dataWithOkState) { Ret.dataWithOkState = dataWithOkState; } /** * 配置 state 监听 * <pre> * 例子: * CPI.setRetStateWatcher((ret, state, value) -> { * ret.set("success", "ok".equals(value)); * }); * 监听 state,当值为 "ok" 时,额外放入 "success" 值为 true,否则为 false, * 在前后端分离项目中,有些前端框架需要该返回值:"success" : true/false * </pre> */ public static void setRetStateWatcher(Func.F30<Ret, String, Object> stateWatcher) { if (stateWatcher == null) { throw new IllegalArgumentException("stateWatcher 不能 null"); } Ret.stateWatcher = stateWatcher; } /** * 配置 Ret.isOk()、Ret.isFail() 在前两个 if 判断都没有 return 之后的处理回调 * 用于支持多于两个状态的情况,也即在 ok、fail 两个状态之外还引入了其它状态 * <pre> * 例子: * CPI.setRetOkFailHandler((isOkMethod, value) -> { * if (isOkMethod == Boolean.TRUE) { * return false; * } else { * return true; * } * }); * </pre> */ public static void setRetOkFailHandler(Func.F21<Boolean, Object, Boolean> okFailHandler) { if (okFailHandler == null) { throw new IllegalArgumentException("okFailHandler 不能 null"); } Ret.okFailHandler = okFailHandler; } public static String getRetStateName() { return Ret.STATE; } public static Object getRetStateOkValue() { return Ret.STATE_OK; } public static Object getRetStateFailValue() { return Ret.STATE_FAIL; } public static String getRetMsgName() { return Ret.MSG; } public static String getRetDataName() { return Ret.DATA; } public static boolean getRetDataWithOkState() { return Ret.dataWithOkState; } public static Func.F30<Ret, String, Object> getRetStateWatcher() { return Ret.stateWatcher; } public static Func.F21<Boolean, Object, Boolean> getRetOkFailHandler() { return Ret.okFailHandler; } }
jfinal/jfinal
src/main/java/com/jfinal/kit/CPI.java
1,246
package org.nutz.conf; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import org.nutz.el.opt.custom.CustomMake; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.util.NutType; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mapl.Mapl; import org.nutz.repo.org.objectweb.asm.Opcodes; import org.nutz.resource.NutResource; import org.nutz.resource.Scans; /** * 配置加载器<br/> * 一个通用的配置加载器, 全局的加载配置文件, 这样, 在所有地方都可以使用这些配置信息了. 规则:<br/> * <ul> * <li>配置文件使用JSON格式. * <li>JSON第一层为配置项键值对, KEY 为配置项名称, 值为配置信息. * <li>使用文件数组, 或者文件目录的形式, 可以加载多个配置文件 * <li>可以使用 include 关键字来引用其它配置文件, 值以数组形式. * <li>多配置文件的情况下后加载的配置会覆盖之前加载的配置,include引用的配置会覆盖引用前的配置. * <li>与JSON 相同, 配置项的值你可以转换成任意你想要的类型. 包括泛型, 可以使用 {@link NutType} * </ul> * * @author juqkai([email protected]) * */ public class NutConf { private static final Log log = Logs.get(); private static final String DEFAULT_CONFIG = "org/nutz/conf/NutzDefaultConfig.js"; // 所有的配置信息 private Map<String, Object> map = new HashMap<String, Object>(); // zozoh 单利的话,没必要用这个吧 ... // private static final Lock lock = new ReentrantLock(); private volatile static NutConf conf; private static NutConf me() { if (null == conf) { synchronized (NutConf.class) { if (null == conf) { conf = new NutConf(); } } } return conf; } private NutConf() { // 加载框架自己的一些配置 loadResource(DEFAULT_CONFIG); } public static void load(String... paths) { me().loadResource(paths); CustomMake.me().init(); } /** * 加载资源 */ @SuppressWarnings({"unchecked", "rawtypes"}) private void loadResource(String... paths) { for (String path : paths) { List<NutResource> resources = Scans.me().scan(path, "\\.(js|json)$"); for (NutResource nr : resources) { try { Object obj = Json.fromJson(nr.getReader()); if (obj instanceof Map) { Map m = (Map) obj; map = (Map) Mapl.merge(map, m); for (Object key : m.keySet()) { if ("include".equals(key)) { map.remove("include"); List<String> include = (List) m.get("include"); loadResource(include.toArray(new String[include.size()])); } } } } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn("Fail to load config?! for " + nr.getName(), e); } } } } } /** * 读取一个配置项, 并转换成相应的类型. */ public static Object get(String key, Type type) { return me().getItem(key, type); } /** * 读取配置项, 返回Map, List或者 Object. 具体返回什么, 请参考 JSON 规则 */ public static Object get(String key) { return me().getItem(key, null); } /** * 读取一个配置项, 并转换成相应的类型. * * @param key * @param type * @return */ private Object getItem(String key, Type type) { if (null == map) { return null; } if (null == type) { return map.get(key); } return Mapl.maplistToObj(map.get(key), type); } /** * 清理所有配置信息 */ public static void clear() { conf = null; } /** * 是否启用FastClass机制,会提高反射的性能,如果需要热部署,应关闭. 性能影响低于10% */ public static boolean USE_FASTCLASS = !Lang.isAndroid && Lang.JdkTool.getMajorVersion() <= 8; /** * 是否缓存Mirror,配合FastClass机制使用,会提高反射的性能,如果需要热部署,应关闭. 性能影响低于10% */ public static boolean USE_MIRROR_CACHE = true; /** * Map.map2object时的EL支持,很少会用到,所以默认关闭. 若启用, Json.fromJson会有30%左右的性能损失 */ public static boolean USE_EL_IN_OBJECT_CONVERT = false; /** * 调试Scans类的开关.鉴于Scans已经非常靠谱,这个开关基本上没用处了 */ public static boolean RESOURCE_SCAN_TRACE = false; /** * 是否允许非法的Json转义符,属于兼容性配置 */ public static boolean JSON_ALLOW_ILLEGAL_ESCAPE = true; /** * 若允许非法的Json转义符,是否把转义符附加进目标字符串 */ public static boolean JSON_APPEND_ILLEGAL_ESCAPE = false; /** * Aop类是否每个Ioc容器都唯一,设置这个开关是因为wendal还不确定会有什么影响,暂时关闭状态. */ public static boolean AOP_USE_CLASS_ID = false; public static int AOP_CLASS_LEVEL = Opcodes.V1_6; public static boolean HAS_LOCAL_DATE_TIME; static { try { Class.forName("java.time.temporal.TemporalAccessor"); HAS_LOCAL_DATE_TIME = true; } catch (Throwable e) { } } public static boolean AOP_ENABLED = !"false".equals(System.getProperty("nutz.aop.enable")); public static void set(String key, Object value) { if (value == null) { me().map.remove(key); } else { me().map.put(key, value); } } public static Object getOrDefault(String key, Object defaultValue) { Object re = me().map.get(key); if (re == null) { return defaultValue; } return re; } public static boolean SQLSERVER_USE_NVARCHAR = true; public static boolean DAO_USE_POJO_INTERCEPTOR = true; public static boolean MVC_ADD_ATTR_$REQUEST = false; }
nutzam/nutz
src/org/nutz/conf/NutConf.java
1,249
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import androidx.core.view.ViewCompat; import androidx.appcompat.app.AppCompatActivity; import android.transition.Transition; import android.view.View; import android.widget.ImageView; import com.example.gsyvideoplayer.databinding.ActivityPlayPickBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by shuyu on 2016/11/11. */ public class PlayPickActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayPickBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayPickBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayer.setUp(list, false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayer.setThumbImageView(imageView); //增加title binding.videoPlayer.getTitleTextView().setVisibility(View.VISIBLE); //设置返回键 binding.videoPlayer.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayer); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //是否可以滑动调整 binding.videoPlayer.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayer.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayer.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayer.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayer.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayer, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayer.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener(){ @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayer.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/PlayPickActivity.java
1,259
package me.ag2s.epublib.epub; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; import me.ag2s.epublib.util.StringUtil; /** * Utility methods for working with the DOM. * * @author paul */ // package class DOMUtil { /** * First tries to get the attribute value by doing an getAttributeNS on the element, if that gets an empty element it does a getAttribute without namespace. * * @param element element * @param namespace namespace * @param attribute attribute * @return String Attribute */ public static String getAttribute(Element element, String namespace, String attribute) { String result = element.getAttributeNS(namespace, attribute); if (StringUtil.isEmpty(result)) { result = element.getAttribute(attribute); } return result; } /** * Gets all descendant elements of the given parentElement with the given namespace and tagname and returns their text child as a list of String. * * @param parentElement parentElement * @param namespace namespace * @param tagName tagName * @return List<String> */ public static List<String> getElementsTextChild(Element parentElement, String namespace, String tagName) { NodeList elements = parentElement .getElementsByTagNameNS(namespace, tagName); //ArrayList 初始化时指定长度提高性能 List<String> result = new ArrayList<>(elements.getLength()); for (int i = 0; i < elements.getLength(); i++) { result.add(getTextChildrenContent((Element) elements.item(i))); } return result; } /** * Finds in the current document the first element with the given namespace and elementName and with the given findAttributeName and findAttributeValue. * It then returns the value of the given resultAttributeName. * * @param document document * @param namespace namespace * @param elementName elementName * @param findAttributeName findAttributeName * @param findAttributeValue findAttributeValue * @param resultAttributeName resultAttributeName * @return String value */ public static String getFindAttributeValue(Document document, String namespace, String elementName, String findAttributeName, String findAttributeValue, String resultAttributeName) { NodeList metaTags = document.getElementsByTagNameNS(namespace, elementName); for (int i = 0; i < metaTags.getLength(); i++) { Element metaElement = (Element) metaTags.item(i); if (findAttributeValue .equalsIgnoreCase(metaElement.getAttribute(findAttributeName)) && StringUtil .isNotBlank(metaElement.getAttribute(resultAttributeName))) { return metaElement.getAttribute(resultAttributeName); } } return null; } /** * Gets the first element that is a child of the parentElement and has the given namespace and tagName * * @param parentElement parentElement * @param namespace namespace * @param tagName tagName * @return Element */ public static NodeList getElementsByTagNameNS(Element parentElement, String namespace, String tagName) { NodeList nodes = parentElement.getElementsByTagNameNS(namespace, tagName); if (nodes.getLength() != 0) { return nodes; } nodes = parentElement.getElementsByTagName(tagName); if (nodes.getLength() == 0) { return null; } return nodes; } /** * Gets the first element that is a child of the parentElement and has the given namespace and tagName * * @param parentElement parentElement * @param namespace namespace * @param tagName tagName * @return Element */ public static NodeList getElementsByTagNameNS(Document parentElement, String namespace, String tagName) { NodeList nodes = parentElement.getElementsByTagNameNS(namespace, tagName); if (nodes.getLength() != 0) { return nodes; } nodes = parentElement.getElementsByTagName(tagName); if (nodes.getLength() == 0) { return null; } return nodes; } /** * Gets the first element that is a child of the parentElement and has the given namespace and tagName * * @param parentElement parentElement * @param namespace namespace * @param tagName tagName * @return Element */ public static Element getFirstElementByTagNameNS(Element parentElement, String namespace, String tagName) { NodeList nodes = parentElement.getElementsByTagNameNS(namespace, tagName); if (nodes.getLength() != 0) { return (Element) nodes.item(0); } nodes = parentElement.getElementsByTagName(tagName); if (nodes.getLength() == 0) { return null; } return (Element) nodes.item(0); } /** * The contents of all Text nodes that are children of the given parentElement. * The result is trim()-ed. * <p> * The reason for this more complicated procedure instead of just returning the data of the firstChild is that * when the text is Chinese characters then on Android each Characater is represented in the DOM as * an individual Text node. * * @param parentElement parentElement * @return String value */ public static String getTextChildrenContent(Element parentElement) { if (parentElement == null) { return null; } StringBuilder result = new StringBuilder(); NodeList childNodes = parentElement.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if ((node == null) || (node.getNodeType() != Node.TEXT_NODE)) { continue; } result.append(((Text) node).getData()); } return result.toString().trim(); } }
gedoor/legado
modules/book/src/main/java/me/ag2s/epublib/epub/DOMUtil.java
1,260
/* * Copyright 2009-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.session; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.function.BiFunction; import org.apache.ibatis.binding.MapperRegistry; import org.apache.ibatis.builder.CacheRefResolver; import org.apache.ibatis.builder.IncompleteElementException; import org.apache.ibatis.builder.ResultMapResolver; import org.apache.ibatis.builder.annotation.MethodResolver; import org.apache.ibatis.builder.xml.XMLStatementBuilder; import org.apache.ibatis.cache.Cache; import org.apache.ibatis.cache.decorators.FifoCache; import org.apache.ibatis.cache.decorators.LruCache; import org.apache.ibatis.cache.decorators.SoftCache; import org.apache.ibatis.cache.decorators.WeakCache; import org.apache.ibatis.cache.impl.PerpetualCache; import org.apache.ibatis.datasource.jndi.JndiDataSourceFactory; import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory; import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory; import org.apache.ibatis.executor.BatchExecutor; import org.apache.ibatis.executor.CachingExecutor; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.ReuseExecutor; import org.apache.ibatis.executor.SimpleExecutor; import org.apache.ibatis.executor.keygen.KeyGenerator; import org.apache.ibatis.executor.loader.ProxyFactory; import org.apache.ibatis.executor.loader.cglib.CglibProxyFactory; import org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.executor.resultset.DefaultResultSetHandler; import org.apache.ibatis.executor.resultset.ResultSetHandler; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.io.VFS; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl; import org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl; import org.apache.ibatis.logging.log4j.Log4jImpl; import org.apache.ibatis.logging.log4j2.Log4j2Impl; import org.apache.ibatis.logging.nologging.NoLoggingImpl; import org.apache.ibatis.logging.slf4j.Slf4jImpl; import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMap; import org.apache.ibatis.mapping.ResultMap; import org.apache.ibatis.mapping.ResultSetType; import org.apache.ibatis.mapping.VendorDatabaseIdProvider; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.InterceptorChain; import org.apache.ibatis.reflection.DefaultReflectorFactory; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.ReflectorFactory; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.factory.ObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.scripting.LanguageDriverRegistry; import org.apache.ibatis.scripting.defaults.RawLanguageDriver; import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import org.apache.ibatis.transaction.managed.ManagedTransactionFactory; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeAliasRegistry; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; /** * @author Clinton Begin * @description 重写put,实现刷新的功能 */ public class Configuration { protected Environment environment; protected boolean safeRowBoundsEnabled; protected boolean safeResultHandlerEnabled = true; protected boolean mapUnderscoreToCamelCase; protected boolean aggressiveLazyLoading; protected boolean multipleResultSetsEnabled = true; protected boolean useGeneratedKeys; protected boolean useColumnLabel = true; protected boolean cacheEnabled = true; protected boolean callSettersOnNulls; protected boolean useActualParamName = true; protected boolean returnInstanceForEmptyRow; protected boolean shrinkWhitespacesInSql; protected boolean nullableOnForEach; protected boolean argNameBasedConstructorAutoMapping; protected String logPrefix; protected Class<? extends Log> logImpl; protected Class<? extends VFS> vfsImpl; protected Class<?> defaultSqlProviderType; protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION; protected JdbcType jdbcTypeForNull = JdbcType.OTHER; protected Set<String> lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString")); protected Integer defaultStatementTimeout; protected Integer defaultFetchSize; protected ResultSetType defaultResultSetType; protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE; protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL; protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE; protected Properties variables = new Properties(); protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); protected ObjectFactory objectFactory = new DefaultObjectFactory(); protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory(); protected boolean lazyLoadingEnabled = false; protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL protected String databaseId; /** * Configuration factory class. Used to create Configuration for loading deserialized unread properties. * * @see <a href='https://github.com/mybatis/old-google-code-issues/issues/300'>Issue 300 (google code)</a> */ protected Class<?> configurationFactory; protected final MapperRegistry mapperRegistry = new MapperRegistry(this); protected final InterceptorChain interceptorChain = new InterceptorChain(); protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(this); protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry(); protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry(); protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection") .conflictMessageProducer((savedValue, targetValue) -> ". please check " + savedValue.getResource() + " and " + targetValue.getResource()); protected final Map<String, Cache> caches = new StrictMap<>("Caches collection"); protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection"); protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection"); protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection"); protected final Set<String> loadedResources = new HashSet<>(); protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers"); protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>(); protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>(); protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>(); protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>(); /* * A map holds cache-ref relationship. The key is the namespace that * references a cache bound to another namespace and the value is the * namespace which the actual cache is bound to. */ protected final Map<String, String> cacheRefMap = new HashMap<>(); public Configuration(Environment environment) { this(); this.environment = environment; } public Configuration() { typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class); typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class); typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class); typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class); typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class); typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class); typeAliasRegistry.registerAlias("FIFO", FifoCache.class); typeAliasRegistry.registerAlias("LRU", LruCache.class); typeAliasRegistry.registerAlias("SOFT", SoftCache.class); typeAliasRegistry.registerAlias("WEAK", WeakCache.class); typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class); typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class); typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class); typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class); typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class); typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class); typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class); typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class); typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class); typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class); typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class); typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class); languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class); languageRegistry.register(RawLanguageDriver.class); } public String getLogPrefix() { return logPrefix; } public void setLogPrefix(String logPrefix) { this.logPrefix = logPrefix; } public Class<? extends Log> getLogImpl() { return logImpl; } public void setLogImpl(Class<? extends Log> logImpl) { if (logImpl != null) { this.logImpl = logImpl; LogFactory.useCustomLogging(this.logImpl); } } public Class<? extends VFS> getVfsImpl() { return this.vfsImpl; } public void setVfsImpl(Class<? extends VFS> vfsImpl) { if (vfsImpl != null) { this.vfsImpl = vfsImpl; VFS.addImplClass(this.vfsImpl); } } /** * Gets an applying type when omit a type on sql provider annotation(e.g. {@link org.apache.ibatis.annotations.SelectProvider}). * * @return the default type for sql provider annotation * @since 3.5.6 */ public Class<?> getDefaultSqlProviderType() { return defaultSqlProviderType; } /** * Sets an applying type when omit a type on sql provider annotation(e.g. {@link org.apache.ibatis.annotations.SelectProvider}). * * @param defaultSqlProviderType the default type for sql provider annotation * @since 3.5.6 */ public void setDefaultSqlProviderType(Class<?> defaultSqlProviderType) { this.defaultSqlProviderType = defaultSqlProviderType; } public boolean isCallSettersOnNulls() { return callSettersOnNulls; } public void setCallSettersOnNulls(boolean callSettersOnNulls) { this.callSettersOnNulls = callSettersOnNulls; } public boolean isUseActualParamName() { return useActualParamName; } public void setUseActualParamName(boolean useActualParamName) { this.useActualParamName = useActualParamName; } public boolean isReturnInstanceForEmptyRow() { return returnInstanceForEmptyRow; } public void setReturnInstanceForEmptyRow(boolean returnEmptyInstance) { this.returnInstanceForEmptyRow = returnEmptyInstance; } public boolean isShrinkWhitespacesInSql() { return shrinkWhitespacesInSql; } public void setShrinkWhitespacesInSql(boolean shrinkWhitespacesInSql) { this.shrinkWhitespacesInSql = shrinkWhitespacesInSql; } /** * Sets the default value of 'nullable' attribute on 'foreach' tag. * * @param nullableOnForEach If nullable, set to {@code true} * @since 3.5.9 */ public void setNullableOnForEach(boolean nullableOnForEach) { this.nullableOnForEach = nullableOnForEach; } /** * Returns the default value of 'nullable' attribute on 'foreach' tag. * * <p> * Default is {@code false}. * * @return If nullable, set to {@code true} * @since 3.5.9 */ public boolean isNullableOnForEach() { return nullableOnForEach; } public boolean isArgNameBasedConstructorAutoMapping() { return argNameBasedConstructorAutoMapping; } public void setArgNameBasedConstructorAutoMapping(boolean argNameBasedConstructorAutoMapping) { this.argNameBasedConstructorAutoMapping = argNameBasedConstructorAutoMapping; } public String getDatabaseId() { return databaseId; } public void setDatabaseId(String databaseId) { this.databaseId = databaseId; } public Class<?> getConfigurationFactory() { return configurationFactory; } public void setConfigurationFactory(Class<?> configurationFactory) { this.configurationFactory = configurationFactory; } public boolean isSafeResultHandlerEnabled() { return safeResultHandlerEnabled; } public void setSafeResultHandlerEnabled(boolean safeResultHandlerEnabled) { this.safeResultHandlerEnabled = safeResultHandlerEnabled; } public boolean isSafeRowBoundsEnabled() { return safeRowBoundsEnabled; } public void setSafeRowBoundsEnabled(boolean safeRowBoundsEnabled) { this.safeRowBoundsEnabled = safeRowBoundsEnabled; } public boolean isMapUnderscoreToCamelCase() { return mapUnderscoreToCamelCase; } public void setMapUnderscoreToCamelCase(boolean mapUnderscoreToCamelCase) { this.mapUnderscoreToCamelCase = mapUnderscoreToCamelCase; } public void addLoadedResource(String resource) { loadedResources.add(resource); } public boolean isResourceLoaded(String resource) { return loadedResources.contains(resource); } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public AutoMappingBehavior getAutoMappingBehavior() { return autoMappingBehavior; } public void setAutoMappingBehavior(AutoMappingBehavior autoMappingBehavior) { this.autoMappingBehavior = autoMappingBehavior; } /** * Gets the auto mapping unknown column behavior. * * @return the auto mapping unknown column behavior * @since 3.4.0 */ public AutoMappingUnknownColumnBehavior getAutoMappingUnknownColumnBehavior() { return autoMappingUnknownColumnBehavior; } /** * Sets the auto mapping unknown column behavior. * * @param autoMappingUnknownColumnBehavior the new auto mapping unknown column behavior * @since 3.4.0 */ public void setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior) { this.autoMappingUnknownColumnBehavior = autoMappingUnknownColumnBehavior; } public boolean isLazyLoadingEnabled() { return lazyLoadingEnabled; } public void setLazyLoadingEnabled(boolean lazyLoadingEnabled) { this.lazyLoadingEnabled = lazyLoadingEnabled; } public ProxyFactory getProxyFactory() { return proxyFactory; } public void setProxyFactory(ProxyFactory proxyFactory) { if (proxyFactory == null) { proxyFactory = new JavassistProxyFactory(); } this.proxyFactory = proxyFactory; } public boolean isAggressiveLazyLoading() { return aggressiveLazyLoading; } public void setAggressiveLazyLoading(boolean aggressiveLazyLoading) { this.aggressiveLazyLoading = aggressiveLazyLoading; } public boolean isMultipleResultSetsEnabled() { return multipleResultSetsEnabled; } public void setMultipleResultSetsEnabled(boolean multipleResultSetsEnabled) { this.multipleResultSetsEnabled = multipleResultSetsEnabled; } public Set<String> getLazyLoadTriggerMethods() { return lazyLoadTriggerMethods; } public void setLazyLoadTriggerMethods(Set<String> lazyLoadTriggerMethods) { this.lazyLoadTriggerMethods = lazyLoadTriggerMethods; } public boolean isUseGeneratedKeys() { return useGeneratedKeys; } public void setUseGeneratedKeys(boolean useGeneratedKeys) { this.useGeneratedKeys = useGeneratedKeys; } public ExecutorType getDefaultExecutorType() { return defaultExecutorType; } public void setDefaultExecutorType(ExecutorType defaultExecutorType) { this.defaultExecutorType = defaultExecutorType; } public boolean isCacheEnabled() { return cacheEnabled; } public void setCacheEnabled(boolean cacheEnabled) { this.cacheEnabled = cacheEnabled; } public Integer getDefaultStatementTimeout() { return defaultStatementTimeout; } public void setDefaultStatementTimeout(Integer defaultStatementTimeout) { this.defaultStatementTimeout = defaultStatementTimeout; } /** * Gets the default fetch size. * * @return the default fetch size * @since 3.3.0 */ public Integer getDefaultFetchSize() { return defaultFetchSize; } /** * Sets the default fetch size. * * @param defaultFetchSize the new default fetch size * @since 3.3.0 */ public void setDefaultFetchSize(Integer defaultFetchSize) { this.defaultFetchSize = defaultFetchSize; } /** * Gets the default result set type. * * @return the default result set type * @since 3.5.2 */ public ResultSetType getDefaultResultSetType() { return defaultResultSetType; } /** * Sets the default result set type. * * @param defaultResultSetType the new default result set type * @since 3.5.2 */ public void setDefaultResultSetType(ResultSetType defaultResultSetType) { this.defaultResultSetType = defaultResultSetType; } public boolean isUseColumnLabel() { return useColumnLabel; } public void setUseColumnLabel(boolean useColumnLabel) { this.useColumnLabel = useColumnLabel; } public LocalCacheScope getLocalCacheScope() { return localCacheScope; } public void setLocalCacheScope(LocalCacheScope localCacheScope) { this.localCacheScope = localCacheScope; } public JdbcType getJdbcTypeForNull() { return jdbcTypeForNull; } public void setJdbcTypeForNull(JdbcType jdbcTypeForNull) { this.jdbcTypeForNull = jdbcTypeForNull; } public Properties getVariables() { return variables; } public void setVariables(Properties variables) { this.variables = variables; } public TypeHandlerRegistry getTypeHandlerRegistry() { return typeHandlerRegistry; } /** * Set a default {@link TypeHandler} class for {@link Enum}. A default {@link TypeHandler} is {@link org.apache.ibatis.type.EnumTypeHandler}. * @param typeHandler a type handler class for {@link Enum} * @since 3.4.5 */ public void setDefaultEnumTypeHandler(Class<? extends TypeHandler> typeHandler) { if (typeHandler != null) { getTypeHandlerRegistry().setDefaultEnumTypeHandler(typeHandler); } } public TypeAliasRegistry getTypeAliasRegistry() { return typeAliasRegistry; } /** * Gets the mapper registry. * * @return the mapper registry * @since 3.2.2 */ public MapperRegistry getMapperRegistry() { return mapperRegistry; } public ReflectorFactory getReflectorFactory() { return reflectorFactory; } public void setReflectorFactory(ReflectorFactory reflectorFactory) { this.reflectorFactory = reflectorFactory; } public ObjectFactory getObjectFactory() { return objectFactory; } public void setObjectFactory(ObjectFactory objectFactory) { this.objectFactory = objectFactory; } public ObjectWrapperFactory getObjectWrapperFactory() { return objectWrapperFactory; } public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) { this.objectWrapperFactory = objectWrapperFactory; } /** * Gets the interceptors. * * @return the interceptors * @since 3.2.2 */ public List<Interceptor> getInterceptors() { return interceptorChain.getInterceptors(); } public LanguageDriverRegistry getLanguageRegistry() { return languageRegistry; } public void setDefaultScriptingLanguage(Class<? extends LanguageDriver> driver) { if (driver == null) { driver = XMLLanguageDriver.class; } getLanguageRegistry().setDefaultDriverClass(driver); } public LanguageDriver getDefaultScriptingLanguageInstance() { return languageRegistry.getDefaultDriver(); } /** * Gets the language driver. * * @param langClass the lang class * @return the language driver * @since 3.5.1 */ public LanguageDriver getLanguageDriver(Class<? extends LanguageDriver> langClass) { if (langClass == null) { return languageRegistry.getDefaultDriver(); } languageRegistry.register(langClass); return languageRegistry.getDriver(langClass); } /** * Gets the default scripting language instance. * * @return the default scripting language instance * @deprecated Use {@link #getDefaultScriptingLanguageInstance()} */ @Deprecated public LanguageDriver getDefaultScriptingLanuageInstance() { return getDefaultScriptingLanguageInstance(); } public MetaObject newMetaObject(Object object) { return MetaObject.forObject(object, objectFactory, objectWrapperFactory, reflectorFactory); } public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql); parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); return parameterHandler; } public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql) { ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds); resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler); return resultSetHandler; } public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql); statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); return statementHandler; } public Executor newExecutor(Transaction transaction) { return newExecutor(transaction, defaultExecutorType); } public Executor newExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType : executorType; executorType = executorType == null ? ExecutorType.SIMPLE : executorType; Executor executor; if (ExecutorType.BATCH == executorType) { executor = new BatchExecutor(this, transaction); } else if (ExecutorType.REUSE == executorType) { executor = new ReuseExecutor(this, transaction); } else { executor = new SimpleExecutor(this, transaction); } if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; } public void addKeyGenerator(String id, KeyGenerator keyGenerator) { keyGenerators.put(id, keyGenerator); } public Collection<String> getKeyGeneratorNames() { return keyGenerators.keySet(); } public Collection<KeyGenerator> getKeyGenerators() { return keyGenerators.values(); } public KeyGenerator getKeyGenerator(String id) { return keyGenerators.get(id); } public boolean hasKeyGenerator(String id) { return keyGenerators.containsKey(id); } public void addCache(Cache cache) { caches.put(cache.getId(), cache); } public Collection<String> getCacheNames() { return caches.keySet(); } public Collection<Cache> getCaches() { return caches.values(); } public Cache getCache(String id) { return caches.get(id); } public boolean hasCache(String id) { return caches.containsKey(id); } public void addResultMap(ResultMap rm) { resultMaps.put(rm.getId(), rm); checkLocallyForDiscriminatedNestedResultMaps(rm); checkGloballyForDiscriminatedNestedResultMaps(rm); } public Collection<String> getResultMapNames() { return resultMaps.keySet(); } public Collection<ResultMap> getResultMaps() { return resultMaps.values(); } public ResultMap getResultMap(String id) { return resultMaps.get(id); } public boolean hasResultMap(String id) { return resultMaps.containsKey(id); } public void addParameterMap(ParameterMap pm) { parameterMaps.put(pm.getId(), pm); } public Collection<String> getParameterMapNames() { return parameterMaps.keySet(); } public Collection<ParameterMap> getParameterMaps() { return parameterMaps.values(); } public ParameterMap getParameterMap(String id) { return parameterMaps.get(id); } public boolean hasParameterMap(String id) { return parameterMaps.containsKey(id); } public void addMappedStatement(MappedStatement ms) { mappedStatements.put(ms.getId(), ms); } public Collection<String> getMappedStatementNames() { buildAllStatements(); return mappedStatements.keySet(); } public Collection<MappedStatement> getMappedStatements() { buildAllStatements(); return mappedStatements.values(); } public Collection<XMLStatementBuilder> getIncompleteStatements() { return incompleteStatements; } public void addIncompleteStatement(XMLStatementBuilder incompleteStatement) { incompleteStatements.add(incompleteStatement); } public Collection<CacheRefResolver> getIncompleteCacheRefs() { return incompleteCacheRefs; } public void addIncompleteCacheRef(CacheRefResolver incompleteCacheRef) { incompleteCacheRefs.add(incompleteCacheRef); } public Collection<ResultMapResolver> getIncompleteResultMaps() { return incompleteResultMaps; } public void addIncompleteResultMap(ResultMapResolver resultMapResolver) { incompleteResultMaps.add(resultMapResolver); } public void addIncompleteMethod(MethodResolver builder) { incompleteMethods.add(builder); } public Collection<MethodResolver> getIncompleteMethods() { return incompleteMethods; } public MappedStatement getMappedStatement(String id) { return this.getMappedStatement(id, true); } public MappedStatement getMappedStatement(String id, boolean validateIncompleteStatements) { if (validateIncompleteStatements) { buildAllStatements(); } return mappedStatements.get(id); } public Map<String, XNode> getSqlFragments() { return sqlFragments; } public void addInterceptor(Interceptor interceptor) { interceptorChain.addInterceptor(interceptor); } public void addMappers(String packageName, Class<?> superType) { mapperRegistry.addMappers(packageName, superType); } public void addMappers(String packageName) { mapperRegistry.addMappers(packageName); } public <T> void addMapper(Class<T> type) { mapperRegistry.addMapper(type); } public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); } public boolean hasMapper(Class<?> type) { return mapperRegistry.hasMapper(type); } public boolean hasStatement(String statementName) { return hasStatement(statementName, true); } public boolean hasStatement(String statementName, boolean validateIncompleteStatements) { if (validateIncompleteStatements) { buildAllStatements(); } return mappedStatements.containsKey(statementName); } public void addCacheRef(String namespace, String referencedNamespace) { cacheRefMap.put(namespace, referencedNamespace); } /* * Parses all the unprocessed statement nodes in the cache. It is recommended * to call this method once all the mappers are added as it provides fail-fast * statement validation. */ protected void buildAllStatements() { parsePendingResultMaps(); if (!incompleteCacheRefs.isEmpty()) { synchronized (incompleteCacheRefs) { incompleteCacheRefs.removeIf(x -> x.resolveCacheRef() != null); } } if (!incompleteStatements.isEmpty()) { synchronized (incompleteStatements) { incompleteStatements.removeIf(x -> { x.parseStatementNode(); return true; }); } } if (!incompleteMethods.isEmpty()) { synchronized (incompleteMethods) { incompleteMethods.removeIf(x -> { x.resolve(); return true; }); } } } private void parsePendingResultMaps() { if (incompleteResultMaps.isEmpty()) { return; } synchronized (incompleteResultMaps) { boolean resolved; IncompleteElementException ex = null; do { resolved = false; Iterator<ResultMapResolver> iterator = incompleteResultMaps.iterator(); while (iterator.hasNext()) { try { iterator.next().resolve(); iterator.remove(); resolved = true; } catch (IncompleteElementException e) { ex = e; } } } while (resolved); if (!incompleteResultMaps.isEmpty() && ex != null) { // At least one result map is unresolvable. throw ex; } } } /** * Extracts namespace from fully qualified statement id. * * @param statementId the statement id * @return namespace or null when id does not contain period. */ protected String extractNamespace(String statementId) { int lastPeriod = statementId.lastIndexOf('.'); return lastPeriod > 0 ? statementId.substring(0, lastPeriod) : null; } // Slow but a one time cost. A better solution is welcome. protected void checkGloballyForDiscriminatedNestedResultMaps(ResultMap rm) { if (rm.hasNestedResultMaps()) { for (Map.Entry<String, ResultMap> entry : resultMaps.entrySet()) { Object value = entry.getValue(); if (value instanceof ResultMap) { ResultMap entryResultMap = (ResultMap) value; if (!entryResultMap.hasNestedResultMaps() && entryResultMap.getDiscriminator() != null) { Collection<String> discriminatedResultMapNames = entryResultMap.getDiscriminator().getDiscriminatorMap().values(); if (discriminatedResultMapNames.contains(rm.getId())) { entryResultMap.forceNestedResultMaps(); } } } } } } // Slow but a one time cost. A better solution is welcome. protected void checkLocallyForDiscriminatedNestedResultMaps(ResultMap rm) { if (!rm.hasNestedResultMaps() && rm.getDiscriminator() != null) { for (Map.Entry<String, String> entry : rm.getDiscriminator().getDiscriminatorMap().entrySet()) { String discriminatedResultMapName = entry.getValue(); if (hasResultMap(discriminatedResultMapName)) { ResultMap discriminatedResultMap = resultMaps.get(discriminatedResultMapName); if (discriminatedResultMap.hasNestedResultMaps()) { rm.forceNestedResultMaps(); break; } } } } } protected static class StrictMap<V> extends HashMap<String, V> { private static final long serialVersionUID = -4950446264854982944L; private final String name; private BiFunction<V, V, String> conflictMessageProducer; public StrictMap(String name, int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); this.name = name; } public StrictMap(String name, int initialCapacity) { super(initialCapacity); this.name = name; } public StrictMap(String name) { super(); this.name = name; } public StrictMap(String name, Map<String, ? extends V> m) { super(m); this.name = name; } /** * Assign a function for producing a conflict error message when contains value with the same key. * <p> * function arguments are 1st is saved value and 2nd is target value. * @param conflictMessageProducer A function for producing a conflict error message * @return a conflict error message * @since 3.5.0 */ public StrictMap<V> conflictMessageProducer(BiFunction<V, V, String> conflictMessageProducer) { this.conflictMessageProducer = conflictMessageProducer; return this; } // TODO 如果现在状态为刷新,则刷新(先删除后添加) @Override @SuppressWarnings("unchecked") public V put(String key, V value) { if (org.apache.ibatis.thread.Runnable.isRefresh()) { remove(key); org.apache.ibatis.thread.Runnable.log.debug("refresh key:" + key.substring(key.lastIndexOf(".") + 1)); } if (containsKey(key)) { throw new IllegalArgumentException(name + " already contains value for " + key + (conflictMessageProducer == null ? "" : conflictMessageProducer.apply(super.get(key), value))); } if (key.contains(".")) { final String shortKey = getShortName(key); if (super.get(shortKey) == null) { super.put(shortKey, value); } else { super.put(shortKey, (V) new Ambiguity(shortKey)); } } return super.put(key, value); } @Override public V get(Object key) { V value = super.get(key); if (value == null) { throw new IllegalArgumentException(name + " does not contain value for " + key); } if (value instanceof Ambiguity) { throw new IllegalArgumentException(((Ambiguity) value).getSubject() + " is ambiguous in " + name + " (try using the full name including the namespace, or rename one of the entries)"); } return value; } protected static class Ambiguity { private final String subject; public Ambiguity(String subject) { this.subject = subject; } public String getSubject() { return subject; } } private String getShortName(String key) { final String[] keyParts = key.split("\\."); return keyParts[keyParts.length - 1]; } } }
thinkgem/jeesite
src/main/java/org/apache/ibatis/session/Configuration.java
1,264
package com.macro.mall.common.api; /** * API返回码封装类 * Created by macro on 2019/4/19. */ public enum ResultCode implements IErrorCode { SUCCESS(200, "操作成功"), FAILED(500, "操作失败"), VALIDATE_FAILED(404, "参数检验失败"), UNAUTHORIZED(401, "暂未登录或token已经过期"), FORBIDDEN(403, "没有相关权限"); private long code; private String message; private ResultCode(long code, String message) { this.code = code; this.message = message; } public long getCode() { return code; } public String getMessage() { return message; } }
macrozheng/mall
mall-common/src/main/java/com/macro/mall/common/api/ResultCode.java
1,272
package io.mycat.statistic.stat; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicLong; import io.mycat.server.parser.ServerParse; /** * SQL R/W 执行状态 * 因为这里的所有元素都近似为非必须原子更新的,即: * 例如:rCount和netInBytes没有必要非得保持同步更新,在同一个事务内 * 只要最后更新了即可,所以将其中的元素拆成一个一个原子类,没必要保证精确的保持原样不加任何锁 * * @author zhuam * */ public class UserSqlRWStat { /** * R/W 次数 */ private AtomicLong rCount = new AtomicLong(0L); private AtomicLong wCount = new AtomicLong(0L); /** * 每秒QPS */ private int qps = 0; /** * Net In/Out 字节数 */ private AtomicLong netInBytes = new AtomicLong(0L); private AtomicLong netOutBytes = new AtomicLong(0L); /** * 最大的并发 */ private int concurrentMax = 1; /** * 执行耗时 * * 10毫秒内、 10 - 200毫秒内、 1秒内、 超过 1秒 */ private final Histogram timeHistogram = new Histogram( new long[] { 10, 200, 1000, 2000 } ); /** * 执行所在时段 * * 22-06 夜间、 06-13 上午、 13-18下午、 18-22 晚间 */ private final Histogram executeHistogram = new Histogram(new long[] { 6, 13, 18, 22 }); /** * 最后执行时间 * 不用很精确,所以不加任何锁 */ private long lastExecuteTime; private int time_zone_offset = 0; private int one_hour = 3600 * 1000; public UserSqlRWStat() { this.time_zone_offset = TimeZone.getDefault().getRawOffset(); } public void reset() { this.rCount = new AtomicLong(0L); this.wCount = new AtomicLong(0L); this.concurrentMax = 1; this.lastExecuteTime = 0; this.netInBytes = new AtomicLong(0L); this.netOutBytes = new AtomicLong(0L); this.timeHistogram.reset(); this.executeHistogram.reset(); } public void add(int sqlType, String sql, long executeTime, long netInBytes, long netOutBytes, long startTime, long endTime) { switch(sqlType) { case ServerParse.SELECT: case ServerParse.SHOW: this.rCount.incrementAndGet(); break; case ServerParse.UPDATE: case ServerParse.INSERT: case ServerParse.DELETE: case ServerParse.REPLACE: this.wCount.incrementAndGet(); break; } //SQL执行所在的耗时区间 if ( executeTime <= 10 ) { this.timeHistogram.record(10); } else if ( executeTime > 10 && executeTime <= 200 ) { this.timeHistogram.record(200); } else if ( executeTime > 200 && executeTime <= 1000 ) { this.timeHistogram.record(1000); } else if ( executeTime > 1000) { this.timeHistogram.record(2000); } //SQL执行所在的时间区间 long hour0 = endTime / ( 24L * (long)one_hour ) * ( 24L * (long)one_hour )- (long)time_zone_offset; long hour06 = hour0 + 6L * (long)one_hour - 1L; long hour13 = hour0 + 13L * (long)one_hour - 1L; long hour18 = hour0 + 18L * (long)one_hour - 1L; long hour22 = hour0 + 22L * (long)one_hour - 1L; if ( endTime <= hour06 || endTime > hour22 ) { this.executeHistogram.record(6); } else if ( endTime > hour06 && endTime <= hour13 ) { this.executeHistogram.record(13); } else if ( endTime > hour13 && endTime <= hour18 ) { this.executeHistogram.record(18); } else if ( endTime > hour18 && endTime <= hour22 ) { this.executeHistogram.record(22); } this.lastExecuteTime = endTime; this.netInBytes.addAndGet(netInBytes); this.netOutBytes.addAndGet(netOutBytes); } public long getLastExecuteTime() { return lastExecuteTime; } public long getNetInBytes() { return netInBytes.get(); } public long getNetOutBytes() { return netOutBytes.get(); } public int getConcurrentMax() { return concurrentMax; } public void setConcurrentMax(int concurrentMax) { this.concurrentMax = concurrentMax; } public int getQps() { return qps; } public void setQps(int qps) { this.qps = qps; } public long getRCount() { return this.rCount.get(); } public long getWCount() { return this.wCount.get(); } public Histogram getTimeHistogram() { return this.timeHistogram; } public Histogram getExecuteHistogram() { return this.executeHistogram; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/statistic/stat/UserSqlRWStat.java
1,275
package com.taobao.arthas.core.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * Arthas 使用情况统计 * <p/> * Created by zhuyong on 15/11/12. */ public class UserStatUtil { private static final int DEFAULT_BUFFER_SIZE = 8192; private static final byte[] SKIP_BYTE_BUFFER = new byte[DEFAULT_BUFFER_SIZE]; private static final ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { final Thread t = new Thread(r, "arthas-UserStat"); t.setDaemon(true); return t; } }); private static final String ip = IPUtils.getLocalIP(); private static final String version = URLEncoder.encode(ArthasBanner.version().replace("\n", "")); private static volatile String statUrl = null; private static volatile String agentId = null; public static String getStatUrl() { return statUrl; } public static void setStatUrl(String url) { statUrl = url; } public static String getAgentId() { return agentId; } public static void setAgentId(String id) { agentId = id; } public static void arthasStart() { if (statUrl == null) { return; } RemoteJob job = new RemoteJob(); job.appendQueryData("ip", ip); job.appendQueryData("version", version); if (agentId != null) { job.appendQueryData("agentId", agentId); } job.appendQueryData("command", "start"); try { executorService.execute(job); } catch (Throwable t) { // } } private static void arthasUsage(String cmd, String detail) { RemoteJob job = new RemoteJob(); job.appendQueryData("ip", ip); job.appendQueryData("version", version); if (agentId != null) { job.appendQueryData("agentId", agentId); } job.appendQueryData("command", URLEncoder.encode(cmd)); if (detail != null) { job.appendQueryData("arguments", URLEncoder.encode(detail)); } try { executorService.execute(job); } catch (Throwable t) { // } } public static void arthasUsageSuccess(String cmd, List<String> args) { if (statUrl == null) { return; } StringBuilder commandString = new StringBuilder(cmd); for (String arg : args) { commandString.append(" ").append(arg); } UserStatUtil.arthasUsage(cmd, commandString.toString()); } public static void destroy() { // 直接关闭,没有回报的丢弃 executorService.shutdownNow(); } static class RemoteJob implements Runnable { private StringBuilder queryData = new StringBuilder(); public void appendQueryData(String key, String value) { if (key != null && value != null) { if (queryData.length() == 0) { queryData.append(key).append("=").append(value); } else { queryData.append("&").append(key).append("=").append(value); } } } @Override public void run() { String link = statUrl; if (link == null) { return; } InputStream inputStream = null; try { if (queryData.length() != 0) { link = link + "?" + queryData; } URL url = new URL(link); URLConnection connection = url.openConnection(); connection.setConnectTimeout(1000); connection.setReadTimeout(1000); connection.connect(); inputStream = connection.getInputStream(); //noinspection StatementWithEmptyBody while (inputStream.read(SKIP_BYTE_BUFFER) != -1) { // do nothing } } catch (Throwable t) { // ignore } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // ignore } } } } } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/util/UserStatUtil.java
1,276
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson.orm; import java.sql.SQLException; import java.sql.Savepoint; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import apijson.NotNull; import apijson.RequestMethod; /**解析器 * @author Lemon */ public interface Parser<T extends Object> { @NotNull Visitor<T> getVisitor(); Parser<T> setVisitor(@NotNull Visitor<T> visitor); @NotNull RequestMethod getMethod(); Parser<T> setMethod(@NotNull RequestMethod method); int getVersion(); Parser<T> setVersion(int version); String getTag(); Parser<T> setTag(String tag); JSONObject getRequest(); Parser<T> setRequest(JSONObject request); Parser<T> setNeedVerify(boolean needVerify); boolean isNeedVerifyLogin(); Parser<T> setNeedVerifyLogin(boolean needVerifyLogin); boolean isNeedVerifyRole(); Parser<T> setNeedVerifyRole(boolean needVerifyRole); boolean isNeedVerifyContent(); Parser<T> setNeedVerifyContent(boolean needVerifyContent); String parse(String request); String parse(JSONObject request); JSONObject parseResponse(String request); JSONObject parseResponse(JSONObject request); // 没必要性能还差 JSONObject parseCorrectResponse(String table, JSONObject response) throws Exception; JSONObject parseCorrectRequest() throws Exception; JSONObject parseCorrectRequest(RequestMethod method, String tag, int version, String name, JSONObject request, int maxUpdateCount, SQLCreator creator) throws Exception; JSONObject getStructure(String table, String method, String tag, int version) throws Exception; JSONObject onObjectParse(JSONObject request, String parentPath, String name, SQLConfig<T> arrayConfig, boolean isSubquery) throws Exception; JSONArray onArrayParse(JSONObject request, String parentPath, String name, boolean isSubquery) throws Exception; /**解析远程函数 * @param key * @param function * @param parentPath * @param currentName * @param currentObject * @return * @throws Exception */ Object onFunctionParse(String key, String function, String parentPath, String currentName, JSONObject currentObject, boolean containRaw) throws Exception; ObjectParser<T> createObjectParser(JSONObject request, String parentPath, SQLConfig<T> arrayConfig, boolean isSubquery, boolean isTable, boolean isArrayMainTable) throws Exception; int getDefaultQueryCount(); int getMaxQueryPage(); int getMaxQueryCount(); int getMaxUpdateCount(); int getMaxSQLCount(); int getMaxObjectCount(); int getMaxArrayCount(); int getMaxQueryDepth(); void putQueryResult(String path, Object result); Object getValueByPath(String valuePath); void onVerifyLogin() throws Exception; void onVerifyContent() throws Exception; void onVerifyRole(SQLConfig<T> config) throws Exception; JSONObject executeSQL(SQLConfig<T> config, boolean isSubquery) throws Exception; SQLExecutor<T> getSQLExecutor(); Verifier<T> getVerifier(); Boolean getGlobalFormat(); String getGlobalRole(); String getGlobalDatabase(); String getGlobalSchema(); String getGlobalDatasource(); Boolean getGlobalExplain(); String getGlobalCache(); int getTransactionIsolation(); void setTransactionIsolation(int transactionIsolation); void begin(int transactionIsolation); void rollback() throws SQLException; void rollback(Savepoint savepoint) throws SQLException; void commit() throws SQLException; void close(); }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/Parser.java
1,284
package com.alibaba.otter.canal.common.utils; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.AbstractQueuedSynchronizer; /** * 实现一个互斥实现,基于Cocurrent中的AQS实现了自己的sync <br/> * 应用场景:系统初始化/授权控制,没权限时阻塞等待。有权限时所有线程都可以快速通过 * * <pre> * false : 代表需要被阻塞挂起,等待mutex变为true被唤醒 * true : 唤醒被阻塞在false状态下的thread * * BooleanMutex mutex = new BooleanMutex(true); * try { * mutex.get(); //当前状态为true, 不会被阻塞 * } catch (InterruptedException e) { * // do something * } * * mutex.set(false); * try { * mutex.get(); //当前状态为false, 会被阻塞直到另一个线程调用mutex.set(true); * } catch (InterruptedException e) { * // do something * } * </pre> * * @author jianghang 2011-9-23 上午09:58:03 * @version 1.0.0 */ public class BooleanMutex { private final Sync sync; public BooleanMutex(){ sync = new Sync(); set(false); } public BooleanMutex(Boolean mutex){ sync = new Sync(); set(mutex); } /** * 阻塞等待Boolean为true * * @throws InterruptedException if the current thread is interrupted */ public void get() throws InterruptedException { sync.innerGet(); } /** * 阻塞等待Boolean为true,允许设置超时时间 * * @param timeout * @param unit * @throws InterruptedException * @throws TimeoutException */ public void get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { sync.innerGet(unit.toNanos(timeout)); } /** * 重新设置对应的Boolean mutex * * @param mutex */ public void set(Boolean mutex) { if (mutex) { sync.innerSetTrue(); } else { sync.innerSetFalse(); } } public boolean state() { return sync.innerState(); } /** * Synchronization control for BooleanMutex. Uses AQS sync state to * represent run status */ private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 2559471934544126329L; /** State value representing that TRUE */ private static final int TRUE = 1; /** State value representing that FALSE */ private static final int FALSE = 2; private boolean isTrue(int state) { return (state & TRUE) != 0; } /** * 实现AQS的接口,获取共享锁的判断 */ protected int tryAcquireShared(int state) { // 如果为true,直接允许获取锁对象 // 如果为false,进入阻塞队列,等待被唤醒 return isTrue(getState()) ? 1 : -1; } /** * 实现AQS的接口,释放共享锁的判断 */ protected boolean tryReleaseShared(int ignore) { // 始终返回true,代表可以release return true; } boolean innerState() { return isTrue(getState()); } void innerGet() throws InterruptedException { acquireSharedInterruptibly(0); } void innerGet(long nanosTimeout) throws InterruptedException, TimeoutException { if (!tryAcquireSharedNanos(0, nanosTimeout)) throw new TimeoutException(); } void innerSetTrue() { for (;;) { int s = getState(); if (s == TRUE) { return; // 直接退出 } if (compareAndSetState(s, TRUE)) {// cas更新状态,避免并发更新true操作 releaseShared(0);// 释放一下锁对象,唤醒一下阻塞的Thread return; } } } void innerSetFalse() { for (;;) { int s = getState(); if (s == FALSE) { return; // 直接退出 } if (compareAndSetState(s, FALSE)) {// cas更新状态,避免并发更新false操作 return; } } } } }
alibaba/canal
common/src/main/java/com/alibaba/otter/canal/common/utils/BooleanMutex.java
1,287
package com.alibaba.otter.canal.store.memory; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang.StringUtils; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.CanalEntry.EventType; import com.alibaba.otter.canal.protocol.position.LogPosition; import com.alibaba.otter.canal.protocol.position.Position; import com.alibaba.otter.canal.protocol.position.PositionRange; import com.alibaba.otter.canal.store.AbstractCanalStoreScavenge; import com.alibaba.otter.canal.store.CanalEventStore; import com.alibaba.otter.canal.store.CanalStoreException; import com.alibaba.otter.canal.store.CanalStoreScavenge; import com.alibaba.otter.canal.store.helper.CanalEventUtils; import com.alibaba.otter.canal.store.model.BatchMode; import com.alibaba.otter.canal.store.model.Event; import com.alibaba.otter.canal.store.model.Events; /** * 基于内存buffer构建内存memory store * * <pre> * 变更记录: * 1. 新增BatchMode类型,支持按内存大小获取批次数据,内存大小更加可控. * a. put操作,会首先根据bufferSize进行控制,然后再进行bufferSize * bufferMemUnit进行控制. 因存储的内容是以Event,如果纯依赖于memsize进行控制,会导致RingBuffer出现动态伸缩 * </pre> * * @author jianghang 2012-6-20 上午09:46:31 * @version 1.0.0 */ public class MemoryEventStoreWithBuffer extends AbstractCanalStoreScavenge implements CanalEventStore<Event>, CanalStoreScavenge { private static final long INIT_SEQUENCE = -1; private int bufferSize = 16 * 1024; private int bufferMemUnit = 1024; // memsize的单位,默认为1kb大小 private int indexMask; private Event[] entries; // 记录下put/get/ack操作的三个下标 private AtomicLong putSequence = new AtomicLong(INIT_SEQUENCE); // 代表当前put操作最后一次写操作发生的位置 private AtomicLong getSequence = new AtomicLong(INIT_SEQUENCE); // 代表当前get操作读取的最后一条的位置 private AtomicLong ackSequence = new AtomicLong(INIT_SEQUENCE); // 代表当前ack操作的最后一条的位置 // 记录下put/get/ack操作的三个memsize大小 private AtomicLong putMemSize = new AtomicLong(0); private AtomicLong getMemSize = new AtomicLong(0); private AtomicLong ackMemSize = new AtomicLong(0); // 记录下put/get/ack操作的三个execTime private AtomicLong putExecTime = new AtomicLong(System.currentTimeMillis()); private AtomicLong getExecTime = new AtomicLong(System.currentTimeMillis()); private AtomicLong ackExecTime = new AtomicLong(System.currentTimeMillis()); // 记录下put/get/ack操作的三个table rows private AtomicLong putTableRows = new AtomicLong(0); private AtomicLong getTableRows = new AtomicLong(0); private AtomicLong ackTableRows = new AtomicLong(0); // 阻塞put/get操作控制信号 private ReentrantLock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); private BatchMode batchMode = BatchMode.ITEMSIZE; // 默认为内存大小模式 private boolean ddlIsolation = false; private boolean raw = true; // 针对entry是否开启raw模式 public MemoryEventStoreWithBuffer(){ } public MemoryEventStoreWithBuffer(BatchMode batchMode){ this.batchMode = batchMode; } public void start() throws CanalStoreException { super.start(); if (Integer.bitCount(bufferSize) != 1) { throw new IllegalArgumentException("bufferSize must be a power of 2"); } indexMask = bufferSize - 1; entries = new Event[bufferSize]; } public void stop() throws CanalStoreException { super.stop(); cleanAll(); } public void put(List<Event> data) throws InterruptedException, CanalStoreException { if (data == null || data.isEmpty()) { return; } final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { try { while (!checkFreeSlotAt(putSequence.get() + data.size())) { // 检查是否有空位 notFull.await(); // wait until not full } } catch (InterruptedException ie) { notFull.signal(); // propagate to non-interrupted thread throw ie; } doPut(data); if (Thread.interrupted()) { throw new InterruptedException(); } } finally { lock.unlock(); } } public boolean put(List<Event> data, long timeout, TimeUnit unit) throws InterruptedException, CanalStoreException { if (data == null || data.isEmpty()) { return true; } long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { if (checkFreeSlotAt(putSequence.get() + data.size())) { doPut(data); return true; } if (nanos <= 0) { return false; } try { nanos = notFull.awaitNanos(nanos); } catch (InterruptedException ie) { notFull.signal(); // propagate to non-interrupted thread throw ie; } } } finally { lock.unlock(); } } public boolean tryPut(List<Event> data) throws CanalStoreException { if (data == null || data.isEmpty()) { return true; } final ReentrantLock lock = this.lock; lock.lock(); try { if (!checkFreeSlotAt(putSequence.get() + data.size())) { return false; } else { doPut(data); return true; } } finally { lock.unlock(); } } public void put(Event data) throws InterruptedException, CanalStoreException { put(Arrays.asList(data)); } public boolean put(Event data, long timeout, TimeUnit unit) throws InterruptedException, CanalStoreException { return put(Arrays.asList(data), timeout, unit); } public boolean tryPut(Event data) throws CanalStoreException { return tryPut(Arrays.asList(data)); } /** * 执行具体的put操作 */ private void doPut(List<Event> data) { long current = putSequence.get(); long end = current + data.size(); // 先写数据,再更新对应的cursor,并发度高的情况,putSequence会被get请求可见,拿出了ringbuffer中的老的Entry值 for (long next = current + 1; next <= end; next++) { entries[getIndex(next)] = data.get((int) (next - current - 1)); } putSequence.set(end); // 记录一下gets memsize信息,方便快速检索 if (batchMode.isMemSize()) { long size = 0; for (Event event : data) { size += calculateSize(event); } putMemSize.getAndAdd(size); } profiling(data, OP.PUT); // tell other threads that store is not empty notEmpty.signal(); } public Events<Event> get(Position start, int batchSize) throws InterruptedException, CanalStoreException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { try { while (!checkUnGetSlotAt((LogPosition) start, batchSize)) notEmpty.await(); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread throw ie; } return doGet(start, batchSize); } finally { lock.unlock(); } } public Events<Event> get(Position start, int batchSize, long timeout, TimeUnit unit) throws InterruptedException, CanalStoreException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (;;) { if (checkUnGetSlotAt((LogPosition) start, batchSize)) { return doGet(start, batchSize); } if (nanos <= 0) { // 如果时间到了,有多少取多少 return doGet(start, batchSize); } try { nanos = notEmpty.awaitNanos(nanos); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread throw ie; } } } finally { lock.unlock(); } } public Events<Event> tryGet(Position start, int batchSize) throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { return doGet(start, batchSize); } finally { lock.unlock(); } } private Events<Event> doGet(Position start, int batchSize) throws CanalStoreException { LogPosition startPosition = (LogPosition) start; long current = getSequence.get(); long maxAbleSequence = putSequence.get(); long next = current; long end = current; // 如果startPosition为null,说明是第一次,默认+1处理 if (startPosition == null || !startPosition.getPostion().isIncluded()) { // 第一次订阅之后,需要包含一下start位置,防止丢失第一条记录 next = next + 1; } if (current >= maxAbleSequence) { return new Events<>(); } Events<Event> result = new Events<>(); List<Event> entrys = result.getEvents(); long memsize = 0; if (batchMode.isItemSize()) { end = (next + batchSize - 1) < maxAbleSequence ? (next + batchSize - 1) : maxAbleSequence; // 提取数据并返回 for (; next <= end; next++) { Event event = entries[getIndex(next)]; if (ddlIsolation && isDdl(event.getEventType())) { // 如果是ddl隔离,直接返回 if (entrys.size() == 0) { entrys.add(event);// 如果没有DML事件,加入当前的DDL事件 end = next; // 更新end为当前 } else { // 如果之前已经有DML事件,直接返回了,因为不包含当前next这记录,需要回退一个位置 end = next - 1; // next-1一定大于current,不需要判断 } break; } else { entrys.add(event); } } } else { long maxMemSize = batchSize * bufferMemUnit; for (; memsize <= maxMemSize && next <= maxAbleSequence; next++) { // 永远保证可以取出第一条的记录,避免死锁 Event event = entries[getIndex(next)]; if (ddlIsolation && isDdl(event.getEventType())) { // 如果是ddl隔离,直接返回 if (entrys.size() == 0) { entrys.add(event);// 如果没有DML事件,加入当前的DDL事件 end = next; // 更新end为当前 } else { // 如果之前已经有DML事件,直接返回了,因为不包含当前next这记录,需要回退一个位置 end = next - 1; // next-1一定大于current,不需要判断 } break; } else { entrys.add(event); memsize += calculateSize(event); end = next;// 记录end位点 } } } PositionRange<LogPosition> range = new PositionRange<>(); result.setPositionRange(range); range.setStart(CanalEventUtils.createPosition(entrys.get(0))); range.setEnd(CanalEventUtils.createPosition(entrys.get(result.getEvents().size() - 1))); range.setEndSeq(end); // 记录一下是否存在可以被ack的点 for (int i = entrys.size() - 1; i >= 0; i--) { Event event = entrys.get(i); // GTID模式,ack的位点必须是事务结尾,因为下一次订阅的时候mysql会发送这个gtid之后的next,如果在事务头就记录了会丢这最后一个事务 if ((CanalEntry.EntryType.TRANSACTIONBEGIN == event.getEntryType() && StringUtils.isEmpty(event.getGtid())) || CanalEntry.EntryType.TRANSACTIONEND == event.getEntryType() || isDdl(event.getEventType())) { // 将事务头/尾设置可被为ack的点 range.setAck(CanalEventUtils.createPosition(event)); break; } } if (getSequence.compareAndSet(current, end)) { getMemSize.addAndGet(memsize); notFull.signal(); profiling(result.getEvents(), OP.GET); return result; } else { return new Events<>(); } } public LogPosition getFirstPosition() throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { long firstSeqeuence = ackSequence.get(); if (firstSeqeuence == INIT_SEQUENCE && firstSeqeuence < putSequence.get()) { // 没有ack过数据 Event event = entries[getIndex(firstSeqeuence + 1)]; // 最后一次ack为-1,需要移动到下一条,included // = false return CanalEventUtils.createPosition(event, false); } else if (firstSeqeuence > INIT_SEQUENCE && firstSeqeuence < putSequence.get()) { // ack未追上put操作 Event event = entries[getIndex(firstSeqeuence)]; // 最后一次ack的位置数据,需要移动到下一条,included // = false return CanalEventUtils.createPosition(event, false); } else if (firstSeqeuence > INIT_SEQUENCE && firstSeqeuence == putSequence.get()) { // 已经追上,store中没有数据 Event event = entries[getIndex(firstSeqeuence)]; // 最后一次ack的位置数据,和last为同一条,included // = false return CanalEventUtils.createPosition(event, false); } else { // 没有任何数据 return null; } } finally { lock.unlock(); } } public LogPosition getLatestPosition() throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { long latestSequence = putSequence.get(); if (latestSequence > INIT_SEQUENCE && latestSequence != ackSequence.get()) { Event event = entries[(int) putSequence.get() & indexMask]; // 最后一次写入的数据,最后一条未消费的数据 return CanalEventUtils.createPosition(event, true); } else if (latestSequence > INIT_SEQUENCE && latestSequence == ackSequence.get()) { // ack已经追上了put操作 Event event = entries[(int) putSequence.get() & indexMask]; // 最后一次写入的数据,included // = // false return CanalEventUtils.createPosition(event, false); } else { // 没有任何数据 return null; } } finally { lock.unlock(); } } public void ack(Position position) throws CanalStoreException { cleanUntil(position, -1L); } public void ack(Position position, Long seqId) throws CanalStoreException { cleanUntil(position, seqId); } @Override public void cleanUntil(Position position) throws CanalStoreException { cleanUntil(position, -1L); } public void cleanUntil(Position position, Long seqId) throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { long sequence = ackSequence.get(); long maxSequence = getSequence.get(); boolean hasMatch = false; long memsize = 0; // ack没有list,但有已存在的foreach,还是节省一下list的开销 long localExecTime = 0L; int deltaRows = 0; if (seqId > 0) { maxSequence = seqId; } for (long next = sequence + 1; next <= maxSequence; next++) { Event event = entries[getIndex(next)]; if (localExecTime == 0 && event.getExecuteTime() > 0) { localExecTime = event.getExecuteTime(); } deltaRows += event.getRowsCount(); memsize += calculateSize(event); if ((seqId < 0 || next == seqId) && CanalEventUtils.checkPosition(event, (LogPosition) position)) { // 找到对应的position,更新ack seq hasMatch = true; if (batchMode.isMemSize()) { ackMemSize.addAndGet(memsize); // 尝试清空buffer中的内存,将ack之前的内存全部释放掉 for (long index = sequence + 1; index < next; index++) { entries[getIndex(index)] = null;// 设置为null } // 考虑getFirstPosition/getLastPosition会获取最后一次ack的position信息 // ack清理的时候只处理entry=null,释放内存 Event lastEvent = entries[getIndex(next)]; lastEvent.setEntry(null); lastEvent.setRawEntry(null); } if (ackSequence.compareAndSet(sequence, next)) {// 避免并发ack notFull.signal(); ackTableRows.addAndGet(deltaRows); if (localExecTime > 0) { ackExecTime.lazySet(localExecTime); } return; } } } if (!hasMatch) {// 找不到对应需要ack的position throw new CanalStoreException("no match ack position" + position.toString()); } } finally { lock.unlock(); } } public void rollback() throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { getSequence.set(ackSequence.get()); getMemSize.set(ackMemSize.get()); } finally { lock.unlock(); } } public void cleanAll() throws CanalStoreException { final ReentrantLock lock = this.lock; lock.lock(); try { putSequence.set(INIT_SEQUENCE); getSequence.set(INIT_SEQUENCE); ackSequence.set(INIT_SEQUENCE); putMemSize.set(0); getMemSize.set(0); ackMemSize.set(0); entries = null; // for (int i = 0; i < entries.length; i++) { // entries[i] = null; // } } finally { lock.unlock(); } } // =================== helper method ================= private long getMinimumGetOrAck() { long get = getSequence.get(); long ack = ackSequence.get(); return ack <= get ? ack : get; } /** * 查询是否有空位 */ private boolean checkFreeSlotAt(final long sequence) { final long wrapPoint = sequence - bufferSize; final long minPoint = getMinimumGetOrAck(); if (wrapPoint > minPoint) { // 刚好追上一轮 return false; } else { // 在bufferSize模式上,再增加memSize控制 if (batchMode.isMemSize()) { final long memsize = putMemSize.get() - ackMemSize.get(); if (memsize < bufferSize * bufferMemUnit) { return true; } else { return false; } } else { return true; } } } /** * 检查是否存在需要get的数据,并且数量>=batchSize */ private boolean checkUnGetSlotAt(LogPosition startPosition, int batchSize) { if (batchMode.isItemSize()) { long current = getSequence.get(); long maxAbleSequence = putSequence.get(); long next = current; if (startPosition == null || !startPosition.getPostion().isIncluded()) { // 第一次订阅之后,需要包含一下start位置,防止丢失第一条记录 next = next + 1;// 少一条数据 } if (current < maxAbleSequence && next + batchSize - 1 <= maxAbleSequence) { return true; } else { return false; } } else { // 处理内存大小判断 long currentSize = getMemSize.get(); long maxAbleSize = putMemSize.get(); if (maxAbleSize - currentSize >= batchSize * bufferMemUnit) { return true; } else { return false; } } } private long calculateSize(Event event) { // 直接返回binlog中的事件大小 return event.getRawLength(); } private int getIndex(long sequcnce) { return (int) sequcnce & indexMask; } private boolean isDdl(EventType type) { return type == EventType.ALTER || type == EventType.CREATE || type == EventType.ERASE || type == EventType.RENAME || type == EventType.TRUNCATE || type == EventType.CINDEX || type == EventType.DINDEX; } private void profiling(List<Event> events, OP op) { long localExecTime = 0L; int deltaRows = 0; if (events != null && !events.isEmpty()) { for (Event e : events) { if (localExecTime == 0 && e.getExecuteTime() > 0) { localExecTime = e.getExecuteTime(); } deltaRows += e.getRowsCount(); } } switch (op) { case PUT: putTableRows.addAndGet(deltaRows); if (localExecTime > 0) { putExecTime.lazySet(localExecTime); } break; case GET: getTableRows.addAndGet(deltaRows); if (localExecTime > 0) { getExecTime.lazySet(localExecTime); } break; case ACK: ackTableRows.addAndGet(deltaRows); if (localExecTime > 0) { ackExecTime.lazySet(localExecTime); } break; default: break; } } private enum OP { PUT, GET, ACK } // ================ setter / getter ================== public int getBufferSize() { return this.bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public void setBufferMemUnit(int bufferMemUnit) { this.bufferMemUnit = bufferMemUnit; } public void setBatchMode(BatchMode batchMode) { this.batchMode = batchMode; } public void setDdlIsolation(boolean ddlIsolation) { this.ddlIsolation = ddlIsolation; } public boolean isRaw() { return raw; } public void setRaw(boolean raw) { this.raw = raw; } public AtomicLong getPutSequence() { return putSequence; } public AtomicLong getAckSequence() { return ackSequence; } public AtomicLong getPutMemSize() { return putMemSize; } public AtomicLong getAckMemSize() { return ackMemSize; } public BatchMode getBatchMode() { return batchMode; } public AtomicLong getPutExecTime() { return putExecTime; } public AtomicLong getGetExecTime() { return getExecTime; } public AtomicLong getAckExecTime() { return ackExecTime; } public AtomicLong getPutTableRows() { return putTableRows; } public AtomicLong getGetTableRows() { return getTableRows; } public AtomicLong getAckTableRows() { return ackTableRows; } }
alibaba/canal
store/src/main/java/com/alibaba/otter/canal/store/memory/MemoryEventStoreWithBuffer.java
1,289
package com.alibaba.otter.canal.meta; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.apache.commons.lang.StringUtils; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson2.JSONWriter; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.common.utils.JsonUtils; import com.alibaba.otter.canal.common.zookeeper.ZkClientx; import com.alibaba.otter.canal.common.zookeeper.ZookeeperPathUtils; import com.alibaba.otter.canal.meta.exception.CanalMetaManagerException; import com.alibaba.otter.canal.protocol.ClientIdentity; import com.alibaba.otter.canal.protocol.position.Position; import com.alibaba.otter.canal.protocol.position.PositionRange; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * zk 版本的 canal manager, 存储结构: * * <pre> * /otter * canal * destinations * dest1 * client1 * filter * batch_mark * 1 * 2 * 3 * </pre> * * @author zebin.xuzb @ 2012-6-21 * @author jianghang * @version 1.0.0 */ public class ZooKeeperMetaManager extends AbstractCanalLifeCycle implements CanalMetaManager { private static final String ENCODE = "UTF-8"; private ZkClientx zkClientx; public void start() { super.start(); Assert.notNull(zkClientx); } public void stop() { zkClientx = null; //关闭时置空 super.stop(); } public void subscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getClientIdNodePath(clientIdentity.getDestination(), clientIdentity.getClientId()); try { zkClientx.createPersistent(path, true); } catch (ZkNodeExistsException e) { // ignore } if (clientIdentity.hasFilter()) { String filterPath = ZookeeperPathUtils.getFilterPath(clientIdentity.getDestination(), clientIdentity.getClientId()); byte[] bytes = null; try { bytes = clientIdentity.getFilter().getBytes(ENCODE); } catch (UnsupportedEncodingException e) { throw new CanalMetaManagerException(e); } try { zkClientx.createPersistent(filterPath, bytes); } catch (ZkNodeExistsException e) { // ignore zkClientx.writeData(filterPath, bytes); } } } public boolean hasSubscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getClientIdNodePath(clientIdentity.getDestination(), clientIdentity.getClientId()); return zkClientx.exists(path); } public void unsubscribe(ClientIdentity clientIdentity) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getClientIdNodePath(clientIdentity.getDestination(), clientIdentity.getClientId()); zkClientx.deleteRecursive(path); // 递归删除所有信息 } public List<ClientIdentity> listAllSubscribeInfo(String destination) throws CanalMetaManagerException { if (zkClientx == null) { //重新加载时可能为空 return new ArrayList<>(); } String path = ZookeeperPathUtils.getDestinationPath(destination); List<String> childs = null; try { childs = zkClientx.getChildren(path); } catch (ZkNoNodeException e) { // ignore } if (CollectionUtils.isEmpty(childs)) { return new ArrayList<>(); } List<Short> clientIds = new ArrayList<>(); for (String child : childs) { if (StringUtils.isNumeric(child)) { clientIds.add(ZookeeperPathUtils.getClientId(child)); } } Collections.sort(clientIds); // 进行一个排序 List<ClientIdentity> clientIdentities = Lists.newArrayList(); for (Short clientId : clientIds) { path = ZookeeperPathUtils.getFilterPath(destination, clientId); byte[] bytes = zkClientx.readData(path, true); String filter = null; if (bytes != null) { try { filter = new String(bytes, ENCODE); } catch (UnsupportedEncodingException e) { throw new CanalMetaManagerException(e); } } clientIdentities.add(new ClientIdentity(destination, clientId, filter)); } return clientIdentities; } public Position getCursor(ClientIdentity clientIdentity) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getCursorPath(clientIdentity.getDestination(), clientIdentity.getClientId()); byte[] data = zkClientx.readData(path, true); if (data == null || data.length == 0) { return null; } return JsonUtils.unmarshalFromByte(data, Position.class); } public void updateCursor(ClientIdentity clientIdentity, Position position) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getCursorPath(clientIdentity.getDestination(), clientIdentity.getClientId()); byte[] data = JsonUtils.marshalToByte(position, JSONWriter.Feature.WriteClassName); try { zkClientx.writeData(path, data); } catch (ZkNoNodeException e) { zkClientx.createPersistent(path, data, true);// 第一次节点不存在,则尝试重建 } } public Long addBatch(ClientIdentity clientIdentity, PositionRange positionRange) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); byte[] data = JsonUtils.marshalToByte(positionRange, JSONWriter.Feature.WriteClassName); String batchPath = zkClientx .createPersistentSequential(path + ZookeeperPathUtils.ZOOKEEPER_SEPARATOR, data, true); String batchIdString = StringUtils.substringAfterLast(batchPath, ZookeeperPathUtils.ZOOKEEPER_SEPARATOR); return ZookeeperPathUtils.getBatchMarkId(batchIdString); } public void addBatch(ClientIdentity clientIdentity, PositionRange positionRange, Long batchId) throws CanalMetaManagerException { String path = ZookeeperPathUtils .getBatchMarkWithIdPath(clientIdentity.getDestination(), clientIdentity.getClientId(), batchId); byte[] data = JsonUtils.marshalToByte(positionRange, JSONWriter.Feature.WriteClassName); zkClientx.createPersistent(path, data, true); } public PositionRange removeBatch(ClientIdentity clientIdentity, Long batchId) throws CanalMetaManagerException { String batchsPath = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); List<String> nodes = zkClientx.getChildren(batchsPath); if (CollectionUtils.isEmpty(nodes)) { // 没有batch记录 return null; } // 找到最小的Id ArrayList<Long> batchIds = new ArrayList<>(nodes.size()); for (String batchIdString : nodes) { batchIds.add(Long.valueOf(batchIdString)); } Long minBatchId = Collections.min(batchIds); if (!minBatchId.equals(batchId)) { // 检查一下提交的ack/rollback,必须按batchId分出去的顺序提交,否则容易出现丢数据 throw new CanalMetaManagerException(String.format("batchId:%d is not the firstly:%d", batchId, minBatchId)); } if (!batchIds.contains(batchId)) { // 不存在对应的batchId return null; } PositionRange positionRange = getBatch(clientIdentity, batchId); if (positionRange != null) { String path = ZookeeperPathUtils .getBatchMarkWithIdPath(clientIdentity.getDestination(), clientIdentity.getClientId(), batchId); zkClientx.delete(path); } return positionRange; } public PositionRange getBatch(ClientIdentity clientIdentity, Long batchId) throws CanalMetaManagerException { String path = ZookeeperPathUtils .getBatchMarkWithIdPath(clientIdentity.getDestination(), clientIdentity.getClientId(), batchId); byte[] data = zkClientx.readData(path, true); if (data == null) { return null; } PositionRange positionRange = JsonUtils.unmarshalFromByte(data, PositionRange.class); return positionRange; } public void clearAllBatchs(ClientIdentity clientIdentity) throws CanalMetaManagerException { String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); List<String> batchChilds = zkClientx.getChildren(path); for (String batchChild : batchChilds) { String batchPath = path + ZookeeperPathUtils.ZOOKEEPER_SEPARATOR + batchChild; zkClientx.delete(batchPath); } } public PositionRange getLastestBatch(ClientIdentity clientIdentity) { String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); List<String> nodes = null; try { nodes = zkClientx.getChildren(path); } catch (ZkNoNodeException e) { // ignore } if (CollectionUtils.isEmpty(nodes)) { return null; } // 找到最大的Id ArrayList<Long> batchIds = new ArrayList<>(nodes.size()); for (String batchIdString : nodes) { batchIds.add(Long.valueOf(batchIdString)); } Long maxBatchId = Collections.max(batchIds); PositionRange result = getBatch(clientIdentity, maxBatchId); if (result == null) { // 出现为null,说明zk节点有变化,重新获取 return getLastestBatch(clientIdentity); } else { return result; } } public PositionRange getFirstBatch(ClientIdentity clientIdentity) { String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); List<String> nodes = null; try { nodes = zkClientx.getChildren(path); } catch (ZkNoNodeException e) { // ignore } if (CollectionUtils.isEmpty(nodes)) { return null; } // 找到最小的Id ArrayList<Long> batchIds = new ArrayList<>(nodes.size()); for (String batchIdString : nodes) { batchIds.add(Long.valueOf(batchIdString)); } Long minBatchId = Collections.min(batchIds); PositionRange result = getBatch(clientIdentity, minBatchId); if (result == null) { // 出现为null,说明zk节点有变化,重新获取 return getFirstBatch(clientIdentity); } else { return result; } } public Map<Long, PositionRange> listAllBatchs(ClientIdentity clientIdentity) { String path = ZookeeperPathUtils.getBatchMarkPath(clientIdentity.getDestination(), clientIdentity.getClientId()); List<String> nodes = null; try { nodes = zkClientx.getChildren(path); } catch (ZkNoNodeException e) { // ignore } if (CollectionUtils.isEmpty(nodes)) { return Maps.newHashMap(); } // 找到最大的Id ArrayList<Long> batchIds = new ArrayList<>(nodes.size()); for (String batchIdString : nodes) { batchIds.add(Long.valueOf(batchIdString)); } Collections.sort(batchIds); // 从小到大排序 Map<Long, PositionRange> positionRanges = Maps.newLinkedHashMap(); for (Long batchId : batchIds) { PositionRange result = getBatch(clientIdentity, batchId); if (result == null) {// 出现为null,说明zk节点有变化,重新获取 return listAllBatchs(clientIdentity); } else { positionRanges.put(batchId, result); } } return positionRanges; } // =========== setter ========== public void setZkClientx(ZkClientx zkClientx) { this.zkClientx = zkClientx; } }
alibaba/canal
meta/src/main/java/com/alibaba/otter/canal/meta/ZooKeeperMetaManager.java
1,290
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat.helper; public enum Status { NO_MAP(0), // 原始日志没有被混淆 NOT_MAPPED(1), // 原始日志被混淆,还没有反混淆 MAPPING(2), // 正在反混淆 MAPPED(3), // 原始日志被混淆,且已经反混淆 FAILED(4); // 反混淆失败 private int m_status; private Status(int status) { m_status = status; } public int getStatus() { return m_status; } }
dianping/cat
cat-core/src/main/java/com/dianping/cat/helper/Status.java
1,293
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.dialect.odps.parser; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.parser.*; import java.util.HashMap; import java.util.Map; import static com.alibaba.druid.sql.parser.CharTypes.*; import static com.alibaba.druid.sql.parser.LayoutCharacters.EOI; public class OdpsLexer extends Lexer { public static final Keywords DEFAULT_ODPS_KEYWORDS; static { Map<String, Token> map = new HashMap<String, Token>(); map.putAll(Keywords.DEFAULT_KEYWORDS.getKeywords()); map.put("SHOW", Token.SHOW); map.put("PARTITION", Token.PARTITION); map.put("PARTITIONED", Token.PARTITIONED); map.put("OVERWRITE", Token.OVERWRITE); map.put("OVER", Token.OVER); map.put("LIMIT", Token.LIMIT); map.put("IF", Token.IF); map.put("DISTRIBUTE", Token.DISTRIBUTE); map.put("TRUE", Token.TRUE); map.put("FALSE", Token.FALSE); map.put("RLIKE", Token.RLIKE); map.put("DIV", Token.DIV); map.put("LATERAL", Token.LATERAL); map.put("QUALIFY", Token.QUALIFY); map.put(";", Token.SEMI); DEFAULT_ODPS_KEYWORDS = new Keywords(map); } public OdpsLexer(String input, SQLParserFeature... features) { super(input); init(); dbType = DbType.odps; super.keywords = DEFAULT_ODPS_KEYWORDS; this.skipComment = true; this.keepComments = false; for (SQLParserFeature feature : features) { config(feature, true); } } public OdpsLexer(String input, boolean skipComment, boolean keepComments) { super(input, skipComment); init(); dbType = DbType.odps; this.skipComment = skipComment; this.keepComments = keepComments; super.keywords = DEFAULT_ODPS_KEYWORDS; } public OdpsLexer(String input, CommentHandler commentHandler) { super(input, commentHandler); init(); dbType = DbType.odps; super.keywords = DEFAULT_ODPS_KEYWORDS; } private void init() { if (ch == '】' || ch == ' ' || ch == ',' || ch == ':' || ch == '、' || ch == '\u200C' || ch == ';') { ch = charAt(++pos); } if (ch == '上' && charAt(pos + 1) == '传') { pos += 2; ch = charAt(pos); while (isWhitespace(ch)) { ch = charAt(++pos); } } } public void scanComment() { scanHiveComment(); } public void scanIdentifier() { hashLCase = 0; hash = 0; final char first = ch; if (first == '`') { mark = pos; bufPos = 1; char ch; for (; ; ) { ch = charAt(++pos); if (ch == '`') { bufPos++; ch = charAt(++pos); if (ch == '`') { ch = charAt(++pos); continue; } break; } else if (ch == EOI) { throw new ParserException("illegal identifier. " + info()); } bufPos++; continue; } this.ch = charAt(pos); stringVal = subString(mark, bufPos); token = Token.IDENTIFIER; return; } final boolean firstFlag = isFirstIdentifierChar(first) || ch == 'å' || ch == 'ß' || ch == 'ç'; if (!firstFlag) { throw new ParserException("illegal identifier. " + info()); } mark = pos; bufPos = 1; char ch; for (; ; ) { ch = charAt(++pos); if (ch != 'ó' && ch != 'å' && ch != 'é' && ch != 'í' && ch != 'ß' && ch != 'ü' && !isIdentifierChar(ch)) { if (ch == '{' && charAt(pos - 1) == '$') { int endIndex = this.text.indexOf('}', pos); if (endIndex != -1) { bufPos += (endIndex - pos + 1); pos = endIndex; continue; } } if (ch == '-' && bufPos > 7 && text.regionMatches(false, mark, "ALIYUN$", 0, 7)) { continue; } break; } if (ch == ';') { break; } bufPos++; continue; } this.ch = charAt(pos); if (ch == '@') { // for user identifier bufPos++; for (; ; ) { ch = charAt(++pos); if (ch != '-' && ch != '.' && !isIdentifierChar(ch)) { break; } bufPos++; continue; } } this.ch = charAt(pos); // bufPos { final int LEN = "USING#CODE".length(); if (bufPos == LEN && text.regionMatches(mark, "USING#CODE", 0, LEN)) { bufPos = "USING".length(); pos -= 5; this.ch = charAt(pos); } } stringVal = addSymbol(); Token tok = keywords.getKeyword(stringVal); if (tok != null) { token = tok; } else { token = Token.IDENTIFIER; } } public void scanVariable() { if (ch == ':') { token = Token.COLON; ch = charAt(++pos); return; } if (ch == '#' && (charAt(pos + 1) == 'C' || charAt(pos + 1) == 'c') && (charAt(pos + 2) == 'O' || charAt(pos + 2) == 'o') && (charAt(pos + 3) == 'D' || charAt(pos + 3) == 'd') && (charAt(pos + 4) == 'E' || charAt(pos + 4) == 'e') ) { int p1 = text.indexOf("#END CODE", pos + 1); int p2 = text.indexOf("#end code", pos + 1); if (p1 == -1) { p1 = p2; } else if (p1 > p2 && p2 != -1) { p1 = p2; } if (p1 != -1) { int end = p1 + "#END CODE".length(); stringVal = text.substring(pos, end); token = Token.CODE; pos = end; ch = charAt(pos); return; } } super.scanVariable(); } protected void scanVariable_at() { scanVariable(); } protected final void scanString() { scanString2(); } }
alibaba/druid
core/src/main/java/com/alibaba/druid/sql/dialect/odps/parser/OdpsLexer.java
1,295
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.config.loader.xml; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.config.loader.SchemaLoader; import io.mycat.config.model.*; import io.mycat.config.model.rule.RuleConfig; import io.mycat.config.model.rule.TableRuleConfig; import io.mycat.config.util.ConfigException; import io.mycat.config.util.ConfigUtil; import io.mycat.route.function.AbstractPartitionAlgorithm; import io.mycat.route.function.TableRuleAware; import io.mycat.util.DecryptUtil; import io.mycat.util.ObjectUtil; import io.mycat.util.SplitUtil; import io.mycat.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.text.SimpleDateFormat; import java.util.*; /** * @author mycat */ @SuppressWarnings("unchecked") public class XMLSchemaLoader implements SchemaLoader { private static final Logger LOGGER = LoggerFactory.getLogger(XMLSchemaLoader.class); private final static String DEFAULT_DTD = "/schema.dtd"; private final static String DEFAULT_XML = "/schema.xml"; private final Map<String, TableRuleConfig> tableRules; private final Map<String, DataHostConfig> dataHosts; private final Map<String, DataNodeConfig> dataNodes; private final Map<String, SchemaConfig> schemas; public XMLSchemaLoader(String schemaFile, String ruleFile) { //先读取rule.xml XMLRuleLoader ruleLoader = new XMLRuleLoader(ruleFile); //将tableRules拿出,用于这里加载Schema做rule有效判断,以及之后的分片路由计算 this.tableRules = ruleLoader.getTableRules(); //释放ruleLoader ruleLoader = null; this.dataHosts = new HashMap<String, DataHostConfig>(); this.dataNodes = new HashMap<String, DataNodeConfig>(); this.schemas = new HashMap<String, SchemaConfig>(); //读取加载schema配置 this.load(DEFAULT_DTD, schemaFile == null ? DEFAULT_XML : schemaFile); } public XMLSchemaLoader() { this(null, null); } @Override public Map<String, TableRuleConfig> getTableRules() { return tableRules; } @Override public Map<String, DataHostConfig> getDataHosts() { return (Map<String, DataHostConfig>) (dataHosts.isEmpty() ? Collections.emptyMap() : dataHosts); } @Override public Map<String, DataNodeConfig> getDataNodes() { return (Map<String, DataNodeConfig>) (dataNodes.isEmpty() ? Collections.emptyMap() : dataNodes); } @Override public Map<String, SchemaConfig> getSchemas() { return (Map<String, SchemaConfig>) (schemas.isEmpty() ? Collections.emptyMap() : schemas); } private void load(String dtdFile, String xmlFile) { InputStream dtd = null; InputStream xml = null; try { dtd = XMLSchemaLoader.class.getResourceAsStream(dtdFile); xml = XMLSchemaLoader.class.getResourceAsStream(xmlFile); Element root = ConfigUtil.getDocument(dtd, xml).getDocumentElement(); //先加载所有的DataHost loadDataHosts(root); //再加载所有的DataNode loadDataNodes(root); //最后加载所有的Schema loadSchemas(root); } catch (ConfigException e) { throw e; } catch (Exception e) { throw new ConfigException(e); } finally { if (dtd != null) { try { dtd.close(); } catch (IOException e) { } } if (xml != null) { try { xml.close(); } catch (IOException e) { } } } } private void loadSchemas(Element root) { NodeList list = root.getElementsByTagName("schema"); for (int i = 0, n = list.getLength(); i < n; i++) { Element schemaElement = (Element) list.item(i); //读取各个属性 String name = schemaElement.getAttribute("name"); String dataNode = schemaElement.getAttribute("dataNode"); String randomDataNode = schemaElement.getAttribute("randomDataNode"); String checkSQLSchemaStr = schemaElement.getAttribute("checkSQLschema"); String sqlMaxLimitStr = schemaElement.getAttribute("sqlMaxLimit"); int sqlMaxLimit = -1; //读取sql返回结果集限制 if (sqlMaxLimitStr != null && !sqlMaxLimitStr.isEmpty()) { sqlMaxLimit = Integer.parseInt(sqlMaxLimitStr); } // check dataNode already exists or not,看schema标签中是否有datanode String defaultDbType = null; //校验检查并添加dataNode if (dataNode != null && !dataNode.isEmpty()) { List<String> dataNodeLst = new ArrayList<String>(1); dataNodeLst.add(dataNode); checkDataNodeExists(dataNodeLst); String dataHost = dataNodes.get(dataNode).getDataHost(); defaultDbType = dataHosts.get(dataHost).getDbType(); } else { dataNode = null; } //加载schema下所有tables Map<String, TableConfig> tables = loadTables(schemaElement); //判断schema是否重复 if (schemas.containsKey(name)) { throw new ConfigException("schema " + name + " duplicated!"); } // 设置了table的不需要设置dataNode属性,没有设置table的必须设置dataNode属性 if (dataNode == null && tables.size() == 0) { throw new ConfigException( "schema " + name + " didn't config tables,so you must set dataNode property!"); } SchemaConfig schemaConfig = new SchemaConfig(name, dataNode, tables, sqlMaxLimit, "true".equalsIgnoreCase(checkSQLSchemaStr),randomDataNode); //设定DB类型,这对之后的sql语句路由解析有帮助 if (defaultDbType != null) { schemaConfig.setDefaultDataNodeDbType(defaultDbType); if (!"mysql".equalsIgnoreCase(defaultDbType)) { schemaConfig.setNeedSupportMultiDBType(true); } } // 判断是否有不是mysql的数据库类型,方便解析判断是否启用多数据库分页语法解析 for (TableConfig tableConfig : tables.values()) { if (isHasMultiDbType(tableConfig)) { schemaConfig.setNeedSupportMultiDBType(true); break; } } //记录每种dataNode的DB类型 Map<String, String> dataNodeDbTypeMap = new HashMap<>(); for (String dataNodeName : dataNodes.keySet()) { DataNodeConfig dataNodeConfig = dataNodes.get(dataNodeName); String dataHost = dataNodeConfig.getDataHost(); DataHostConfig dataHostConfig = dataHosts.get(dataHost); if (dataHostConfig != null) { String dbType = dataHostConfig.getDbType(); dataNodeDbTypeMap.put(dataNodeName, dbType); } } schemaConfig.setDataNodeDbTypeMap(dataNodeDbTypeMap); schemas.put(name, schemaConfig); } } /** * 处理动态日期表, 支持 YYYYMM、YYYYMMDD 两种格式 * <p> * YYYYMM格式: yyyymm,2015,01,60 * YYYYMMDD格式: yyyymmdd,2015,01,10,50 * * @param tableNameElement * @param tableNameSuffixElement * @return */ private String doTableNameSuffix(String tableNameElement, String tableNameSuffixElement) { String newTableName = tableNameElement; String[] params = tableNameSuffixElement.split(","); String suffixFormat = params[0].toUpperCase(); if (suffixFormat.equals("YYYYMM")) { //读取参数 int yyyy = Integer.parseInt(params[1]); int mm = Integer.parseInt(params[2]); int mmEndIdx = Integer.parseInt(params[3]); //日期处理 SimpleDateFormat yyyyMMSDF = new SimpleDateFormat("yyyyMM"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, yyyy); cal.set(Calendar.MONTH, mm - 1); cal.set(Calendar.DATE, 0); //表名改写 StringBuffer tableNameBuffer = new StringBuffer(); for (int mmIdx = 0; mmIdx <= mmEndIdx; mmIdx++) { tableNameBuffer.append(tableNameElement); tableNameBuffer.append(yyyyMMSDF.format(cal.getTime())); cal.add(Calendar.MONTH, 1); if (mmIdx != mmEndIdx) { tableNameBuffer.append(","); } } newTableName = tableNameBuffer.toString(); } else if (suffixFormat.equals("YYYYMMDD")) { //读取参数 int yyyy = Integer.parseInt(params[1]); int mm = Integer.parseInt(params[2]); int dd = Integer.parseInt(params[3]); int ddEndIdx = Integer.parseInt(params[4]); //日期处理 SimpleDateFormat yyyyMMddSDF = new SimpleDateFormat("yyyyMMdd"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, yyyy); cal.set(Calendar.MONTH, mm - 1); cal.set(Calendar.DATE, dd); //表名改写 StringBuffer tableNameBuffer = new StringBuffer(); for (int ddIdx = 0; ddIdx <= ddEndIdx; ddIdx++) { tableNameBuffer.append(tableNameElement); tableNameBuffer.append(yyyyMMddSDF.format(cal.getTime())); cal.add(Calendar.DATE, 1); if (ddIdx != ddEndIdx) { tableNameBuffer.append(","); } } newTableName = tableNameBuffer.toString(); } return newTableName; } private Map<String, TableConfig> loadTables(Element node) { // Map<String, TableConfig> tables = new HashMap<String, TableConfig>(); // 支持表名中包含引号[`] BEN GONG final String schemaName = node.getAttribute("name"); Map<String, TableConfig> tables = new TableConfigMap(); NodeList nodeList = node.getElementsByTagName("table"); List<Element> list = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { Element tableElement = (Element) nodeList.item(i); String tableNameElement = tableElement.getAttribute("name").toUpperCase(); if("true".equalsIgnoreCase(tableElement.getAttribute("splitTableNames"))){ String[] split = tableNameElement.split(","); for (String name : split) { Element node1 = (Element)tableElement.cloneNode(true); node1.setAttribute("name",name); list.add(node1); } }else { list.add(tableElement); } } loadTable(schemaName, tables, list); return tables; } private void loadTable(String schemaName, Map<String, TableConfig> tables, List<Element> nodeList) { for (int i = 0; i < nodeList.size(); i++) { Element tableElement = (Element) nodeList.get(i); String tableNameElement = tableElement.getAttribute("name").toUpperCase(); //TODO:路由, 增加对动态日期表的支持 String tableNameSuffixElement = tableElement.getAttribute("nameSuffix").toUpperCase(); if (!"".equals(tableNameSuffixElement)) { if (tableNameElement.split(",").length > 1) { throw new ConfigException("nameSuffix " + tableNameSuffixElement + ", require name parameter cannot multiple breaks!"); } //前缀用来标明日期格式 tableNameElement = doTableNameSuffix(tableNameElement, tableNameSuffixElement); } //记录主键,用于之后路由分析,以及启用自增长主键 String[] tableNames = tableNameElement.split(","); String primaryKey = tableElement.hasAttribute("primaryKey") ? tableElement.getAttribute("primaryKey").toUpperCase() : null; //记录是否主键自增,默认不是,(启用全局sequence handler) boolean autoIncrement = false; if (tableElement.hasAttribute("autoIncrement")) { autoIncrement = Boolean.parseBoolean(tableElement.getAttribute("autoIncrement")); } boolean fetchStoreNodeByJdbc = false; if (tableElement.hasAttribute("fetchStoreNodeByJdbc")) { fetchStoreNodeByJdbc = Boolean.parseBoolean(tableElement.getAttribute("fetchStoreNodeByJdbc")); } //记录是否需要加返回结果集限制,默认需要加 boolean needAddLimit = true; if (tableElement.hasAttribute("needAddLimit")) { needAddLimit = Boolean.parseBoolean(tableElement.getAttribute("needAddLimit")); } //记录type,是否为global String tableTypeStr = tableElement.hasAttribute("type") ? tableElement.getAttribute("type") : null; int tableType = TableConfig.TYPE_GLOBAL_DEFAULT; if ("global".equalsIgnoreCase(tableTypeStr)) { tableType = TableConfig.TYPE_GLOBAL_TABLE; } //记录dataNode,就是分布在哪些dataNode上 String dataNode = tableElement.getAttribute("dataNode"); TableRuleConfig tableRule = null; if (tableElement.hasAttribute("rule")) { String ruleName = tableElement.getAttribute("rule"); tableRule = tableRules.get(ruleName); if (tableRule == null) { throw new ConfigException("rule " + ruleName + " is not found!"); } } boolean ruleRequired = false; //记录是否绑定有分片规则 if (tableElement.hasAttribute("ruleRequired")) { ruleRequired = Boolean.parseBoolean(tableElement.getAttribute("ruleRequired")); } if (tableNames == null) { throw new ConfigException("table name is not found!"); } //distribute函数,重新编排dataNode String distPrex = "distribute("; boolean distTableDns = dataNode.startsWith(distPrex); if (distTableDns) { dataNode = dataNode.substring(distPrex.length(), dataNode.length() - 1); } //分表功能 String subTables = tableElement.getAttribute("subTables"); for (int j = 0; j < tableNames.length; j++) { String tableName = tableNames[j]; TableRuleConfig tableRuleConfig = tableRule; if (tableRuleConfig != null) { //对于实现TableRuleAware的function进行特殊处理 根据每个表新建个实例 RuleConfig rule = tableRuleConfig.getRule(); if (rule.getRuleAlgorithm() instanceof TableRuleAware) { //因为ObjectUtil.copyObject是深拷贝,所以会把crc32的算法也拷贝一份状态,而不是公用一个分片数 tableRuleConfig = (TableRuleConfig) ObjectUtil.copyObject(tableRuleConfig); String name = tableRuleConfig.getName(); String newRuleName = getNewRuleName(schemaName, tableName, name); tableRuleConfig.setName(newRuleName); TableRuleAware tableRuleAware = (TableRuleAware) tableRuleConfig.getRule().getRuleAlgorithm(); tableRuleAware.setRuleName(newRuleName); tableRules.put(newRuleName, tableRuleConfig); } } TableConfig table = new TableConfig(tableName, primaryKey, autoIncrement, needAddLimit, tableType, dataNode, getDbType(dataNode), (tableRuleConfig != null) ? tableRuleConfig.getRule() : null, ruleRequired, null, false, null, null, subTables, fetchStoreNodeByJdbc); //因为需要等待TableConfig构造完毕才可以拿到dataNode节点数量,所以Rule构造延后到此处 @cjw if ((tableRuleConfig != null) && (tableRuleConfig.getRule().getRuleAlgorithm() instanceof TableRuleAware)) { AbstractPartitionAlgorithm newRuleAlgorithm = tableRuleConfig.getRule().getRuleAlgorithm(); ((TableRuleAware)newRuleAlgorithm).setTableConfig(table); newRuleAlgorithm.init(); } checkDataNodeExists(table.getDataNodes()); // 检查分片表分片规则配置是否合法 if (table.getRule() != null) { checkRuleSuitTable(table); } if (distTableDns) { distributeDataNodes(table.getDataNodes()); } //检查去重 if (tables.containsKey(table.getName())) { throw new ConfigException("table " + tableName + " duplicated!"); } //放入map tables.put(table.getName(), table); } //只有tableName配置的是单个表(没有逗号)的时候才能有子表 if (tableNames.length == 1) { TableConfig table = tables.get(tableNames[0]); // process child tables processChildTables(tables, table, dataNode, tableElement); } } } private String getNewRuleName(String schemaName, String tableName, String name) { return name + "_" + schemaName + "_" + tableName; } /** * distribute datanodes in multi hosts,means ,dn1 (host1),dn100 * (host2),dn300(host3),dn2(host1),dn101(host2),dn301(host3)...etc * 将每个host上的datanode按照host重新排列。比如上面的例子host1拥有dn1,dn2,host2拥有dn100,dn101,host3拥有dn300,dn301, * 按照host重新排列: 0->dn1 (host1),1->dn100(host2),2->dn300(host3),3->dn2(host1),4->dn101(host2),5->dn301(host3) * * @param theDataNodes */ private void distributeDataNodes(ArrayList<String> theDataNodes) { Map<String, ArrayList<String>> newDataNodeMap = new HashMap<String, ArrayList<String>>(dataHosts.size()); for (String dn : theDataNodes) { DataNodeConfig dnConf = dataNodes.get(dn); String host = dnConf.getDataHost(); ArrayList<String> hostDns = newDataNodeMap.get(host); hostDns = (hostDns == null) ? new ArrayList<String>() : hostDns; hostDns.add(dn); newDataNodeMap.put(host, hostDns); } ArrayList<String> result = new ArrayList<String>(theDataNodes.size()); boolean hasData = true; while (hasData) { hasData = false; for (ArrayList<String> dns : newDataNodeMap.values()) { if (!dns.isEmpty()) { result.add(dns.remove(0)); hasData = true; } } } theDataNodes.clear(); theDataNodes.addAll(result); } private Set<String> getDbType(String dataNode) { Set<String> dbTypes = new HashSet<>(); String[] dataNodeArr = SplitUtil.split(dataNode, ',', '$', '-'); for (String node : dataNodeArr) { DataNodeConfig datanode = dataNodes.get(node); DataHostConfig datahost = dataHosts.get(datanode.getDataHost()); dbTypes.add(datahost.getDbType()); } return dbTypes; } private Set<String> getDataNodeDbTypeMap(String dataNode) { Set<String> dbTypes = new HashSet<>(); String[] dataNodeArr = SplitUtil.split(dataNode, ',', '$', '-'); for (String node : dataNodeArr) { DataNodeConfig datanode = dataNodes.get(node); DataHostConfig datahost = dataHosts.get(datanode.getDataHost()); dbTypes.add(datahost.getDbType()); } return dbTypes; } private boolean isHasMultiDbType(TableConfig table) { Set<String> dbTypes = table.getDbTypes(); for (String dbType : dbTypes) { if (!"mysql".equalsIgnoreCase(dbType)) { return true; } } return false; } private void processChildTables(Map<String, TableConfig> tables, TableConfig parentTable, String dataNodes, Element tableNode) { // parse child tables NodeList childNodeList = tableNode.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node theNode = childNodeList.item(j); if (!theNode.getNodeName().equals("childTable")) { continue; } Element childTbElement = (Element) theNode; //读取子表信息 String cdTbName = childTbElement.getAttribute("name").toUpperCase(); String primaryKey = childTbElement.hasAttribute("primaryKey") ? childTbElement.getAttribute("primaryKey").toUpperCase() : null; boolean autoIncrement = false; if (childTbElement.hasAttribute("autoIncrement")) { autoIncrement = Boolean.parseBoolean(childTbElement.getAttribute("autoIncrement")); } boolean needAddLimit = true; if (childTbElement.hasAttribute("needAddLimit")) { needAddLimit = Boolean.parseBoolean(childTbElement.getAttribute("needAddLimit")); } String subTables = childTbElement.getAttribute("subTables"); //子表join键,和对应的parent的键,父子表通过这个关联 String joinKey = childTbElement.getAttribute("joinKey").toUpperCase(); String parentKey = childTbElement.getAttribute("parentKey").toUpperCase(); TableConfig table = new TableConfig(cdTbName, primaryKey, autoIncrement, needAddLimit, TableConfig.TYPE_GLOBAL_DEFAULT, dataNodes, getDbType(dataNodes), null, false, parentTable, true, joinKey, parentKey, subTables, false); if (tables.containsKey(table.getName())) { throw new ConfigException("table " + table.getName() + " duplicated!"); } tables.put(table.getName(), table); //对于子表的子表,递归处理 processChildTables(tables, table, dataNodes, childTbElement); } } private void checkDataNodeExists(Collection<String> nodes) { if (nodes == null || nodes.size() < 1) { return; } for (String node : nodes) { if (!dataNodes.containsKey(node)) { throw new ConfigException("dataNode '" + node + "' is not found!"); } } } /** * 检查分片表分片规则配置, 目前主要检查分片表分片算法定义与分片dataNode是否匹配<br> * 例如分片表定义如下:<br> * {@code * <table name="hotnews" primaryKey="ID" autoIncrement="true" dataNode="dn1,dn2" * rule="mod-long" /> * } * <br> * 分片算法如下:<br> * {@code * <function name="mod-long" class="io.mycat.route.function.PartitionByMod"> * <!-- how many data nodes --> * <property name="count">3</property> * </function> * } * <br> * shard table datanode(2) < function count(3) 此时检测为不匹配 */ private void checkRuleSuitTable(TableConfig tableConf) { AbstractPartitionAlgorithm function = tableConf.getRule().getRuleAlgorithm(); int suitValue = function.suitableFor(tableConf); switch (suitValue) { case -1: // 少节点,给提示并抛异常 throw new ConfigException("Illegal table conf : table [ " + tableConf.getName() + " ] rule function [ " + tableConf.getRule().getFunctionName() + " ] partition size : " + tableConf.getRule().getRuleAlgorithm().getPartitionNum() + " > table datanode size : " + tableConf.getDataNodes().size() + ", please make sure table datanode size = function partition size"); case 0: // table datanode size == rule function partition size break; case 1: // 有些节点是多余的,给出warn log LOGGER.warn("table conf : table [ {} ] rule function [ {} ] partition size : {} < table datanode size : {} , this cause some datanode to be redundant", new String[]{ tableConf.getName(), tableConf.getRule().getFunctionName(), String.valueOf(tableConf.getRule().getRuleAlgorithm().getPartitionNum()), String.valueOf(tableConf.getDataNodes().size()) }); break; } } private void loadDataNodes(Element root) { //读取DataNode分支 NodeList list = root.getElementsByTagName("dataNode"); for (int i = 0, n = list.getLength(); i < n; i++) { Element element = (Element) list.item(i); String dnNamePre = element.getAttribute("name"); String databaseStr = element.getAttribute("database"); String host = element.getAttribute("dataHost"); //字符串不为空 if (empty(dnNamePre) || empty(databaseStr) || empty(host)) { throw new ConfigException("dataNode " + dnNamePre + " define error ,attribute can't be empty"); } //dnNames(name),databases(database),hostStrings(dataHost)都可以配置多个,以',', '$', '-'区分,但是需要保证database的个数*dataHost的个数=name的个数 //多个dataHost与多个database如果写在一个标签,则每个dataHost拥有所有database //例如:<dataNode name="dn1$0-75" dataHost="localhost$1-10" database="db$0-759" /> //则为:localhost1拥有dn1$0-75,localhost2也拥有dn1$0-75(对应db$76-151) String[] dnNames = io.mycat.util.SplitUtil.split(dnNamePre, ',', '$', '-'); String[] databases = io.mycat.util.SplitUtil.split(databaseStr, ',', '$', '-'); String[] hostStrings = io.mycat.util.SplitUtil.split(host, ',', '$', '-'); if (dnNames.length > 1 && dnNames.length != databases.length * hostStrings.length) { throw new ConfigException("dataNode " + dnNamePre + " define error ,dnNames.length must be=databases.length*hostStrings.length"); } if (dnNames.length > 1) { List<String[]> mhdList = mergerHostDatabase(hostStrings, databases); for (int k = 0; k < dnNames.length; k++) { String[] hd = mhdList.get(k); String dnName = dnNames[k]; String databaseName = hd[1]; String hostName = hd[0]; createDataNode(dnName, databaseName, hostName); } } else { createDataNode(dnNamePre, databaseStr, host); } } } /** * 匹配DataHost和Database,每个DataHost拥有每个Database名字 * * @param hostStrings * @param databases * @return */ private List<String[]> mergerHostDatabase(String[] hostStrings, String[] databases) { List<String[]> mhdList = new ArrayList<>(); for (int i = 0; i < hostStrings.length; i++) { String hostString = hostStrings[i]; for (int i1 = 0; i1 < databases.length; i1++) { String database = databases[i1]; String[] hd = new String[2]; hd[0] = hostString; hd[1] = database; mhdList.add(hd); } } return mhdList; } private void createDataNode(String dnName, String database, String host) { DataNodeConfig conf = new DataNodeConfig(dnName, database, host); if (dataNodes.containsKey(conf.getName())) { throw new ConfigException("dataNode " + conf.getName() + " duplicated!"); } if (!dataHosts.containsKey(host)) { throw new ConfigException("dataNode " + dnName + " reference dataHost:" + host + " not exists!"); } dataHosts.get(host).addDataNode(conf.getName()); dataNodes.put(conf.getName(), conf); } private boolean empty(String dnName) { return dnName == null || dnName.length() == 0; } private DBHostConfig createDBHostConf(String dataHost, Element node, String dbType, String dbDriver, int maxCon, int minCon, String filters, long logTime) { String nodeHost = node.getAttribute("host"); String nodeUrl = node.getAttribute("url"); String user = node.getAttribute("user"); String password = node.getAttribute("password"); String usingDecrypt = node.getAttribute("usingDecrypt"); String checkAliveText = node.getAttribute("checkAlive"); if (checkAliveText == null)checkAliveText = Boolean.TRUE.toString(); boolean checkAlive = Boolean.parseBoolean(checkAliveText); String passwordEncryty = DecryptUtil.DBHostDecrypt(usingDecrypt, nodeHost, user, password); String weightStr = node.getAttribute("weight"); int weight = "".equals(weightStr) ? PhysicalDBPool.WEIGHT : Integer.parseInt(weightStr); String ip = null; int port = 0; if (empty(nodeHost) || empty(nodeUrl) || empty(user)) { throw new ConfigException( "dataHost " + dataHost + " define error,some attributes of this element is empty: " + nodeHost); } if ("native".equalsIgnoreCase(dbDriver)) { int colonIndex = nodeUrl.indexOf(':'); ip = nodeUrl.substring(0, colonIndex).trim(); port = Integer.parseInt(nodeUrl.substring(colonIndex + 1).trim()); } else { URI url; try { url = new URI(nodeUrl.substring(5)); } catch (Exception e) { throw new ConfigException("invalid jdbc url " + nodeUrl + " of " + dataHost); } ip = url.getHost(); port = url.getPort(); } DBHostConfig conf = new DBHostConfig(nodeHost, ip, port, nodeUrl, user, passwordEncryty, password,checkAlive); conf.setDbType(dbType); conf.setMaxCon(maxCon); conf.setMinCon(minCon); conf.setFilters(filters); conf.setLogTime(logTime); conf.setWeight(weight); //新增权重 return conf; } private void loadDataHosts(Element root) { NodeList list = root.getElementsByTagName("dataHost"); for (int i = 0, n = list.getLength(); i < n; ++i) { Element element = (Element) list.item(i); String name = element.getAttribute("name"); //判断是否重复 if (dataHosts.containsKey(name)) { throw new ConfigException("dataHost name " + name + "duplicated!"); } //读取最大连接数 int maxCon = Integer.parseInt(element.getAttribute("maxCon")); //读取最小连接数 int minCon = Integer.parseInt(element.getAttribute("minCon")); /** * 读取负载均衡配置 * 1. balance="0", 不开启分离机制,所有读操作都发送到当前可用的 writeHost 上。 * 2. balance="1",全部的 readHost 和 stand by writeHost 参不 select 的负载均衡 * 3. balance="2",所有读操作都随机的在 writeHost、readhost 上分发。 * 4. balance="3",所有读请求随机的分发到 wiriterHost 对应的 readhost 执行,writerHost 不负担读压力 */ int balance = Integer.parseInt(element.getAttribute("balance")); /** * 负载均衡配置 * 1. balanceType=0, 随机 * 2. balanceType=1,加权轮询 * 3. balanceType=2,最少活跃 */ String balanceTypeStr = element.getAttribute("balanceType"); int balanceType = balanceTypeStr.equals("") ? 0 : Integer.parseInt(balanceTypeStr); /** * 读取切换类型 * -1 表示不自动切换 * 1 默认值,自动切换 * 2 基于MySQL主从同步的状态决定是否切换 * 心跳询句为 show slave status * 3 基于 MySQL galary cluster 的切换机制 */ String switchTypeStr = element.getAttribute("switchType"); int switchType = switchTypeStr.equals("") ? -1 : Integer.parseInt(switchTypeStr); //读取从延迟界限 String slaveThresholdStr = element.getAttribute("slaveThreshold"); int slaveThreshold = slaveThresholdStr.equals("") ? -1 : Integer.parseInt(slaveThresholdStr); //如果 tempReadHostAvailable 设置大于 0 则表示写主机如果挂掉, 临时的读服务依然可用 String tempReadHostAvailableStr = element.getAttribute("tempReadHostAvailable"); boolean tempReadHostAvailable = !tempReadHostAvailableStr.equals("") && Integer.parseInt(tempReadHostAvailableStr) > 0; /** * 读取 写类型 * 这里只支持 0 - 所有写操作仅配置的第一个 writeHost */ String writeTypStr = element.getAttribute("writeType"); int writeType = "".equals(writeTypStr) ? PhysicalDBPool.WRITE_ONLYONE_NODE : Integer.parseInt(writeTypStr); String dbDriver = element.getAttribute("dbDriver"); String dbType = element.getAttribute("dbType"); String filters = element.getAttribute("filters"); String logTimeStr = element.getAttribute("logTime"); String slaveIDs = element.getAttribute("slaveIDs"); String maxRetryCountStr = element.getAttribute("maxRetryCount"); int maxRetryCount; if (StringUtil.isEmpty(maxRetryCountStr)) { maxRetryCount = 3; } else { maxRetryCount = Integer.valueOf(maxRetryCountStr); } long logTime = "".equals(logTimeStr) ? PhysicalDBPool.LONG_TIME : Long.parseLong(logTimeStr); String notSwitch = element.getAttribute("notSwitch"); if(StringUtil.isEmpty(notSwitch)) { notSwitch = DataHostConfig.CAN_SWITCH_DS; } //读取心跳语句 String heartbeatSQL = element.getElementsByTagName("heartbeat").item(0).getTextContent(); //读取 初始化sql配置,用于oracle NodeList connectionInitSqlList = element.getElementsByTagName("connectionInitSql"); String initConSQL = null; if (connectionInitSqlList.getLength() > 0) { initConSQL = connectionInitSqlList.item(0).getTextContent(); } //读取writeHost NodeList writeNodes = element.getElementsByTagName("writeHost"); DBHostConfig[] writeDbConfs = new DBHostConfig[writeNodes.getLength()]; Map<Integer, DBHostConfig[]> readHostsMap = new HashMap<Integer, DBHostConfig[]>(2); Set<String> writeHostNameSet = new HashSet<String>(writeNodes.getLength()); for (int w = 0; w < writeDbConfs.length; w++) { Element writeNode = (Element) writeNodes.item(w); writeDbConfs[w] = createDBHostConf(name, writeNode, dbType, dbDriver, maxCon, minCon, filters, logTime); if (writeHostNameSet.contains(writeDbConfs[w].getHostName())) { throw new ConfigException("writeHost " + writeDbConfs[w].getHostName() + " duplicated!"); } else { writeHostNameSet.add(writeDbConfs[w].getHostName()); } NodeList readNodes = writeNode.getElementsByTagName("readHost"); //读取对应的每一个readHost if (readNodes.getLength() != 0) { DBHostConfig[] readDbConfs = new DBHostConfig[readNodes.getLength()]; Set<String> readHostNameSet = new HashSet<String>(readNodes.getLength()); for (int r = 0; r < readDbConfs.length; r++) { Element readNode = (Element) readNodes.item(r); readDbConfs[r] = createDBHostConf(name, readNode, dbType, dbDriver, maxCon, minCon, filters, logTime); if (readHostNameSet.contains(readDbConfs[r].getHostName())) { throw new ConfigException("readHost " + readDbConfs[r].getHostName() + " duplicated!"); } else { readHostNameSet.add(readDbConfs[r].getHostName()); } } readHostsMap.put(w, readDbConfs); } } DataHostConfig hostConf = new DataHostConfig(name, dbType, dbDriver, writeDbConfs, readHostsMap, switchType, slaveThreshold, tempReadHostAvailable); hostConf.setMaxCon(maxCon); hostConf.setMinCon(minCon); hostConf.setBalance(balance); hostConf.setBalanceType(balanceType); hostConf.setWriteType(writeType); hostConf.setHearbeatSQL(heartbeatSQL); hostConf.setConnectionInitSql(initConSQL); hostConf.setFilters(filters); hostConf.setLogTime(logTime); hostConf.setSlaveIDs(slaveIDs); hostConf.setNotSwitch(notSwitch); hostConf.setMaxRetryCount(maxRetryCount); dataHosts.put(hostConf.getName(), hostConf); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/config/loader/xml/XMLSchemaLoader.java
1,302
package com.xkcoding.upload.config; import com.qiniu.common.Zone; import com.qiniu.storage.BucketManager; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.MultipartConfigElement; import javax.servlet.Servlet; /** * <p> * 上传配置 * </p> * * @author yangkai.shen * @date Created in 2018-10-23 14:09 */ @Configuration @ConditionalOnClass({Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class}) @ConditionalOnProperty(prefix = "spring.http.multipart", name = "enabled", matchIfMissing = true) @EnableConfigurationProperties(MultipartProperties.class) public class UploadConfig { @Value("${qiniu.accessKey}") private String accessKey; @Value("${qiniu.secretKey}") private String secretKey; private final MultipartProperties multipartProperties; @Autowired public UploadConfig(MultipartProperties multipartProperties) { this.multipartProperties = multipartProperties; } /** * 上传配置 */ @Bean @ConditionalOnMissingBean public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } /** * 注册解析器 */ @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) @ConditionalOnMissingBean(MultipartResolver.class) public StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily()); return multipartResolver; } /** * 华东机房 */ @Bean public com.qiniu.storage.Configuration qiniuConfig() { return new com.qiniu.storage.Configuration(Zone.zone0()); } /** * 构建一个七牛上传工具实例 */ @Bean public UploadManager uploadManager() { return new UploadManager(qiniuConfig()); } /** * 认证信息实例 */ @Bean public Auth auth() { return Auth.create(accessKey, secretKey); } /** * 构建七牛空间管理实例 */ @Bean public BucketManager bucketManager() { return new BucketManager(auth(), qiniuConfig()); } }
xkcoding/spring-boot-demo
demo-upload/src/main/java/com/xkcoding/upload/config/UploadConfig.java
1,304
package org.jeecg.common.util; import io.minio.*; import io.minio.http.Method; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.util.filter.SsrfFileTypeFilter; import org.jeecg.common.util.filter.StrAttackFilter; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.net.URLDecoder; /** * minio文件上传工具类 * @author: jeecg-boot */ @Slf4j public class MinioUtil { private static String minioUrl; private static String minioName; private static String minioPass; private static String bucketName; public static void setMinioUrl(String minioUrl) { MinioUtil.minioUrl = minioUrl; } public static void setMinioName(String minioName) { MinioUtil.minioName = minioName; } public static void setMinioPass(String minioPass) { MinioUtil.minioPass = minioPass; } public static void setBucketName(String bucketName) { MinioUtil.bucketName = bucketName; } public static String getMinioUrl() { return minioUrl; } public static String getBucketName() { return bucketName; } private static MinioClient minioClient = null; /** * 上传文件 * @param file * @return */ public static String upload(MultipartFile file, String bizPath, String customBucket) throws Exception { String fileUrl = ""; //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击 bizPath = StrAttackFilter.filter(bizPath); //update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击 //update-begin-author:liusq date:20210809 for: 过滤上传文件类型 SsrfFileTypeFilter.checkUploadFileType(file); //update-end-author:liusq date:20210809 for: 过滤上传文件类型 String newBucket = bucketName; if(oConvertUtils.isNotEmpty(customBucket)){ newBucket = customBucket; } try { initMinio(minioUrl, minioName,minioPass); // 检查存储桶是否已经存在 if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) { log.info("Bucket already exists."); } else { // 创建一个名为ota的存储桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build()); log.info("create a new bucket."); } InputStream stream = file.getInputStream(); // 获取文件名 String orgName = file.getOriginalFilename(); if("".equals(orgName)){ orgName=file.getName(); } orgName = CommonUtils.getFileName(orgName); String objectName = bizPath+"/" +( orgName.indexOf(".")==-1 ?orgName + "_" + System.currentTimeMillis() :orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf(".")) ); // 使用putObject上传一个本地文件到存储桶中。 if(objectName.startsWith(SymbolConstant.SINGLE_SLASH)){ objectName = objectName.substring(1); } PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName) .bucket(newBucket) .contentType("application/octet-stream") .stream(stream,stream.available(),-1).build(); minioClient.putObject(objectArgs); stream.close(); fileUrl = minioUrl+newBucket+"/"+objectName; }catch (Exception e){ log.error(e.getMessage(), e); } return fileUrl; } /** * 文件上传 * @param file * @param bizPath * @return */ public static String upload(MultipartFile file, String bizPath) throws Exception { return upload(file,bizPath,null); } /** * 获取文件流 * @param bucketName * @param objectName * @return */ public static InputStream getMinioFile(String bucketName,String objectName){ InputStream inputStream = null; try { initMinio(minioUrl, minioName, minioPass); GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName) .bucket(bucketName).build(); inputStream = minioClient.getObject(objectArgs); } catch (Exception e) { log.info("文件获取失败" + e.getMessage()); } return inputStream; } /** * 删除文件 * @param bucketName * @param objectName * @throws Exception */ public static void removeObject(String bucketName, String objectName) { try { initMinio(minioUrl, minioName,minioPass); RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName) .bucket(bucketName).build(); minioClient.removeObject(objectArgs); }catch (Exception e){ log.info("文件删除失败" + e.getMessage()); } } /** * 获取文件外链 * @param bucketName * @param objectName * @param expires * @return */ public static String getObjectUrl(String bucketName, String objectName, Integer expires) { initMinio(minioUrl, minioName,minioPass); try{ //update-begin---author:liusq Date:20220121 for:获取文件外链报错提示method不能为空,导致文件下载和预览失败---- GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName) .bucket(bucketName) .expiry(expires).method(Method.GET).build(); //update-begin---author:liusq Date:20220121 for:获取文件外链报错提示method不能为空,导致文件下载和预览失败---- String url = minioClient.getPresignedObjectUrl(objectArgs); return URLDecoder.decode(url,"UTF-8"); }catch (Exception e){ log.info("文件路径获取失败" + e.getMessage()); } return null; } /** * 初始化客户端 * @param minioUrl * @param minioName * @param minioPass * @return */ private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) { if (minioClient == null) { try { minioClient = MinioClient.builder() .endpoint(minioUrl) .credentials(minioName, minioPass) .build(); } catch (Exception e) { e.printStackTrace(); } } return minioClient; } /** * 上传文件到minio * @param stream * @param relativePath * @return */ public static String upload(InputStream stream,String relativePath) throws Exception { initMinio(minioUrl, minioName,minioPass); if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) { log.info("Bucket already exists."); } else { // 创建一个名为ota的存储桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); log.info("create a new bucket."); } PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath) .bucket(bucketName) .contentType("application/octet-stream") .stream(stream,stream.available(),-1).build(); minioClient.putObject(objectArgs); stream.close(); return minioUrl+bucketName+"/"+relativePath; } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MinioUtil.java
1,307
package me.zhyd.oauth.enums.scope; import lombok.AllArgsConstructor; import lombok.Getter; /** * QQ 平台 OAuth 授权范围 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @version 1.0.0 * @since 1.0.0 */ @Getter @AllArgsConstructor public enum AuthQqScope implements AuthScope { /** * {@code scope} 含义,以{@code description} 为准 */ GET_USER_INFO("get_user_info", "获取登录用户的昵称、头像、性别", true), /** * 以下 scope 需要申请:http://wiki.connect.qq.com/openapi%e6%9d%83%e9%99%90%e7%94%b3%e8%af%b7 */ GET_VIP_INFO("get_vip_info", "获取QQ会员的基本信息", false), GET_VIP_RICH_INFO("get_vip_rich_info", "获取QQ会员的高级信息", false), LIST_ALBUM("list_album", "获取用户QQ空间相册列表", false), UPLOAD_PIC("upload_pic", "上传一张照片到QQ空间相册", false), ADD_ALBUM("add_album", "在用户的空间相册里,创建一个新的个人相册", false), LIST_PHOTO("list_photo", "获取用户QQ空间相册中的照片列表", false); private final String scope; private final String description; private final boolean isDefault; }
justauth/JustAuth
src/main/java/me/zhyd/oauth/enums/scope/AuthQqScope.java
1,311
/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.service; import me.zhengjie.domain.QiniuConfig; import me.zhengjie.domain.QiniuContent; import me.zhengjie.service.dto.QiniuQueryCriteria; import me.zhengjie.utils.PageResult; import org.springframework.data.domain.Pageable; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @author Zheng Jie * @date 2018-12-31 */ public interface QiNiuService { /** * 查配置 * @return QiniuConfig */ QiniuConfig find(); /** * 修改配置 * @param qiniuConfig 配置 * @return QiniuConfig */ QiniuConfig config(QiniuConfig qiniuConfig); /** * 分页查询 * @param criteria 条件 * @param pageable 分页参数 * @return / */ PageResult<QiniuContent> queryAll(QiniuQueryCriteria criteria, Pageable pageable); /** * 查询全部 * @param criteria 条件 * @return / */ List<QiniuContent> queryAll(QiniuQueryCriteria criteria); /** * 上传文件 * @param file 文件 * @param qiniuConfig 配置 * @return QiniuContent */ QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig); /** * 查询文件 * @param id 文件ID * @return QiniuContent */ QiniuContent findByContentId(Long id); /** * 下载文件 * @param content 文件信息 * @param config 配置 * @return String */ String download(QiniuContent content, QiniuConfig config); /** * 删除文件 * @param content 文件 * @param config 配置 */ void delete(QiniuContent content, QiniuConfig config); /** * 同步数据 * @param config 配置 */ void synchronize(QiniuConfig config); /** * 删除文件 * @param ids 文件ID数组 * @param config 配置 */ void deleteAll(Long[] ids, QiniuConfig config); /** * 更新数据 * @param type 类型 */ void update(String type); /** * 导出数据 * @param queryAll / * @param response / * @throws IOException / */ void downloadList(List<QiniuContent> queryAll, HttpServletResponse response) throws IOException; }
elunez/eladmin
eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java
1,315
package com.tamsiree.rxui.view; import android.animation.Animator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Handler; import android.text.TextPaint; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tamsiree.rxkit.RxImageTool; import com.tamsiree.rxkit.TLog; import com.tamsiree.rxui.R; import java.util.ArrayList; import java.util.Collections; /** * @author Tamsiree * @date 16/6/16 */ public class RxSeatMovie extends View { private final boolean deBug = false; Paint paint = new Paint(); Paint overviewPaint = new Paint(); Paint lineNumberPaint; float lineNumberTxtHeight; /** * 设置行号 默认显示 1,2,3....数字 * * @param lineNumbers 行号 */ public void setLineNumbers(ArrayList<String> lineNumbers) { this.lineNumbers = lineNumbers; invalidate(); } /** * 用来保存所有行号 */ ArrayList<String> lineNumbers = new ArrayList<>(); Paint.FontMetrics lineNumberPaintFontMetrics; Matrix matrix = new Matrix(); /** * 座位水平间距 */ int spacing; /** * 座位垂直间距 */ int verSpacing; /** * 行号宽度 */ int numberWidth; /** * 行数 */ int row; /** * 列数 */ int column; /** * 可选时座位的图片 */ Bitmap seatBitmap; /** * 选中时座位的图片 */ Bitmap checkedSeatBitmap; /** * 座位已经售出时的图片 */ Bitmap seatSoldBitmap; Bitmap overviewBitmap; int lastX; int lastY; /** * 整个座位图的宽度 */ int seatBitmapWidth; /** * 整个座位图的高度 */ int seatBitmapHeight; /** * 标识是否需要绘制座位图 */ boolean isNeedDrawSeatBitmap = true; /** * 概览图白色方块高度 */ float rectHeight; /** * 概览图白色方块的宽度 */ float rectWidth; /** * 概览图上方块的水平间距 */ float overviewSpacing; /** * 概览图上方块的垂直间距 */ float overviewVerSpacing; /** * 概览图的比例 */ float overviewScale = 4.8f; /** * 荧幕高度 */ float screenHeight; /** * 荧幕默认宽度与座位图的比例 */ float screenWidthScale = 0.5f; /** * 荧幕最小宽度 */ int defaultScreenWidth; /** * 标识是否正在缩放 */ boolean isScaling; float scaleX, scaleY; /** * 是否是第一次缩放 */ boolean firstScale = true; /** * 最多可以选择的座位数量 */ int maxSelected = Integer.MAX_VALUE; private SeatChecker seatChecker; /** * 荧幕名称 */ private String screenName = ""; /** * 整个概览图的宽度 */ float rectW; /** * 整个概览图的高度 */ float rectH; Paint headPaint; Bitmap headBitmap; /** * 是否第一次执行onDraw */ boolean isFirstDraw = true; /** * 标识是否需要绘制概览图 */ boolean isDrawOverview = false; /** * 标识是否需要更新概览图 */ boolean isDrawOverviewBitmap = true; int overviewChecked; int overviewSold; int txtColor; int seatCheckedResID; int seatSoldResID; int seatAvailableResID; boolean isOnClick; /** * 座位已售 */ private static final int SEAT_TYPE_SOLD = 1; /** * 座位已经选中 */ private static final int SEAT_TYPE_SELECTED = 2; /** * 座位可选 */ private static final int SEAT_TYPE_AVAILABLE = 3; /** * 座位不可用 */ private static final int SEAT_TYPE_NOT_AVAILABLE = 4; private int downX, downY; private boolean pointer; /** * 顶部高度,可选,已选,已售区域的高度 */ float headHeight; Paint pathPaint; RectF rectF; /** * 头部下面横线的高度 */ int borderHeight = 1; Paint redBorderPaint; /** * 默认的座位图宽度,如果使用的自己的座位图片比这个尺寸大或者小,会缩放到这个大小 */ private float defaultImgW = 40f; /** * 默认的座位图高度 */ private float defaultImgH = 34f; /** * 座位图片的宽度 */ private int seatWidth; /** * 座位图片的高度 */ private int seatHeight; public RxSeatMovie(Context context) { super(context); init(context, null); } public RxSeatMovie(Context context, AttributeSet attrs) { super(context, attrs); //导入布局 init(context, attrs); } public RxSeatMovie(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } @TargetApi(21) public RxSeatMovie(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RxSeatMovie); overviewChecked = typedArray.getColor(R.styleable.RxSeatMovie_overview_checked, Color.parseColor("#5A9E64")); overviewSold = typedArray.getColor(R.styleable.RxSeatMovie_overview_sold, Color.RED); txtColor = typedArray.getColor(R.styleable.RxSeatMovie_txt_color, Color.WHITE); seatCheckedResID = typedArray.getResourceId(R.styleable.RxSeatMovie_seat_checked, R.drawable.seat_green); seatSoldResID = typedArray.getResourceId(R.styleable.RxSeatMovie_overview_sold, R.drawable.seat_sold); seatAvailableResID = typedArray.getResourceId(R.styleable.RxSeatMovie_seat_available, R.drawable.seat_gray); typedArray.recycle(); //设置屏幕名称 setScreenName("3号厅荧幕"); //设置最多选中 setMaxSelected(8); setSeatChecker(new RxSeatMovie.SeatChecker() { @Override public boolean isValidSeat(int row, int column) { return !(column == 2 || column == 12); } @Override public boolean isSold(int row, int column) { return row == 6 && column == 6; } @Override public void checked(int row, int column) { } @Override public void unCheck(int row, int column) { } @Override public String[] checkedSeatTxt(int row, int column) { return null; } }); setData(10, 15); } float xScale1 = 1; float yScale1 = 1; private void init() { spacing = RxImageTool.dp2px(getContext(), 5); verSpacing = RxImageTool.dp2px(getContext(), 10); defaultScreenWidth = RxImageTool.dp2px(getContext(), 80); seatBitmap = BitmapFactory.decodeResource(getResources(), seatAvailableResID); float scaleX = defaultImgW / seatBitmap.getWidth(); float scaleY = defaultImgH / seatBitmap.getHeight(); xScale1 = scaleX; yScale1 = scaleY; seatHeight = (int) (seatBitmap.getHeight() * yScale1); seatWidth = (int) (seatBitmap.getWidth() * xScale1); checkedSeatBitmap = BitmapFactory.decodeResource(getResources(), seatCheckedResID); seatSoldBitmap = BitmapFactory.decodeResource(getResources(), seatSoldResID); seatBitmapWidth = (int) (column * seatBitmap.getWidth() * xScale1 + (column - 1) * spacing); seatBitmapHeight = (int) (row * seatBitmap.getHeight() * yScale1 + (row - 1) * verSpacing); paint.setColor(Color.RED); numberWidth = RxImageTool.dp2px(getContext(), 20); screenHeight = RxImageTool.dp2px(getContext(), 20); headHeight = RxImageTool.dp2px(getContext(), 30); headPaint = new Paint(); headPaint.setStyle(Paint.Style.FILL); headPaint.setTextSize(24); headPaint.setColor(Color.WHITE); headPaint.setAntiAlias(true); pathPaint = new Paint(Paint.ANTI_ALIAS_FLAG); pathPaint.setStyle(Paint.Style.FILL); pathPaint.setColor(Color.parseColor("#e2e2e2")); redBorderPaint = new Paint(); redBorderPaint.setAntiAlias(true); redBorderPaint.setColor(Color.RED); redBorderPaint.setStyle(Paint.Style.STROKE); redBorderPaint.setStrokeWidth(getResources().getDisplayMetrics().density * 1); rectF = new RectF(); rectHeight = seatHeight / overviewScale; rectWidth = seatWidth / overviewScale; overviewSpacing = spacing / overviewScale; overviewVerSpacing = verSpacing / overviewScale; rectW = column * rectWidth + (column - 1) * overviewSpacing + overviewSpacing * 2; rectH = row * rectHeight + (row - 1) * overviewVerSpacing + overviewVerSpacing * 2; overviewBitmap = Bitmap.createBitmap((int) rectW, (int) rectH, Bitmap.Config.ARGB_4444); lineNumberPaint = new Paint(Paint.ANTI_ALIAS_FLAG); lineNumberPaint.setColor(bacColor); lineNumberPaint.setTextSize(getResources().getDisplayMetrics().density * 16); lineNumberTxtHeight = lineNumberPaint.measureText("4"); lineNumberPaintFontMetrics = lineNumberPaint.getFontMetrics(); lineNumberPaint.setTextAlign(Paint.Align.CENTER); if (lineNumbers == null) { lineNumbers = new ArrayList<>(); } else if (lineNumbers.size() <= 0) { for (int i = 0; i < row; i++) { lineNumbers.add((i + 1) + ""); } } matrix.postTranslate(numberWidth + spacing, headHeight + screenHeight + borderHeight + verSpacing); } @Override protected void onDraw(Canvas canvas) { long startTime = System.currentTimeMillis(); if (row <= 0 || column == 0) { return; } drawSeat(canvas); drawNumber(canvas); if (headBitmap == null) { headBitmap = drawHeadInfo(); } canvas.drawBitmap(headBitmap, 0, 0, null); drawScreen(canvas); if (isDrawOverview) { long s = System.currentTimeMillis(); if (isDrawOverviewBitmap) { drawOverview(); } canvas.drawBitmap(overviewBitmap, 0, 0, null); drawOverview(canvas); TLog.d("drawTime", "OverviewDrawTime:" + (System.currentTimeMillis() - s)); } if (deBug) { long drawTime = System.currentTimeMillis() - startTime; TLog.d("drawTime", "totalDrawTime:" + drawTime); } } @Override public boolean onTouchEvent(MotionEvent event) { int y = (int) event.getY(); int x = (int) event.getX(); super.onTouchEvent(event); scaleGestureDetector.onTouchEvent(event); gestureDetector.onTouchEvent(event); int pointerCount = event.getPointerCount(); if (pointerCount > 1) { pointer = true; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: pointer = false; downX = x; downY = y; isDrawOverview = true; handler.removeCallbacks(hideOverviewRunnable); invalidate(); break; case MotionEvent.ACTION_MOVE: if (!isScaling && !isOnClick) { int downDX = Math.abs(x - downX); int downDY = Math.abs(y - downY); if ((downDX > 10 || downDY > 10) && !pointer) { int dx = x - lastX; int dy = y - lastY; matrix.postTranslate(dx, dy); invalidate(); } } break; case MotionEvent.ACTION_UP: handler.postDelayed(hideOverviewRunnable, 1500); autoScale(); int downDX = Math.abs(x - downX); int downDY = Math.abs(y - downY); if ((downDX > 10 || downDY > 10) && !pointer) { autoScroll(); } break; default: break; } isOnClick = false; lastY = y; lastX = x; return true; } private Runnable hideOverviewRunnable = new Runnable() { @Override public void run() { isDrawOverview = false; invalidate(); } }; Bitmap drawHeadInfo() { String txt = "已售"; float txtY = getBaseLine(headPaint, 0, headHeight); int txtWidth = (int) headPaint.measureText(txt); float spacing = RxImageTool.dp2px(getContext(), 10); float spacing1 = RxImageTool.dp2px(getContext(), 5); float y = (headHeight - seatBitmap.getHeight()) / 2; float width = seatBitmap.getWidth() + spacing1 + txtWidth + spacing + seatSoldBitmap.getWidth() + txtWidth + spacing1 + spacing + checkedSeatBitmap.getHeight() + spacing1 + txtWidth; Bitmap bitmap = Bitmap.createBitmap(getWidth(), (int) headHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); //绘制背景 canvas.drawRect(0, 0, getWidth(), headHeight, headPaint); headPaint.setColor(Color.BLACK); float startX = (getWidth() - width) / 2; tempMatrix.setScale(xScale1, yScale1); tempMatrix.postTranslate(startX, (headHeight - seatHeight) / 2); canvas.drawBitmap(seatBitmap, tempMatrix, headPaint); canvas.drawText("可选", startX + seatWidth + spacing1, txtY, headPaint); float soldSeatBitmapY = startX + seatBitmap.getWidth() + spacing1 + txtWidth + spacing; tempMatrix.setScale(xScale1, yScale1); tempMatrix.postTranslate(soldSeatBitmapY, (headHeight - seatHeight) / 2); canvas.drawBitmap(seatSoldBitmap, tempMatrix, headPaint); canvas.drawText("已售", soldSeatBitmapY + seatWidth + spacing1, txtY, headPaint); float checkedSeatBitmapX = soldSeatBitmapY + seatSoldBitmap.getWidth() + spacing1 + txtWidth + spacing; tempMatrix.setScale(xScale1, yScale1); tempMatrix.postTranslate(checkedSeatBitmapX, y); canvas.drawBitmap(checkedSeatBitmap, tempMatrix, headPaint); canvas.drawText("已选", checkedSeatBitmapX + spacing1 + seatWidth, txtY, headPaint); //绘制分割线 headPaint.setStrokeWidth(1); headPaint.setColor(Color.GRAY); canvas.drawLine(0, headHeight, getWidth(), headHeight, headPaint); return bitmap; } /** * 绘制中间屏幕 */ void drawScreen(Canvas canvas) { pathPaint.setStyle(Paint.Style.FILL); pathPaint.setColor(Color.parseColor("#e2e2e2")); float startY = headHeight + borderHeight; float centerX = seatBitmapWidth * getMatrixScaleX() / 2 + getTranslateX(); float screenWidth = seatBitmapWidth * screenWidthScale * getMatrixScaleX(); if (screenWidth < defaultScreenWidth) { screenWidth = defaultScreenWidth; } Path path = new Path(); path.moveTo(centerX, startY); path.lineTo(centerX - screenWidth / 2, startY); path.lineTo(centerX - screenWidth / 2 + 20, screenHeight * getMatrixScaleY() + startY); path.lineTo(centerX + screenWidth / 2 - 20, screenHeight * getMatrixScaleY() + startY); path.lineTo(centerX + screenWidth / 2, startY); canvas.drawPath(path, pathPaint); pathPaint.setColor(Color.BLACK); pathPaint.setTextSize(20 * getMatrixScaleX()); canvas.drawText(screenName, centerX - pathPaint.measureText(screenName) / 2, getBaseLine(pathPaint, startY, startY + screenHeight * getMatrixScaleY()), pathPaint); } Matrix tempMatrix = new Matrix(); void drawSeat(Canvas canvas) { zoom = getMatrixScaleX(); long startTime = System.currentTimeMillis(); float translateX = getTranslateX(); float translateY = getTranslateY(); float scaleX = zoom; float scaleY = zoom; for (int i = 0; i < row; i++) { float top = i * seatBitmap.getHeight() * yScale1 * scaleY + i * verSpacing * scaleY + translateY; float bottom = top + seatBitmap.getHeight() * yScale1 * scaleY; if (bottom < 0 || top > getHeight()) { continue; } for (int j = 0; j < column; j++) { float left = j * seatBitmap.getWidth() * xScale1 * scaleX + j * spacing * scaleX + translateX; float right = (left + seatBitmap.getWidth() * xScale1 * scaleY); if (right < 0 || left > getWidth()) { continue; } int seatType = getSeatType(i, j); tempMatrix.setTranslate(left, top); tempMatrix.postScale(xScale1, yScale1, left, top); tempMatrix.postScale(scaleX, scaleY, left, top); switch (seatType) { case SEAT_TYPE_AVAILABLE: canvas.drawBitmap(seatBitmap, tempMatrix, paint); break; case SEAT_TYPE_NOT_AVAILABLE: break; case SEAT_TYPE_SELECTED: canvas.drawBitmap(checkedSeatBitmap, tempMatrix, paint); drawText(canvas, i, j, top, left); break; case SEAT_TYPE_SOLD: canvas.drawBitmap(seatSoldBitmap, tempMatrix, paint); break; default: break; } } } if (deBug) { long drawTime = System.currentTimeMillis() - startTime; TLog.d("drawTime", "seatDrawTime:" + drawTime); } } private int getSeatType(int row, int column) { if (isHave(getID(row, column)) >= 0) { return SEAT_TYPE_SELECTED; } if (seatChecker != null) { if (!seatChecker.isValidSeat(row, column)) { return SEAT_TYPE_NOT_AVAILABLE; } else if (seatChecker.isSold(row, column)) { return SEAT_TYPE_SOLD; } } return SEAT_TYPE_AVAILABLE; } private int getID(int row, int column) { return row * this.column + (column + 1); } /** * 绘制选中座位的行号列号 * * @param row 多少排 * @param column 多少座 */ private void drawText(Canvas canvas, int row, int column, float top, float left) { String txt = (row + 1) + "排"; String txt1 = (column + 1) + "座"; if (seatChecker != null) { String[] strings = seatChecker.checkedSeatTxt(row, column); if (strings != null && strings.length > 0) { if (strings.length >= 2) { txt = strings[0]; txt1 = strings[1]; } else { txt = strings[0]; txt1 = null; } } } TextPaint txtPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); txtPaint.setColor(txtColor); txtPaint.setTypeface(Typeface.DEFAULT_BOLD); float seatHeight = this.seatHeight * getMatrixScaleX(); float seatWidth = this.seatWidth * getMatrixScaleX(); txtPaint.setTextSize(seatHeight / 3); //获取中间线 float center = seatHeight / 2; float txtWidth = txtPaint.measureText(txt); float startX = left + seatWidth / 2 - txtWidth / 2; //只绘制一行文字 if (txt1 == null) { canvas.drawText(txt, startX, getBaseLine(txtPaint, top, top + seatHeight), txtPaint); } else { canvas.drawText(txt, startX, getBaseLine(txtPaint, top, top + center), txtPaint); canvas.drawText(txt1, startX, getBaseLine(txtPaint, top + center, top + center + seatHeight / 2), txtPaint); } if (deBug) { TLog.d("drawTest:", "top:" + top); } } int bacColor = Color.parseColor("#7e000000"); /** * 绘制行号 */ void drawNumber(Canvas canvas) { long startTime = System.currentTimeMillis(); lineNumberPaint.setColor(bacColor); int translateY = (int) getTranslateY(); float scaleY = getMatrixScaleY(); rectF.top = translateY - lineNumberTxtHeight / 2; rectF.bottom = translateY + (seatBitmapHeight * scaleY) + lineNumberTxtHeight / 2; rectF.left = 0; rectF.right = numberWidth; canvas.drawRoundRect(rectF, numberWidth / 2, numberWidth / 2, lineNumberPaint); lineNumberPaint.setColor(Color.WHITE); for (int i = 0; i < row; i++) { float top = (i * seatHeight + i * verSpacing) * scaleY + translateY; float bottom = (i * seatHeight + i * verSpacing + seatHeight) * scaleY + translateY; float baseline = (bottom + top - lineNumberPaintFontMetrics.bottom - lineNumberPaintFontMetrics.top) / 2; canvas.drawText(lineNumbers.get(i), numberWidth / 2, baseline, lineNumberPaint); } if (deBug) { long drawTime = System.currentTimeMillis() - startTime; TLog.d("drawTime", "drawNumberTime:" + drawTime); } } /** * 绘制概览图 */ void drawOverview(Canvas canvas) { //绘制红色框 int left = (int) -getTranslateX(); if (left < 0) { left = 0; } left /= overviewScale; left /= getMatrixScaleX(); int currentWidth = (int) (getTranslateX() + (column * seatWidth + spacing * (column - 1)) * getMatrixScaleX()); if (currentWidth > getWidth()) { currentWidth = currentWidth - getWidth(); } else { currentWidth = 0; } int right = (int) (rectW - currentWidth / overviewScale / getMatrixScaleX()); float top = -getTranslateY() + headHeight; if (top < 0) { top = 0; } top /= overviewScale; top /= getMatrixScaleY(); if (top > 0) { top += overviewVerSpacing; } int currentHeight = (int) (getTranslateY() + (row * seatHeight + verSpacing * (row - 1)) * getMatrixScaleY()); if (currentHeight > getHeight()) { currentHeight = currentHeight - getHeight(); } else { currentHeight = 0; } int bottom = (int) (rectH - currentHeight / overviewScale / getMatrixScaleY()); canvas.drawRect(left, top, right, bottom, redBorderPaint); } Bitmap drawOverview() { isDrawOverviewBitmap = false; int bac = Color.parseColor("#7e000000"); overviewPaint.setColor(bac); overviewPaint.setAntiAlias(true); overviewPaint.setStyle(Paint.Style.FILL); overviewBitmap.eraseColor(Color.TRANSPARENT); Canvas canvas = new Canvas(overviewBitmap); //绘制透明灰色背景 canvas.drawRect(0, 0, rectW, rectH, overviewPaint); overviewPaint.setColor(Color.WHITE); for (int i = 0; i < row; i++) { float top = i * rectHeight + i * overviewVerSpacing + overviewVerSpacing; for (int j = 0; j < column; j++) { int seatType = getSeatType(i, j); switch (seatType) { case SEAT_TYPE_AVAILABLE: overviewPaint.setColor(Color.WHITE); break; case SEAT_TYPE_NOT_AVAILABLE: continue; case SEAT_TYPE_SELECTED: overviewPaint.setColor(overviewChecked); break; case SEAT_TYPE_SOLD: overviewPaint.setColor(overviewSold); break; default: break; } float left; left = j * rectWidth + j * overviewSpacing + overviewSpacing; canvas.drawRect(left, top, left + rectWidth, top + rectHeight, overviewPaint); } } return overviewBitmap; } /** * 自动回弹 * 整个大小不超过控件大小的时候: * 往左边滑动,自动回弹到行号右边 * 往右边滑动,自动回弹到右边 * 往上,下滑动,自动回弹到顶部 * <p> * 整个大小超过控件大小的时候: * 往左侧滑动,回弹到最右边,往右侧滑回弹到最左边 * 往上滑动,回弹到底部,往下滑动回弹到顶部 */ private void autoScroll() { float currentSeatBitmapWidth = seatBitmapWidth * getMatrixScaleX(); float currentSeatBitmapHeight = seatBitmapHeight * getMatrixScaleY(); float moveYLength = 0; float moveXLength = 0; //处理左右滑动的情况 if (currentSeatBitmapWidth < getWidth()) { if (getTranslateX() < 0 || getMatrixScaleX() < numberWidth + spacing) { //计算要移动的距离 if (getTranslateX() < 0) { moveXLength = (-getTranslateX()) + numberWidth + spacing; } else { moveXLength = numberWidth + spacing - getTranslateX(); } } } else { if (getTranslateX() < 0 && getTranslateX() + currentSeatBitmapWidth > getWidth()) { } else { //往左侧滑动 if (getTranslateX() + currentSeatBitmapWidth < getWidth()) { moveXLength = getWidth() - (getTranslateX() + currentSeatBitmapWidth); } else { //右侧滑动 moveXLength = -getTranslateX() + numberWidth + spacing; } } } float startYPosition = screenHeight * getMatrixScaleY() + verSpacing * getMatrixScaleY() + headHeight + borderHeight; //处理上下滑动 if (currentSeatBitmapHeight + headHeight < getHeight()) { if (getTranslateY() < startYPosition) { moveYLength = startYPosition - getTranslateY(); } else { moveYLength = -(getTranslateY() - (startYPosition)); } } else { if (getTranslateY() < 0 && getTranslateY() + currentSeatBitmapHeight > getHeight()) { } else { //往上滑动 if (getTranslateY() + currentSeatBitmapHeight < getHeight()) { moveYLength = getHeight() - (getTranslateY() + currentSeatBitmapHeight); } else { moveYLength = -(getTranslateY() - (startYPosition)); } } } Point start = new Point(); start.x = (int) getTranslateX(); start.y = (int) getTranslateY(); Point end = new Point(); end.x = (int) (start.x + moveXLength); end.y = (int) (start.y + moveYLength); moveAnimate(start, end); } private void autoScale() { if (getMatrixScaleX() > 2.2) { zoomAnimate(getMatrixScaleX(), 2.0f); } else if (getMatrixScaleX() < 0.98) { zoomAnimate(getMatrixScaleX(), 1.0f); } } Handler handler = new Handler(); ArrayList<Integer> selects = new ArrayList<>(); public ArrayList<String> getSelectedSeat() { ArrayList<String> results = new ArrayList<>(); for (int i = 0; i < this.row; i++) { for (int j = 0; j < this.column; j++) { if (isHave(getID(i, j)) >= 0) { results.add(i + "," + j); } } } return results; } private int isHave(Integer seat) { return Collections.binarySearch(selects, seat); } private void remove(int index) { selects.remove(index); } float[] m = new float[9]; private float getTranslateX() { matrix.getValues(m); return m[2]; } private float getTranslateY() { matrix.getValues(m); return m[5]; } private float getMatrixScaleY() { matrix.getValues(m); return m[4]; } private float getMatrixScaleX() { matrix.getValues(m); return m[Matrix.MSCALE_X]; } private float getBaseLine(Paint p, float top, float bottom) { Paint.FontMetrics fontMetrics = p.getFontMetrics(); int baseline = (int) ((bottom + top - fontMetrics.bottom - fontMetrics.top) / 2); return baseline; } private void moveAnimate(Point start, Point end) { ValueAnimator valueAnimator = ValueAnimator.ofObject(new MoveEvaluator(), start, end); valueAnimator.setInterpolator(new DecelerateInterpolator()); MoveAnimation moveAnimation = new MoveAnimation(); valueAnimator.addUpdateListener(moveAnimation); valueAnimator.setDuration(400); valueAnimator.start(); } private void zoomAnimate(float cur, float tar) { ValueAnimator valueAnimator = ValueAnimator.ofFloat(cur, tar); valueAnimator.setInterpolator(new DecelerateInterpolator()); ZoomAnimation zoomAnim = new ZoomAnimation(); valueAnimator.addUpdateListener(zoomAnim); valueAnimator.addListener(zoomAnim); valueAnimator.setDuration(400); valueAnimator.start(); } private float zoom; private void zoom(float zoom) { float z = zoom / getMatrixScaleX(); matrix.postScale(z, z, scaleX, scaleY); invalidate(); } private void move(Point p) { float x = p.x - getTranslateX(); float y = p.y - getTranslateY(); matrix.postTranslate(x, y); invalidate(); } class MoveAnimation implements ValueAnimator.AnimatorUpdateListener { @Override public void onAnimationUpdate(ValueAnimator animation) { Point p = (Point) animation.getAnimatedValue(); move(p); } } class MoveEvaluator implements TypeEvaluator { @Override public Object evaluate(float fraction, Object startValue, Object endValue) { Point startPoint = (Point) startValue; Point endPoint = (Point) endValue; int x = (int) (startPoint.x + fraction * (endPoint.x - startPoint.x)); int y = (int) (startPoint.y + fraction * (endPoint.y - startPoint.y)); return new Point(x, y); } } class ZoomAnimation implements ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener { @Override public void onAnimationUpdate(ValueAnimator animation) { zoom = (Float) animation.getAnimatedValue(); zoom(zoom); if (deBug) { TLog.d("zoomTest", "zoom:" + zoom); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationStart(Animator animation) { } } public void setData(int row, int column) { this.row = row; this.column = column; init(); invalidate(); } ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(getContext(), new ScaleGestureDetector.OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { isScaling = true; float scaleFactor = detector.getScaleFactor(); if (getMatrixScaleY() * scaleFactor > 3) { scaleFactor = 3 / getMatrixScaleY(); } if (firstScale) { scaleX = detector.getCurrentSpanX(); scaleY = detector.getCurrentSpanY(); firstScale = false; } if (getMatrixScaleY() * scaleFactor < 0.5) { scaleFactor = 0.5f / getMatrixScaleY(); } matrix.postScale(scaleFactor, scaleFactor, scaleX, scaleY); invalidate(); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { isScaling = false; firstScale = true; } }); GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapConfirmed(MotionEvent e) { isOnClick = true; int x = (int) e.getX(); int y = (int) e.getY(); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { int tempX = (int) ((j * seatWidth + j * spacing) * getMatrixScaleX() + getTranslateX()); int maxTemX = (int) (tempX + seatWidth * getMatrixScaleX()); int tempY = (int) ((i * seatHeight + i * verSpacing) * getMatrixScaleY() + getTranslateY()); int maxTempY = (int) (tempY + seatHeight * getMatrixScaleY()); if (seatChecker != null && seatChecker.isValidSeat(i, j) && !seatChecker.isSold(i, j)) { if (x >= tempX && x <= maxTemX && y >= tempY && y <= maxTempY) { int id = getID(i, j); int index = isHave(id); if (index >= 0) { remove(index); if (seatChecker != null) { seatChecker.unCheck(i, j); } } else { if (selects.size() >= maxSelected) { Toast.makeText(getContext(), "最多只能选择" + maxSelected + "个", Toast.LENGTH_SHORT).show(); return super.onSingleTapConfirmed(e); } else { addChooseSeat(i, j); if (seatChecker != null) { seatChecker.checked(i, j); } } } isNeedDrawSeatBitmap = true; isDrawOverviewBitmap = true; float currentScaleY = getMatrixScaleY(); if (currentScaleY < 1.7) { scaleX = x; scaleY = y; zoomAnimate(currentScaleY, 1.9f); } invalidate(); break; } } } } return super.onSingleTapConfirmed(e); } }); private void addChooseSeat(int row, int column) { int id = getID(row, column); for (int i = 0; i < selects.size(); i++) { int item = selects.get(i); if (id < item) { selects.add(i, id); return; } } selects.add(id); } public interface SeatChecker { /** * 是否可用座位 * * @param row * @param column * @return */ boolean isValidSeat(int row, int column); /** * 是否已售 * * @param row * @param column * @return */ boolean isSold(int row, int column); void checked(int row, int column); void unCheck(int row, int column); /** * 获取选中后座位上显示的文字 * * @param row * @param column * @return 返回2个元素的数组, 第一个元素是第一行的文字, 第二个元素是第二行文字, 如果只返回一个元素则会绘制到座位图的中间位置 */ String[] checkedSeatTxt(int row, int column); } public void setScreenName(String screenName) { this.screenName = screenName; } public void setMaxSelected(int maxSelected) { this.maxSelected = maxSelected; } public void setSeatChecker(SeatChecker seatChecker) { this.seatChecker = seatChecker; invalidate(); } private int getRowNumber(int row) { int result = row; if (seatChecker == null) { return -1; } for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (seatChecker.isValidSeat(i, j)) { break; } if (j == column - 1) { if (i == row) { return -1; } result--; } } } return result; } private int getColumnNumber(int row, int column) { int result = column; if (seatChecker == null) { return -1; } for (int i = row; i <= row; i++) { for (int j = 0; j < column; j++) { if (!seatChecker.isValidSeat(i, j)) { if (j == column) { return -1; } result--; } } } return result; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } }
Tamsiree/RxTool
RxUI/src/main/java/com/tamsiree/rxui/view/RxSeatMovie.java
1,316
package org.nutz.lang; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.nutz.lang.util.Regex; /** * 关于数的一些帮助函数 * * @author zozoh([email protected]) */ public abstract class Nums { /** * 对齐浮点数精度,超过精度四舍五入 * * @param n * 浮点数 * @param dp * 精度 * @return 对齐精度的浮点数 */ public static float precision(float n, int dp) { if (0 == dp) { return Math.round(n); } if (1 == dp) { return Math.round(n * 10f) / 10f; } if (2 == dp) { return Math.round(n * 100f) / 100f; } if (3 == dp) { return Math.round(n * 1000f) / 1000f; } // 其他精度 float p = (float) Math.pow(10, dp); return Math.round(n * p) / p; } /** * 对齐双精度浮点精度,超过精度四舍五入 * * @param n * 双精度浮点数 * @param dp * 精度 * @return 对齐精度的双精度浮点数 */ public static double precision(double n, int dp) { if (0 == dp) { return Math.round(n); } if (1 == dp) { return Math.round(n * 10) / 10.0; } if (2 == dp) { return Math.round(n * 100) / 100.0; } if (3 == dp) { return Math.round(n * 1000) / 1000.0; } // 其他精度 double p = Math.pow(10, dp); return Math.round(n * p) / p; } /** * @param a * 数字 * @param b * 数字 * @return 两个数的最大公约数 <code>greatest common divisor(gcd)</code> */ public static int gcd(int a, int b) { a = Math.round(a); b = Math.round(b); if (b != 0) { return gcd(b, a % b); } return a; } /** * @param list * 一组整数 * @return 一组整数的最大公约数 <code>greatest common divisor(gcd)</code> */ public static int gcds(int... list) { // 没数 if (list.length == 0) return Integer.MIN_VALUE; // 一个是自己 if (list.length == 1) { return list[0]; } // 两个以上 int gcd = gcd(list[0], list[1]); for (int i = 2; i < list.length; i++) { gcd = gcd(gcd, list[i]); } // 返回 return gcd; } /** * @param a * 数字 * @param b * 数字 * @return 两个数的最小公倍数 <code>lowest common multiple (LCM)</code> */ public static int lcm(int a, int b) { a = Math.round(a); b = Math.round(b); return a * b / gcd(a, b); } /** * @param list * 一组整数 * @return 一组整数的最小公倍数 <code>lowest common multiple (LCM)</code> */ public static int lcms(int... list) { // 没数 if (list.length == 0) return Integer.MAX_VALUE; // 一个是自己 if (list.length == 1) { return list[0]; } // 两个以上 int lcm = lcm(list[0], list[1]); for (int i = 2; i < list.length; i++) { lcm = lcm(lcm, list[i]); } // 返回 return lcm; } /** * 计算尺寸 * * @param v * 要计算的尺寸值的类型可以是 * <ul> * <li>500 - 整数,直接返回 * <li>.12 - 浮点,相当于一个百分比,可以大于 1.0 * <li>"12%" - 百分比,相当于 .12 * </ul> * @param base * 百分比的基数 * * @return 根据基数计算后的数值 */ public static double dimension(String v, double base) { // 试试整型 try { Integer nb = Integer.valueOf(v); return nb.intValue(); } catch (NumberFormatException e) {} // 试试浮点 try { Double nb = Double.valueOf(v); return nb.doubleValue() * base; } catch (NumberFormatException e) {} // 百分比 Pattern p = Regex.getPattern("^([0-9.]{1,})%$"); Matcher m = p.matcher(v); if (m.find()) { Double nb = Double.valueOf(m.group(1)); return (nb.doubleValue() / 100) * base; } // 靠不知道是啥 throw Lang.makeThrow("fail to dimension : " + v); } /** * @see #dimension(String, double) */ public static int dimension(String v, int base) { return (int) (dimension(v, (double) base)); } /** * @param nbs * 一组数字 * @return 数字之和 */ public static int sum(int... nbs) { int re = 0; for (int nb : nbs) re += nb; return re; } /** * 一个数的字面量的进制和值 */ public static class Radix { Radix(String val, int radix) { this.val = val; this.radix = radix; } public int radix; public String val; } /** * @param str * 数字的字符串 * @return 字符串的进制 * * @see org.nutz.lang.Nums.Radix */ public static Radix evalRadix(String str) { if (str.startsWith("0x")) return new Radix(str.substring(2), 16); if (str.startsWith("0") && str.length() > 1) return new Radix(str.substring(1), 8); if (str.startsWith("0b")) return new Radix(str.substring(2), 2); return new Radix(str, 10); } /** * 将一个字符串变成一个整型数组,如果字符串不符合规则,对应的元素为 -1 <br> * 比如: * * <pre> * "3,4,9" => [ 3, 4, 9 ] * "a,9,100" => [ -1, 9, 100 ] * </pre> * * @param str * 半角逗号分隔的数字字符串 * @return 数组 */ public static int[] splitInt(String str) { String[] ss = Strings.splitIgnoreBlank(str); if (null == ss) return null; int[] ns = new int[ss.length]; for (int i = 0; i < ns.length; i++) { try { ns[i] = Integer.parseInt(ss[i]); } catch (NumberFormatException e) { ns[i] = -1; } } return ns; } /** * @see #splitInt(String) */ public static long[] splitLong(String str) { String[] ss = Strings.splitIgnoreBlank(str); if (null == ss) return null; long[] ns = new long[ss.length]; for (int i = 0; i < ns.length; i++) { try { ns[i] = Long.parseLong(ss[i]); } catch (NumberFormatException e) { ns[i] = -1; } } return ns; } /** * 将一个字符串变成一个浮点数数组,如果字符串不符合规则,对应的元素为 0.0 <br> * 比如: * * <pre> * "3,4,9" => [ 3.0f, 4.0f, 9.0f ] * "a,9.8,100" => [ 0.0f, 9.0f, 100.0f ] * </pre> * * @param str * 半角逗号分隔的数字字符串 * @return 数组 */ public static float[] splitFloat(String str) { String[] ss = Strings.splitIgnoreBlank(str); if (null == ss) return null; float[] ns = new float[ss.length]; for (int i = 0; i < ns.length; i++) { try { ns[i] = Float.parseFloat(ss[i]); } catch (NumberFormatException e) { ns[i] = 0.0f; } } return ns; } /** * 将一个字符串变成一个双精度数数组,如果字符串不符合规则,对应的元素为 -1 * * @param str * 半角逗号分隔的数字字符串 * @return 数组 */ public static double[] splitDouble(String str) { String[] ss = Strings.splitIgnoreBlank(str); if (null == ss) return null; double[] ns = new double[ss.length]; for (int i = 0; i < ns.length; i++) { try { ns[i] = Long.parseLong(ss[i]); } catch (NumberFormatException e) { ns[i] = -1; } } return ns; } /** * @see #splitInt(String) */ public static boolean[] splitBoolean(String str) { String[] ss = Strings.splitIgnoreBlank(str); if (null == ss) return null; boolean[] ns = new boolean[ss.length]; for (int i = 0; i < ns.length; i++) { try { ns[i] = Regex.match("^(1|yes|true|on)$", ss[i].toLowerCase()); } catch (NumberFormatException e) { ns[i] = false; } } return ns; } /** * @see #indexOf(int[], int, int) */ public static int indexOf(int[] arr, int v) { return indexOf(arr, v, 0); } /** * @param arr * 数组 * @param v * 值 * @param off * 从那个下标开始搜索(包含) * @return 第一个匹配元素的下标 */ public static int indexOf(int[] arr, int v, int off) { if (null != arr) for (int i = off; i < arr.length; i++) { if (arr[i] == v) return i; } return -1; } /** * @param arr * @param v * @return 最后一个匹配元素的下标 */ public static int lastIndexOf(int[] arr, int v) { if (null != arr) for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == v) return i; } return -1; } /** * @see #indexOf(char[], char, int) */ public static int indexOf(char[] arr, char v) { if (null != arr) for (int i = 0; i < arr.length; i++) { if (arr[i] == v) return i; } return -1; } /** * @param arr * 数组 * @param v * 值 * @param off * 从那个下标开始搜索(包含) * @return 第一个匹配元素的下标 */ public static int indexOf(char[] arr, char v, int off) { if (null != arr) for (int i = off; i < arr.length; i++) { if (arr[i] == v) return i; } return -1; } /** * @param arr * @param v * @return 第一个匹配元素的下标 */ public static int lastIndexOf(char[] arr, char v) { if (null != arr) for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == v) return i; } return -1; } /** * @see #indexOf(long[], long, int) */ public static int indexOf(long[] arr, long v) { return indexOf(arr, v, 0); } /** * @param arr * 数组 * @param v * 值 * @param off * 从那个下标开始搜索(包含) * @return 第一个匹配元素的下标 */ public static int indexOf(long[] arr, long v, int off) { if (null != arr) for (int i = off; i < arr.length; i++) { if (arr[i] == v) return i; } return -1; } /** * @param arr * @param v * @return 第一个匹配元素的下标 */ public static int lastIndexOf(long[] arr, long v) { if (null != arr) for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] == v) return i; } return -1; } /** * 不解释,你懂的 */ public static int[] array(int... is) { return is; } /** * 判断一个整数是否在数组中 * * @param arr * 数组 * @param i * 整数 * @return 是否存在 */ public static boolean isin(int[] arr, int i) { return indexOf(arr, i) >= 0; } /** * 整合两个整数数组为一个数组 <b>这个方法在JDK5不可用!!<b/> * * @param arr * 整数数组 * @param is * 变参 * @return 新的整合过的数组 */ public static int[] join(int[] arr, int... is) { if (null == arr) return is; int length = arr.length + is.length; int[] re = new int[length]; System.arraycopy(arr, 0, re, 0, arr.length); int i = arr.length; for (int num : is) re[i++] = num; return re; } /** * 不解释,你懂的 */ public static long[] arrayL(long... is) { return is; } /** * 判断一个长整数是否在数组中 * * @param arr * 数组 * @param i * 长整数 * @return 是否存在 */ public static boolean isin(long[] arr, long i) { return indexOf(arr, i) >= 0; } /** * 整合两个长整数数组为一个数组 <b>这个方法在JDK5不可用!!<b/> * * @param arr * 长整数数组 * @param is * 变参 * @return 新的整合过的数组 */ public static long[] join(long[] arr, long... is) { if (null == arr) return is; int length = arr.length + is.length; long[] re = new long[length]; System.arraycopy(arr, 0, re, 0, arr.length); int i = arr.length; for (long num : is) re[i++] = num; return re; } /** * 不解释,你懂的 */ public static char[] arrayC(char... is) { return is; } /** * 判断一个长整数是否在数组中 * * @param arr * 数组 * @param i * 长整数 * @return 是否存在 */ public static boolean isin(char[] arr, char i) { return indexOf(arr, i) >= 0; } /** * 整合两个长整数数组为一个数组 <b>这个方法在JDK5不可用!!<b/> * * @param arr * 长整数数组 * @param is * 变参 * @return 新的整合过的数组 */ public static char[] join(char[] arr, char... is) { if (null == arr) return is; int length = arr.length + is.length; char[] re = new char[length]; System.arraycopy(arr, 0, re, 0, arr.length); int i = arr.length; for (char num : is) re[i++] = num; return re; } }
nutzam/nutz
src/org/nutz/lang/Nums.java
1,317
package org.nutz.img; import static java.lang.Integer.parseInt; import static org.nutz.lang.Strings.dup; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.nutz.lang.Strings; import org.nutz.lang.random.R; /** * 提供快捷的解析颜色值的方法 * * 颜色值的字符串类型支持如下: * <ul> * <li>RGB: #FFF * <li>RRGGBB: #F0F0F0 * <li>ARGB: #9FE5 * <li>AARRGGBB: #88FF8899 * <li>RGB值: rgb(255,33,89) * <li>RGBA值: rgba(6,6,6,0.8) * </ul> * * @author zozoh([email protected]) */ public final class Colors { /** * RGB: #FFF */ private static Pattern FFF_PATTERN = Pattern.compile("^([0-9A-F])([0-9A-F])([0-9A-F])$"); /** * RRGGBB: #F0F0F0 */ private static Pattern F0F0F0_PATTERN = Pattern.compile("^([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$"); /** * ARGB: #9FE5 */ private static Pattern ARGB = Pattern.compile("^([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])$"); /** * AARRGGBB: #88FF8899 */ private static Pattern AARRGGBB_PATTERN = Pattern.compile("^([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$"); /** * RGB值: rgb(255,33,89) */ private static Pattern RGB_PATTERN = Pattern.compile("^RGB\\s*[(]\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*[)]$"); /** * RGBA值: rgba(6,6,6,0.9) */ private static Pattern RGBA_PATTERN = Pattern.compile("^RGBA\\s*[(]\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*((\\d[.])?\\d+)\\s*[)]$"); /** * @see #as(String) * * @deprecated */ @Deprecated public static Color fromString(String str) { return as(str); } /** * 将字符串变成颜色值 * * @param str * 颜色字符串,详细,请参看本类的总体描述,如果为空,则表示黑色 * @return 颜色对象 */ public static Color as(String str) { if (null == str) { return Color.BLACK; } // 整理一下字符串以便后面匹配分析 str = Strings.trim(str.toUpperCase()); if (str.startsWith("#")) { str = str.substring(1); } if (str.endsWith(";")) { str = str.substring(0, str.length() - 1); } // RGB: #FFF Pattern p = FFF_PATTERN; Matcher m = p.matcher(str); if (m.find()) { return new Color(parseInt(dup(m.group(1), 2), 16), parseInt(dup(m.group(2), 2), 16), parseInt(dup(m.group(3), 2), 16)); } // RRGGBB: #F0F0F0 p = F0F0F0_PATTERN; m = p.matcher(str); if (m.find()) { return new Color(parseInt(m.group(1), 16), parseInt(m.group(2), 16), parseInt(m.group(3), 16)); } // ARGB: #9FE5 p = ARGB; m = p.matcher(str); if (m.find()) { return new Color(parseInt(dup(m.group(2), 2), 16), parseInt(dup(m.group(3), 2), 16), parseInt(dup(m.group(4), 2), 16), parseInt(dup(m.group(1), 2), 16)); } // AARRGGBB: #88FF8899 p = AARRGGBB_PATTERN; m = p.matcher(str); if (m.find()) { return new Color(parseInt(m.group(2), 16), parseInt(m.group(3), 16), parseInt(m.group(4), 16), parseInt(m.group(1), 16)); } // RGB值: rgb(255,33,89) p = RGB_PATTERN; m = p.matcher(str); if (m.find()) { return new Color(parseInt(m.group(1), 10), parseInt(m.group(2), 10), parseInt(m.group(3), 10)); } // // RGBA值: rgba(6,6,6,255) // p = // Pattern.compile("^RGBA\\s*[(]\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*[)]$"); // m = p.matcher(str); // if (m.find()) { // return new Color(parseInt(m.group(1), 10), // parseInt(m.group(2), 10), // parseInt(m.group(3), 10), // parseInt(m.group(4), 10)); // } // RGBA值: rgba(6,6,6,0.9) p = RGBA_PATTERN; m = p.matcher(str); if (m.find()) { float alpha = Float.parseFloat(m.group(4)); return new Color(parseInt(m.group(1), 10), parseInt(m.group(2), 10), parseInt(m.group(3), 10), (int) (255.0f * alpha)); } // 全都匹配不上,返回黑色 return Color.BLACK; } /** * Color转换为 “rgb(12, 25, 33)” 格式字符串 * * @param color * 颜色 * @return 文字格式 */ public static String toRGB(Color color) { return String.format("rgb(%d, %d, %d)", color.getRed(), color.getGreen(), color.getBlue()); } /** * 获取一个制定范围内的颜色 * * @param min * 最小取值,范围0-255 * @param max * 最大取值,范围0-255 * @return 颜色 */ public static Color randomColor(int min, int max) { if (min > 255) { min = 255; } if (min < 0) { min = 0; } if (max > 255) { max = 255; } if (max < 0) { max = 0; } return new Color(min + R.random(0, max - min), min + R.random(0, max - min), min + R.random(0, max - min)); } /** * 获取一个随机颜色 * * @return 颜色 */ public static Color randomColor() { return randomColor(0, 255); } /** * 获取图片指定像素点的RGB值 * * @param srcIm * 源图片 * @param x * 横坐标 * @param y * 纵坐标 * @return RGB值数组 */ public static int[] getRGB(BufferedImage srcIm, int x, int y) { int pixel = srcIm.getRGB(x, y); return getRGB(pixel); } /** * 获取像素点的RGB值(三元素数组)) * * @param pixel * 像素RGB值 * @return RGB值数组 */ public static int[] getRGB(int pixel) { int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = pixel & 0xff; return new int[]{r, g, b}; } public static int getAlpha(int pixel) { ColorModel cm = ColorModel.getRGBdefault(); return cm.getAlpha(pixel); } /** * 获取图片指定像素点的亮度值(YUV中的Y) * * @param srcIm * 源图片 * @param x * 横坐标 * @param y * 纵坐标 * @return 亮度值 */ public static int getLuminance(BufferedImage srcIm, int x, int y) { int[] rgb = getRGB(srcIm, x, y); return (int) (0.3 * rgb[0] + 0.59 * rgb[1] + 0.11 * rgb[2]); // 加权法 } /** * 获取图片指定像素点的亮度值(YUV中的Y) 类型为double * * @param srcIm * 源图片 * @param x * 横坐标 * @param y * 纵坐标 * @return 亮度值 */ public static double getLuminanceDouble(BufferedImage srcIm, int x, int y) { int[] rgb = getRGB(srcIm, x, y); return 0.3 * rgb[0] + 0.59 * rgb[1] + 0.11 * rgb[2]; // 加权法 } /** * 获取图片指定像素点的灰度值 * * @param srcIm * 源图片 * @param x * 横坐标 * @param y * 纵坐标 * @return 灰度值 */ public static int getGray(BufferedImage srcIm, int x, int y) { int grayValue = getLuminance(srcIm, x, y); int newPixel = 0; newPixel = (grayValue << 16) & 0x00ff0000 | (newPixel & 0xff00ffff); newPixel = (grayValue << 8) & 0x0000ff00 | (newPixel & 0xffff00ff); newPixel = (grayValue) & 0x000000ff | (newPixel & 0xffffff00); return newPixel; } /** * 获取两个像素点正片叠底后的像素值 * * @param pixel1 * 像素点1 * @param pixel2 * 像素点1 * @return 新像素点值 */ public static int getMultiply(int pixel1, int pixel2) { int[] rgb1 = getRGB(pixel1); int[] rgb2 = getRGB(pixel2); int r = rgb1[0] * rgb2[0] / 255; int g = rgb1[1] * rgb2[1] / 255; int b = rgb1[2] * rgb2[2] / 255; return new Color(r, g, b).getRGB(); } private Colors() {} }
nutzam/nutz
src/org/nutz/img/Colors.java
1,319
package org.nutz.json; import static org.nutz.lang.Streams.buffr; import static org.nutz.lang.Streams.fileInr; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.nutz.json.entity.JsonEntity; import org.nutz.json.handler.JsonArrayHandler; import org.nutz.json.handler.JsonBooleanHandler; import org.nutz.json.handler.JsonClassHandler; import org.nutz.json.handler.JsonDateTimeHandler; import org.nutz.json.handler.JsonEnumHandler; import org.nutz.json.handler.JsonIterableHandler; import org.nutz.json.handler.JsonJsonRenderHandler; import org.nutz.json.handler.JsonLocalDateLikeHandler; import org.nutz.json.handler.JsonMapHandler; import org.nutz.json.handler.JsonMirrorHandler; import org.nutz.json.handler.JsonNumberHandler; import org.nutz.json.handler.JsonPojoHandler; import org.nutz.json.handler.JsonStringLikeHandler; import org.nutz.json.impl.JsonEntityFieldMakerImpl; import org.nutz.json.impl.JsonRenderImpl; import org.nutz.lang.Files; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Streams; import org.nutz.lang.util.NutType; import org.nutz.lang.util.PType; import org.nutz.mapl.Mapl; public class Json { // ========================================================================= // ============================Json.fromJson================================ // ========================================================================= /** * 从文本输入流中生成 JAVA 对象。 * * @param reader * 文本输入流 * @return JAVA 对象 * @throws JsonException */ public static Object fromJson(Reader reader) throws JsonException { // return new org.nutz.json.impl.JsonCompileImpl().parse(reader); return new org.nutz.json.impl.JsonCompileImplV2().parse(reader); } /** * 根据指定的类型,从文本输入流中生成 JAVA 对象。 指定的类型可以是任意 JAVA 对象。 * * @param type * 对象类型 * @param reader * 文本输入流 * @return 指定类型的 JAVA 对象 * @throws JsonException */ @SuppressWarnings("unchecked") public static <T> T fromJson(Class<T> type, Reader reader) throws JsonException { return (T) parse(type, reader); } /** * 根据指定的类型,从文本输入流中生成 JAVA 对象。 指定的类型可以是任意 JAVA 对象。 * * @param type * 对象类型,可以是范型 * @param reader * 文本输入流 * @return 指定类型的 JAVA 对象 * @throws JsonException */ public static Object fromJson(Type type, Reader reader) throws JsonException { return parse(type, reader); } private static Object parse(Type type, Reader reader) { Object obj = fromJson(reader); if (type != null) return Mapl.maplistToObj(obj, type); return obj; } /** * 根据指定的类型,从字符串中生成 JAVA 对象。 指定的类型可以是任意 JAVA 对象。 * * @param type * 对象类型,可以是范型 * @param cs * JSON 字符串 * @return 指定类型的 JAVA 对象 * @throws JsonException */ public static Object fromJson(Type type, CharSequence cs) throws JsonException { return fromJson(type, Lang.inr(cs)); } @SuppressWarnings("unchecked") public static <T> T fromJson(PType<T> type, Reader reader) throws JsonException { return (T) fromJson((Type)type, reader); } @SuppressWarnings("unchecked") public static <T> T fromJson(PType<T> type, CharSequence cs) throws JsonException { return (T)fromJson((Type)type, cs); } /** * 根据指定的类型,读取指定的 JSON 文件生成 JAVA 对象。 指定的类型可以是任意 JAVA 对象。 * * @param type * 对象类型 * @param f * 文件对象 * @return 指定类型的 JAVA 对象 * @throws JsonException */ public static <T> T fromJsonFile(Class<T> type, File f) { BufferedReader br = null; try { br = buffr(fileInr(f)); return Json.fromJson(type, br); } finally { Streams.safeClose(br); } } /** * 从 JSON 字符串中,获取 JAVA 对象。 实际上,它就是用一个 Read 包裹了的字符串。 * <p> * 请参看函数 ‘Object fromJson(Reader reader)’ 的描述 * * @param cs * JSON 字符串 * @return JAVA 对象 * @throws JsonException * * @see #fromJson(Reader reader) */ public static Object fromJson(CharSequence cs) throws JsonException { return fromJson(Lang.inr(cs)); } /** * 根据指定的类型,从字符串中生成 JAVA 对象。 指定的类型可以是任意 JAVA 对象。 * <p> * 请参看函数 ‘<T> T fromJson(Class<T> type, Reader reader)’ 的描述 * * @param type * 对象类型 * @param cs * JSON 字符串 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Class type, Reader reader) */ public static <T> T fromJson(Class<T> type, CharSequence cs) throws JsonException { return fromJson(type, Lang.inr(cs)); } // ========================================================================= // ============================Json.toJson================================== // ========================================================================= private static Class<? extends JsonRender> jsonRenderCls; public static Class<? extends JsonRender> getJsonRenderCls() { return jsonRenderCls; } public static void setJsonRenderCls(Class<? extends JsonRender> cls) { jsonRenderCls = cls; } /** * 将一个 JAVA 对象转换成 JSON 字符串 * * @param obj * JAVA 对象 * @return JSON 字符串 */ public static String toJson(Object obj) { return toJson(obj, null); } /** * 将一个 JAVA 对象转换成 JSON 字符串,并且可以设定 JSON 字符串的格式化方式 * * @param obj * JAVA 对象 * @param format * JSON 字符串格式化方式 ,若 format 为 null ,则以 JsonFormat.nice() 格式输出 * @return JSON 字符串 */ public static String toJson(Object obj, JsonFormat format) { StringBuilder sb = new StringBuilder(); toJson(Lang.opw(sb), obj, format); return sb.toString(); } /** * 将一个 JAVA 对象以 JSON 的形式写到一个文本输出流里 * * @param writer * 文本输出流 * @param obj * JAVA 对象 */ public static void toJson(Writer writer, Object obj) { toJson(writer, obj, null); } /** * 将一个 JAVA 对象以 JSON 的形式写到一个文本输出流里,并且可以设定 JSON 字符串的格式化方式 * * @param writer * 文本输出流 * @param obj * JAVA 对象 * @param format * JSON 字符串格式化方式 ,若 format 为 null ,则以 JsonFormat.nice() 格式输出 */ public static void toJson(Writer writer, Object obj, JsonFormat format) { try { if (format == null) format = deft; JsonRender jr; Class<? extends JsonRender> jrCls = getJsonRenderCls(); if (jrCls == null) jr = new JsonRenderImpl(); else jr = Mirror.me(jrCls).born(); jr.setWriter(writer); jr.setFormat(format); jr.render(obj); writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e, JsonException.class); } } /** * 将一个 JAVA 对象以 JSON 的形式写到一个文件里 * * @param f * 文本文件 * @param obj * JAVA 对象 */ public static void toJsonFile(File f, Object obj) { toJsonFile(f, obj, null); } /** * 将一个 JAVA 对象以 JSON 的形式写到一个文件里,并且可以设定 JSON 字符串的格式化方式 * * @param f * 文本文件 * @param obj * JAVA 对象 * @param format * JSON 字符串格式化方式 ,若 format 为 null ,则以 JsonFormat.nice() 格式输出 */ public static void toJsonFile(File f, Object obj, JsonFormat format) { Writer writer = null; try { Files.createFileIfNoExists(f); writer = Streams.fileOutw(f); Json.toJson(writer, obj, format); writer.append('\n'); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(writer); } } /** * 清除 Json 解析器对实体解析的缓存 */ public static void clearEntityCache() { entities.clear(); } /** * 保存所有的 Json 实体 */ private static final ConcurrentHashMap<String, JsonEntity> entities = new ConcurrentHashMap<String, JsonEntity>(); /** * 获取一个 Json 实体 */ public static JsonEntity getEntity(Mirror<?> mirror) { JsonEntity je = entities.get(mirror.getTypeId()); if (null == je) { je = new JsonEntity(mirror); entities.put(mirror.getTypeId(), je); } return je; } // ================================================================================== // ====================帮助函数====================================================== /** * 从 JSON 字符串中,根据获取某种指定类型的 List 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, CharSequence cs)’ 的描述 * * @param eleType * 对象类型 * @param cs * JSON 字符串 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Type type, CharSequence cs) */ @SuppressWarnings("unchecked") public static <T> List<T> fromJsonAsList(Class<T> eleType, CharSequence cs) { return (List<T>) fromJson(NutType.list(eleType), cs); } /** * 从 JSON 输入流中,根据获取某种指定类型的 List 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, Reader reader)’ 的描述 * * @param eleType * 对象类型 * @param reader * JSON 输入流 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Type type, Reader reader) */ @SuppressWarnings("unchecked") public static <T> List<T> fromJsonAsList(Class<T> eleType, Reader reader) { return (List<T>) fromJson(NutType.list(eleType), reader); } /** * 从 JSON 字符串中,根据获取某种指定类型的 数组 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, CharSequence cs)’ 的描述 * * @param eleType * 对象类型 * @param cs * JSON 字符串 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Type type, CharSequence cs) */ @SuppressWarnings("unchecked") public static <T> T[] fromJsonAsArray(Class<T> eleType, CharSequence cs) { return (T[]) fromJson(NutType.array(eleType), cs); } /** * 从 JSON 输入流中,根据获取某种指定类型的 数组 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, Reader reader)’ 的描述 * * @param eleType * 对象类型 * @param reader * JSON 输入流 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Class type, Reader reader) */ @SuppressWarnings("unchecked") public static <T> T[] fromJsonAsArray(Class<T> eleType, Reader reader) { return (T[]) fromJson(NutType.array(eleType), reader); } /** * 从 JSON 字符串中,根据获取某种指定类型的 Map 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, CharSequence cs)’ 的描述 * * @param eleType * 对象类型 * @param cs * JSON 字符串 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Type type, CharSequence cs) */ @SuppressWarnings("unchecked") public static <T> Map<String, T> fromJsonAsMap(Class<T> eleType, CharSequence cs) { return (Map<String, T>) fromJson(NutType.mapStr(eleType), cs); } /** * 从 JSON 输入流中,根据获取某种指定类型的 Map 对象。 * <p> * 请参看函数 ‘Object fromJson(Type type, Reader reader)’ 的描述 * * @param eleType * 对象类型 * @param reader * JSON 输入流 * @return 特定类型的 JAVA 对象 * @throws JsonException * * @see #fromJson(Type type, Reader reader) */ @SuppressWarnings("unchecked") public static <T> Map<String, T> fromJsonAsMap(Class<T> eleType, Reader reader) { return (Map<String, T>) fromJson(NutType.mapStr(eleType), reader); } protected static JsonFormat deft = JsonFormat.nice(); public static void setDefaultJsonformat(JsonFormat defaultJf) { if (defaultJf == null) defaultJf = JsonFormat.nice(); Json.deft = defaultJf; } private static JsonEntityFieldMaker deftMaker = new JsonEntityFieldMakerImpl(); public static void setDefaultFieldMaker(JsonEntityFieldMaker fieldMaker) { if (fieldMaker != null) Json.deftMaker = fieldMaker; } public static JsonEntityFieldMaker getDefaultFieldMaker() { return deftMaker; } protected static List<JsonTypeHandler> handlers = new ArrayList<JsonTypeHandler>(); public static void addTypeHandler(JsonTypeHandler handler) { if (!handlers.contains(handler)) handlers.add(0, handler); } public static List<JsonTypeHandler> getTypeHandlers() { return Collections.unmodifiableList(handlers); } /** * */ static { handlers.add(new JsonJsonRenderHandler()); handlers.add(new JsonClassHandler()); handlers.add(new JsonMirrorHandler()); handlers.add(new JsonEnumHandler()); handlers.add(new JsonNumberHandler()); handlers.add(new JsonBooleanHandler()); handlers.add(new JsonStringLikeHandler()); handlers.add(new JsonDateTimeHandler()); try { Class.forName("java.time.temporal.TemporalAccessor"); handlers.add(new JsonLocalDateLikeHandler()); } catch (Throwable e) { } handlers.add(new JsonMapHandler()); handlers.add(new JsonIterableHandler()); handlers.add(new JsonArrayHandler()); handlers.add(new JsonPojoHandler()); } }
nutzam/nutz
src/org/nutz/json/Json.java
1,320
package com.taobao.arthas.core.shell.command.internal; import com.taobao.arthas.core.shell.term.Term; /** * 将数据写到term * * @author gehui 2017年7月26日 上午11:20:00 */ public class TermHandler extends StdoutHandler { private Term term; public TermHandler(Term term) { this.term = term; } @Override public String apply(String data) { term.write(data); return data; } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/shell/command/internal/TermHandler.java
1,321
package com.taobao.tddl.dbsync.binlog.event; import com.taobao.tddl.dbsync.binlog.LogBuffer; import com.taobao.tddl.dbsync.binlog.LogEvent; import java.nio.charset.StandardCharsets; /** * <pre> * Replication event to ensure to slave that master is alive. * The event is originated by master's dump thread and sent straight to * slave without being logged. Slave itself does not store it in relay log * but rather uses a data for immediate checks and throws away the event. * * Two members of the class log_ident and Log_event::log_pos comprise * @see the event_coordinates instance. The coordinates that a heartbeat * instance carries correspond to the last event master has sent from * its binlog. * </pre> * * @author jianghang 2013-4-8 上午12:36:29 * @version 1.0.3 * @since mysql 5.6 */ public class HeartbeatLogEvent extends LogEvent { public static final int FN_REFLEN = 512; /* Max length of full path-name */ private int identLen; private String logIdent; public HeartbeatLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent){ super(header); final int commonHeaderLen = descriptionEvent.commonHeaderLen; identLen = buffer.limit() - commonHeaderLen; if (identLen > FN_REFLEN - 1) { identLen = FN_REFLEN - 1; } logIdent = buffer.getFullString(commonHeaderLen, identLen, StandardCharsets.ISO_8859_1); } public int getIdentLen() { return identLen; } public String getLogIdent() { return logIdent; } }
alibaba/canal
dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/event/HeartbeatLogEvent.java
1,323
H 1516774576 tags: DP DP. 公式如何想到, 还需要重新理解. dp[i][j][m]: # of possibilities such that from j elements, pick m elements and sum up to i. i: [0~target] dp[i][j][m] = dp[i][j-1][m] + dp[i - A[j - 1]][j-1][m-1] (i not included) (i included) ``` /* Given n distinct positive integers, integer k (k <= n) and a number target. Find k numbers where sum is target. Calculate how many solutions there are? Given [1,2,3,4], k = 2, target = 5. There are 2 solutions: [1,4] and [2,3]. Return 2. */ /* Thoughts: Once learned the equation, it becomes easy: create dp[i][j][m]: # of possibilities such that from j elements, pick m elements and sum up to i. i: [0~target] HOWEVER: need to figure out how to come up with the equation Two ways to reach dp[i][j][m]: If element i is not included; if i is included. dp[i][j][m] = dp[i][j-1][m] + dp[i - A[j - 1]][j-1][m-1] (i not included) (i included) Initialization dp[0][j][0], j=[0, A.length]: from j elemnts, pick 0 element to sum up to 0, there can be just 1 possibility, don't pick any thing: [] Therefore: dp[0][j][0] = 1; */ public class Solution { /* * @param A: An integer array * @param k: A positive integer (k <= length(A)) * @param target: An integer * @return: An integer */ public int kSum(int[] A, int k, int target) { if (A == null || A.length == 0 || k <= 0) { return 0; } final int[][][] dp = new int[target + 1][A.length + 1][k + 1]; for (int j = 0; j <= A.length; j++) { dp[0][j][0] = 1; } for (int i = 1; i <= target; i++) { for (int j = 1; j <= A.length; j++) { for (int m = 1; m <= j && m <= k; m++) { dp[i][j][m] = dp[i][j - 1][m]; if (i - A[j - 1] >= 0) { dp[i][j][m] += dp[i - A[j - 1]][j - 1][m - 1]; } } } } return dp[target][A.length][k]; } } ```
awangdev/leet-code
Java/k Sum.java
1,326
package io.mycat.route.parser.druid; import java.util.ArrayList; import java.util.List; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.stat.TableStat.Condition; /** * Where条件单元 * * @author wang.dw * @date 2015-3-17 下午4:21:21 * @version 0.1.0 * @copyright wonhigh.cn * * 示例: SELECT id,traveldate FROM travelrecord WHERE id = 1 AND ( fee > 0 OR days > 0 OR ( traveldate > '2015-05-04 00:00:07.375' AND ( user_id <= 2 OR fee = days OR fee > 0 ) ) ) AND name = 'zhangsan' ORDER BY traveldate DESC LIMIT 20 * * * */ public class WhereUnit { /** * 完整的where条件 */ private SQLBinaryOpExpr whereExpr; /** * 还能继续再分的表达式:可能还有or关键字 */ private SQLBinaryOpExpr canSplitExpr; private List<SQLExpr> splitedExprList = new ArrayList<SQLExpr>(); private List<List<Condition>> conditionList = new ArrayList<List<Condition>>(); /** * whereExpr并不是一个where的全部,有部分条件在outConditions */ private List<Condition> outConditions = new ArrayList<Condition>(); /** * 按照or拆分后的条件片段中可能还有or语句,这样的片段实际上是嵌套的or语句,将其作为内层子whereUnit,不管嵌套多少层,循环处理 */ private List<WhereUnit> subWhereUnits = new ArrayList<WhereUnit>(); private boolean finishedParse = false; public List<Condition> getOutConditions() { return outConditions; } public void addOutConditions(List<Condition> outConditions) { this.outConditions.addAll(outConditions); } public boolean isFinishedParse() { return finishedParse; } public void setFinishedParse(boolean finishedParse) { this.finishedParse = finishedParse; } public WhereUnit() { } public WhereUnit(SQLBinaryOpExpr whereExpr) { this.whereExpr = whereExpr; this.canSplitExpr = whereExpr; } public SQLBinaryOpExpr getWhereExpr() { return whereExpr; } public void setWhereExpr(SQLBinaryOpExpr whereExpr) { this.whereExpr = whereExpr; } public SQLBinaryOpExpr getCanSplitExpr() { return canSplitExpr; } public void setCanSplitExpr(SQLBinaryOpExpr canSplitExpr) { this.canSplitExpr = canSplitExpr; } public List<SQLExpr> getSplitedExprList() { return splitedExprList; } public void addSplitedExpr(SQLExpr splitedExpr) { this.splitedExprList.add(splitedExpr); } public List<List<Condition>> getConditionList() { return conditionList; } public void setConditionList(List<List<Condition>> conditionList) { this.conditionList = conditionList; } public void addSubWhereUnit(WhereUnit whereUnit) { this.subWhereUnits.add(whereUnit); } public List<WhereUnit> getSubWhereUnit() { return this.subWhereUnits; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/route/parser/druid/WhereUnit.java
1,328
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper.dialect; /** * 替换和还原 SQL * * @author liuzh * @since 2017/8/23. */ public interface ReplaceSql { /** * 临时替换后用于 jsqlparser 解析 * * @param sql * @return */ String replace(String sql); /** * 还原经过解析后的 sql * * @param sql * @return */ String restore(String sql); }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/dialect/ReplaceSql.java
1,330
package com.taobao.arthas.core.shell.term.impl.http; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSession; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.termd.core.http.HttpTtyConnection; /** * 从http请求传递过来的 session 信息。解析websocket创建的 term 还需要登陆验证问题 * * @author hengyunabc 2021-03-04 * */ public class ExtHttpTtyConnection extends HttpTtyConnection { private ChannelHandlerContext context; public ExtHttpTtyConnection(ChannelHandlerContext context) { this.context = context; } @Override protected void write(byte[] buffer) { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(buffer); if (context != null) { context.writeAndFlush(new TextWebSocketFrame(byteBuf)); } } @Override public void schedule(Runnable task, long delay, TimeUnit unit) { if (context != null) { context.executor().schedule(task, delay, unit); } } @Override public void execute(Runnable task) { if (context != null) { context.executor().execute(task); } } @Override public void close() { if (context != null) { context.close(); } } public Map<String, Object> extSessions() { if (context != null) { HttpSession httpSession = HttpSessionManager.getHttpSessionFromContext(context); if (httpSession != null) { Object subject = httpSession.getAttribute(ArthasConstants.SUBJECT_KEY); if (subject != null) { Map<String, Object> result = new HashMap<String, Object>(); result.put(ArthasConstants.SUBJECT_KEY, subject); return result; } } } return Collections.emptyMap(); } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/ExtHttpTtyConnection.java