CommonTest.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package com.izouma.nineth;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.OSSClient;
  4. import com.aliyun.oss.model.SetBucketCORSRequest;
  5. import com.github.kevinsawicki.http.HttpRequest;
  6. import com.izouma.nineth.config.Constants;
  7. import com.izouma.nineth.domain.BaseEntity;
  8. import com.izouma.nineth.domain.BlindBoxItem;
  9. import com.izouma.nineth.domain.User;
  10. import com.izouma.nineth.enums.AuthorityName;
  11. import com.izouma.nineth.security.Authority;
  12. import com.izouma.nineth.utils.UrlUtils;
  13. import com.izouma.nineth.web.BaseController;
  14. import io.ipfs.api.IPFS;
  15. import io.ipfs.api.MerkleNode;
  16. import io.ipfs.api.NamedStreamable;
  17. import io.ipfs.cid.Cid;
  18. import io.ipfs.multihash.Multihash;
  19. import io.jsonwebtoken.Claims;
  20. import io.jsonwebtoken.Jwts;
  21. import io.jsonwebtoken.SignatureAlgorithm;
  22. import lombok.SneakyThrows;
  23. import net.coobird.thumbnailator.Thumbnails;
  24. import net.coobird.thumbnailator.name.Rename;
  25. import org.apache.commons.codec.EncoderException;
  26. import org.apache.commons.codec.net.URLCodec;
  27. import org.apache.commons.lang3.RandomStringUtils;
  28. import org.apache.commons.lang3.RandomUtils;
  29. import org.apache.commons.lang3.Range;
  30. import org.apache.commons.text.CaseUtils;
  31. import org.apache.http.client.utils.URLEncodedUtils;
  32. import org.apache.poi.util.TempFile;
  33. import org.bouncycastle.util.encoders.Base64;
  34. import org.bouncycastle.util.encoders.UrlBase64Encoder;
  35. import org.bytedeco.javacv.FFmpegFrameGrabber;
  36. import org.bytedeco.javacv.Frame;
  37. import org.bytedeco.javacv.Java2DFrameConverter;
  38. import org.junit.Assert;
  39. import org.junit.Test;
  40. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessException;
  41. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessInfo;
  42. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessor;
  43. import org.libjpegturbo.turbojpeg.processor.impl.ImageProcessorImpl;
  44. import org.libjpegturbo.turbojpeg.processor.utils.ImageProcessorUtils;
  45. import org.pngquant.PngQuant;
  46. import org.reflections.ReflectionUtils;
  47. import org.reflections.Reflections;
  48. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  49. import org.springframework.util.FileCopyUtils;
  50. import org.springframework.web.bind.annotation.GetMapping;
  51. import org.springframework.web.bind.annotation.PostMapping;
  52. import org.springframework.web.bind.annotation.RequestMapping;
  53. import org.springframework.web.bind.annotation.RestController;
  54. import javax.imageio.ImageIO;
  55. import java.awt.*;
  56. import java.awt.font.FontRenderContext;
  57. import java.awt.geom.AffineTransform;
  58. import java.awt.image.BufferedImage;
  59. import java.io.File;
  60. import java.io.IOException;
  61. import java.lang.reflect.Method;
  62. import java.net.URL;
  63. import java.nio.charset.StandardCharsets;
  64. import java.nio.file.Files;
  65. import java.nio.file.Paths;
  66. import java.util.*;
  67. import java.util.List;
  68. import java.util.regex.Pattern;
  69. import static java.nio.file.StandardOpenOption.CREATE;
  70. import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
  71. public class CommonTest {
  72. @Test
  73. public void getGenericsClass() {
  74. List<User> data = new ArrayList<>();
  75. data.add(new User());
  76. System.out.println(data.get(0).getClass().getSimpleName());
  77. System.out.println(data.getClass());
  78. Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".domain");
  79. Set<Class<? extends BaseEntity>> allClasses = reflections.getSubTypesOf(BaseEntity.class);
  80. for (Class<? extends BaseEntity> allClass : allClasses) {
  81. System.out.println(allClass.getName());
  82. }
  83. }
  84. @Test
  85. public void getapis() {
  86. List<Map<String, String>> entities = new ArrayList<>();
  87. Reflections classReflections = new Reflections(this.getClass().getPackage().getName());
  88. Set<Class<? extends BaseController>> controllers = classReflections.getSubTypesOf(BaseController.class);
  89. Set<Class<? extends BaseController>> list = ReflectionUtils
  90. .getAll(controllers, ReflectionUtils.withAnnotation(RestController.class));
  91. System.out.println(list);
  92. for (Class<? extends BaseController> aClass : list) {
  93. RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class);
  94. String baseUrl = requestMapping.value()[0];
  95. for (Method method : ReflectionUtils.getMethods(aClass, ReflectionUtils.withAnnotation(GetMapping.class))) {
  96. GetMapping getMapping = method.getAnnotation(GetMapping.class);
  97. System.out.println(getMapping.value()[0]);
  98. }
  99. for (Method method : ReflectionUtils
  100. .getMethods(aClass, ReflectionUtils.withAnnotation(PostMapping.class))) {
  101. PostMapping postMapping = method.getAnnotation(PostMapping.class);
  102. System.out.println(postMapping.value()[0]);
  103. }
  104. }
  105. }
  106. @Test
  107. public void testCaseUtils() {
  108. System.out.println(CaseUtils.toCamelCase("test_Model", true, '_'));
  109. }
  110. @Test
  111. public void testMeasureText() throws IOException, FontFormatException {
  112. AffineTransform affinetransform = new AffineTransform();
  113. FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
  114. Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass()
  115. .getResourceAsStream("/font/SourceHanSansCN-Normal.ttf"));
  116. System.out.println((int) (font.deriveFont(14f).getStringBounds("aaa", frc).getWidth()));
  117. }
  118. @Test
  119. public void testIdNoRegexp() {
  120. boolean b = Pattern
  121. .matches("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0-2]\\d)|3[0-1])\\d{3}[0-9xX]$", "32100219950830461X");
  122. System.out.println(b);
  123. }
  124. @Test
  125. public void tesSms() throws IOException {
  126. Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".enums");
  127. Set<Class<? extends Enum>> entitySet = reflections.getSubTypesOf(Enum.class);
  128. StringBuilder idxJs = new StringBuilder();
  129. for (Class<? extends Enum> entity : entitySet) {
  130. idxJs.append("import ").append(entity.getSimpleName()).append(" from \"./").append(entity.getSimpleName())
  131. .append("\";\n");
  132. StringBuilder str = new StringBuilder("export default {\n");
  133. for (Enum enumConstant : entity.getEnumConstants()) {
  134. str.append(" ").append(enumConstant.name()).append(": \"").append(enumConstant.name())
  135. .append("\",\n");
  136. }
  137. str.append("}");
  138. Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", entity
  139. .getSimpleName() + ".js"), str.toString()
  140. .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  141. Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", entity
  142. .getSimpleName() + ".js"), str.toString()
  143. .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  144. }
  145. idxJs.append("export default {\n");
  146. for (Class<? extends Enum> entity : entitySet) {
  147. idxJs.append(" ").append(entity.getSimpleName()).append(": ").append(entity.getSimpleName())
  148. .append(",\n");
  149. }
  150. idxJs.append("}");
  151. System.out.println(idxJs.toString());
  152. Files.write(Paths
  153. .get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", "index.js"), idxJs
  154. .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  155. Files.write(Paths
  156. .get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", "index.js"), idxJs
  157. .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  158. }
  159. @Test
  160. public void gen() {
  161. System.out.println(RandomStringUtils.randomAlphabetic(32));
  162. }
  163. @Test
  164. public void password() {
  165. String password = new BCryptPasswordEncoder().encode("123456");
  166. System.out.println(password);
  167. }
  168. @SneakyThrows
  169. @Test
  170. public void pngquant() {
  171. PngQuant pngQuant = new PngQuant();
  172. ImageIO.write(pngQuant
  173. .getRemapped(ImageIO.read(new File("/Users/drew/Downloads/2021-11-01-18-07-04JCDfFxKb.HEIC"))),
  174. "jpg", new File("/Users/drew/Downloads/111.jpg"));
  175. }
  176. @SneakyThrows
  177. @Test
  178. public void mozjpeg() {
  179. File out = TempFile.createTempFile("kljasdlkhfasldg", ".jpg");
  180. ImageProcessor processor = new ImageProcessorImpl();
  181. ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
  182. new File("/Users/drew/Downloads/2020-09-08-17-07-21zwBhaHeQ.jpg"),
  183. out, 75));
  184. FileCopyUtils.copy(out, new File("/Users/drew/Desktop/111.jpg"));
  185. System.out.println(out);
  186. }
  187. @Test
  188. public void thumbnailator() throws IOException, ImageProcessException {
  189. Thumbnails.of(new File("/Users/drew/Downloads/2021-11-01-17-47-55zMwbSlgJ.jpeg"))
  190. .size(3000, 3000)
  191. .outputFormat("jpg")
  192. .toFile("/Users/drew/Desktop/1.jpg");
  193. PngQuant pngQuant = new PngQuant();
  194. ImageIO.write(pngQuant
  195. .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.jpg"))),
  196. "jpg", new File("/Users/drew/Desktop/2.jpg"));
  197. ImageProcessor processor = new ImageProcessorImpl();
  198. ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
  199. new File("/Users/drew/Desktop/1.jpg"),
  200. new File("/Users/drew/Desktop/3.jpg"), 75));
  201. }
  202. @Test
  203. public void base64() {
  204. System.out.println(Base64.decode("e6e6vQJYhGmIkcA1pfnsipTovp10wJ"));
  205. }
  206. @Test
  207. public void resolveUrl() {
  208. try {
  209. System.out.println(new URLCodec().encode("http://www.baidu.com"));
  210. } catch (EncoderException e) {
  211. e.printStackTrace();
  212. }
  213. }
  214. @Test
  215. public void testIPFS() throws IOException {
  216. IPFS ipfs = new IPFS("121.40.132.44", 5001);
  217. HttpRequest request = HttpRequest.get("https://awesomeadmin.oss-cn-hangzhou.aliyuncs.com/image/2021-10-21-16-44-52kZqxuwhH.gif");
  218. File file = File.createTempFile("ipfs", ".tmp");
  219. request.receive(file);
  220. NamedStreamable.FileWrapper file1 = new NamedStreamable.FileWrapper(file);
  221. MerkleNode put = ipfs.add(file1).get(0);
  222. Multihash multihash = ipfs.pin.add(put.hash).get(0);
  223. System.out.println(put.hash.toBase58());
  224. System.out.println(multihash.toBase58());
  225. }
  226. @Test
  227. public void testWin() {
  228. List<BlindBoxItem> items = new ArrayList<>();
  229. items.add(BlindBoxItem.builder()
  230. .name("普通1")
  231. .total(100)
  232. .stock(100)
  233. .build());
  234. items.add(BlindBoxItem.builder()
  235. .name("普通2")
  236. .total(100)
  237. .stock(100)
  238. .build());
  239. items.add(BlindBoxItem.builder()
  240. .name("稀有1")
  241. .total(5)
  242. .stock(5)
  243. .rare(true)
  244. .build());
  245. items.add(BlindBoxItem.builder()
  246. .name("稀有2")
  247. .total(5)
  248. .stock(5)
  249. .rare(true)
  250. .build());
  251. for (int k = 0; k < items.stream().mapToInt(BlindBoxItem::getTotal).sum(); k++) {
  252. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  253. int c = 0, sum = 0;
  254. for (BlindBoxItem item : items) {
  255. randomRange.put(item, Range.between(c, c + item.getStock()));
  256. c += item.getStock();
  257. sum += item.getStock();
  258. }
  259. boolean win = false;
  260. int retry = 0;
  261. BlindBoxItem winItem = null;
  262. while (winItem == null) {
  263. int rand = RandomUtils.nextInt(0, sum + 1);
  264. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  265. BlindBoxItem item = entry.getKey();
  266. Range<Integer> range = entry.getValue();
  267. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  268. int total = items.stream().filter(i -> !i.isRare())
  269. .mapToInt(BlindBoxItem::getTotal).sum();
  270. int stock = items.stream().filter(i -> !i.isRare())
  271. .mapToInt(BlindBoxItem::getStock).sum();
  272. if (item.isRare()) {
  273. double nRate = stock / (double) total;
  274. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  275. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  276. if (!(nRate > 0.1 && item.getStock() == 1)) {
  277. winItem = item;
  278. }
  279. } else {
  280. retry++;
  281. }
  282. } else {
  283. double nRate = (stock - 1) / (double) total;
  284. double rRate = item.getStock() / (double) item.getTotal();
  285. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  286. winItem = item;
  287. } else {
  288. retry++;
  289. }
  290. }
  291. }
  292. }
  293. }
  294. winItem.setStock(winItem.getStock() - 1);
  295. System.out.println(winItem.getName() + (winItem.isRare() ? "\t+++" : ""));
  296. }
  297. }
  298. @Test
  299. public void testGrabFrame() throws IOException {
  300. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("/Users/drew/Downloads/video1627914878375.mp4");
  301. frameGrabber.start();
  302. Java2DFrameConverter aa = new Java2DFrameConverter();
  303. int length = frameGrabber.getLengthInVideoFrames();
  304. Frame frame = null;
  305. int i = 0;
  306. while (frame == null && i < length) {
  307. frame = frameGrabber.grabKeyFrame();
  308. i++;
  309. }
  310. Objects.requireNonNull(frame);
  311. BufferedImage thumbBi = aa.convert(frame);
  312. ImageIO.write(thumbBi, "jpg", new File("/Users/drew/Desktop/1.jpg"));
  313. }
  314. @Test
  315. public void testQuality() throws IOException {
  316. Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
  317. .size(1000, 1000)
  318. .outputFormat("jpg")
  319. .outputQuality(1)
  320. .toFile("/Users/drew/Desktop/1.jpg");
  321. Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
  322. .size(1000, 1000)
  323. .outputFormat("jpg")
  324. .outputQuality(0.6)
  325. .toFile("/Users/drew/Desktop/2.jpg");
  326. }
  327. @Test
  328. public void testJwt() {
  329. String token = Jwts.builder()
  330. .setClaims(new HashMap<>())
  331. .setSubject("15077886171")
  332. .setIssuedAt(new Date())
  333. .setExpiration(new Date(new Date().getTime() + 10 * 60 * 1000)) //10min
  334. .signWith(SignatureAlgorithm.HS512, Constants.SMS_TOKEN_SECRET)
  335. .compact();
  336. System.out.println(token);
  337. Claims claims = Jwts.parser()
  338. .setSigningKey(Constants.SMS_TOKEN_SECRET)
  339. .parseClaimsJws(token)
  340. .getBody();
  341. System.out.println(claims.getSubject());
  342. System.out.println(claims.getExpiration());
  343. }
  344. @Test
  345. public void setOSSCORS() {
  346. // Endpoint以杭州为例,其它Region请按实际情况填写。
  347. String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
  348. // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号
  349. String accessKeyId = "LTAI5tCtRs8DXBLBsn49qRZX";
  350. String accessKeySecret = "86uC18LZsfB9JU04BK7ImVXfOytEkG";
  351. String bucketName = "9space-2021";
  352. // 创建OSSClient实例。
  353. OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  354. SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);
  355. // 跨域资源共享规则的容器,每个存储空间最多允许10条规则。
  356. ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<>();
  357. SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();
  358. ArrayList<String> allowedOrigin = new ArrayList<String>();
  359. // 指定允许跨域请求的来源。
  360. allowedOrigin.add("*");
  361. ArrayList<String> allowedMethod = new ArrayList<String>();
  362. allowedMethod.add("PUT");
  363. allowedMethod.add("GET");
  364. allowedMethod.add("POST");
  365. allowedMethod.add("HEAD");
  366. // 指定允许用户从应用程序中访问的响应头。
  367. // AllowedOrigins和AllowedMethods最多支持一个星号(*)通配符。星号(*)表示允许所有的域来源或者操作。
  368. corRule.setAllowedMethods(allowedMethod);
  369. corRule.setAllowedOrigins(allowedOrigin);
  370. // 最多允许10条规则。
  371. putCorsRules.add(corRule);
  372. // 已存在的规则将被覆盖。
  373. request.setCorsRules(putCorsRules);
  374. client.setBucketCORS(request);
  375. // 关闭OSSClient。
  376. client.shutdown();
  377. }
  378. }