CommonTest.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package com.izouma.nineth;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializerFeature;
  4. import com.github.kevinsawicki.http.HttpRequest;
  5. import com.google.common.base.Splitter;
  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.utils.AESEncryptUtil;
  11. import com.izouma.nineth.utils.TokenUtils;
  12. import com.izouma.nineth.web.BaseController;
  13. import io.ipfs.api.IPFS;
  14. import io.ipfs.api.MerkleNode;
  15. import io.ipfs.api.NamedStreamable;
  16. import io.ipfs.multihash.Multihash;
  17. import io.jsonwebtoken.Claims;
  18. import io.jsonwebtoken.Jwts;
  19. import io.jsonwebtoken.SignatureAlgorithm;
  20. import lombok.SneakyThrows;
  21. import net.coobird.thumbnailator.Thumbnails;
  22. import org.apache.commons.codec.EncoderException;
  23. import org.apache.commons.codec.net.URLCodec;
  24. import org.apache.commons.io.FileUtils;
  25. import org.apache.commons.lang3.RandomStringUtils;
  26. import org.apache.commons.lang3.RandomUtils;
  27. import org.apache.commons.lang3.Range;
  28. import org.apache.commons.text.CaseUtils;
  29. import org.apache.http.NameValuePair;
  30. import org.apache.http.client.utils.URLEncodedUtils;
  31. import org.apache.poi.util.TempFile;
  32. import org.bouncycastle.util.encoders.Base64;
  33. import org.bytedeco.javacv.FFmpegFrameGrabber;
  34. import org.bytedeco.javacv.Frame;
  35. import org.bytedeco.javacv.Java2DFrameConverter;
  36. import org.junit.Test;
  37. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessException;
  38. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessInfo;
  39. import org.libjpegturbo.turbojpeg.processor.api.ImageProcessor;
  40. import org.libjpegturbo.turbojpeg.processor.impl.ImageProcessorImpl;
  41. import org.libjpegturbo.turbojpeg.processor.utils.ImageProcessorUtils;
  42. import org.pngquant.PngQuant;
  43. import org.reflections.ReflectionUtils;
  44. import org.reflections.Reflections;
  45. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  46. import org.springframework.util.FileCopyUtils;
  47. import org.springframework.web.bind.annotation.GetMapping;
  48. import org.springframework.web.bind.annotation.PostMapping;
  49. import org.springframework.web.bind.annotation.RequestMapping;
  50. import org.springframework.web.bind.annotation.RestController;
  51. import javax.imageio.ImageIO;
  52. import java.awt.*;
  53. import java.awt.font.FontRenderContext;
  54. import java.awt.geom.AffineTransform;
  55. import java.awt.image.BufferedImage;
  56. import java.io.File;
  57. import java.io.IOException;
  58. import java.lang.reflect.Method;
  59. import java.math.BigDecimal;
  60. import java.math.BigInteger;
  61. import java.math.RoundingMode;
  62. import java.nio.charset.StandardCharsets;
  63. import java.nio.file.Files;
  64. import java.nio.file.Paths;
  65. import java.security.NoSuchAlgorithmException;
  66. import java.util.List;
  67. import java.util.*;
  68. import java.util.concurrent.ExecutorService;
  69. import java.util.concurrent.Executors;
  70. import java.util.concurrent.ForkJoinPool;
  71. import java.util.regex.Pattern;
  72. import java.util.stream.IntStream;
  73. import static java.nio.file.StandardOpenOption.CREATE;
  74. import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
  75. public class CommonTest {
  76. @Test
  77. public void getGenericsClass() {
  78. List<User> data = new ArrayList<>();
  79. data.add(new User());
  80. System.out.println(data.get(0).getClass().getSimpleName());
  81. System.out.println(data.getClass());
  82. Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".domain");
  83. Set<Class<? extends BaseEntity>> allClasses = reflections.getSubTypesOf(BaseEntity.class);
  84. for (Class<? extends BaseEntity> allClass : allClasses) {
  85. System.out.println(allClass.getName());
  86. }
  87. }
  88. @Test
  89. public void getapis() {
  90. List<Map<String, String>> entities = new ArrayList<>();
  91. Reflections classReflections = new Reflections(this.getClass().getPackage().getName());
  92. Set<Class<? extends BaseController>> controllers = classReflections.getSubTypesOf(BaseController.class);
  93. Set<Class<? extends BaseController>> list = ReflectionUtils
  94. .getAll(controllers, ReflectionUtils.withAnnotation(RestController.class));
  95. System.out.println(list);
  96. for (Class<? extends BaseController> aClass : list) {
  97. RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class);
  98. String baseUrl = requestMapping.value()[0];
  99. for (Method method : ReflectionUtils.getMethods(aClass, ReflectionUtils.withAnnotation(GetMapping.class))) {
  100. GetMapping getMapping = method.getAnnotation(GetMapping.class);
  101. System.out.println(getMapping.value()[0]);
  102. }
  103. for (Method method : ReflectionUtils
  104. .getMethods(aClass, ReflectionUtils.withAnnotation(PostMapping.class))) {
  105. PostMapping postMapping = method.getAnnotation(PostMapping.class);
  106. System.out.println(postMapping.value()[0]);
  107. }
  108. }
  109. }
  110. @Test
  111. public void testCaseUtils() {
  112. System.out.println(CaseUtils.toCamelCase("test_Model", true, '_'));
  113. }
  114. @Test
  115. public void testMeasureText() throws IOException, FontFormatException {
  116. AffineTransform affinetransform = new AffineTransform();
  117. FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
  118. Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass()
  119. .getResourceAsStream("/font/SourceHanSansCN-Normal.ttf"));
  120. System.out.println((int) (font.deriveFont(14f).getStringBounds("aaa", frc).getWidth()));
  121. }
  122. @Test
  123. public void testIdNoRegexp() {
  124. boolean b = Pattern
  125. .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");
  126. System.out.println(b);
  127. }
  128. @Test
  129. public void tesSms() throws IOException {
  130. Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".enums");
  131. Set<Class<? extends Enum>> entitySet = reflections.getSubTypesOf(Enum.class);
  132. StringBuilder idxJs = new StringBuilder();
  133. for (Class<? extends Enum> entity : entitySet) {
  134. idxJs.append("import ").append(entity.getSimpleName()).append(" from \"./").append(entity.getSimpleName())
  135. .append("\";\n");
  136. StringBuilder str = new StringBuilder("export default {\n");
  137. for (Enum enumConstant : entity.getEnumConstants()) {
  138. str.append(" ").append(enumConstant.name()).append(": \"").append(enumConstant.name())
  139. .append("\",\n");
  140. }
  141. str.append("}");
  142. Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", entity
  143. .getSimpleName() + ".js"), str.toString()
  144. .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  145. Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", entity
  146. .getSimpleName() + ".js"), str.toString()
  147. .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  148. }
  149. idxJs.append("export default {\n");
  150. for (Class<? extends Enum> entity : entitySet) {
  151. idxJs.append(" ").append(entity.getSimpleName()).append(": ").append(entity.getSimpleName())
  152. .append(",\n");
  153. }
  154. idxJs.append("}");
  155. System.out.println(idxJs.toString());
  156. Files.write(Paths
  157. .get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", "index.js"), idxJs
  158. .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  159. Files.write(Paths
  160. .get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", "index.js"), idxJs
  161. .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
  162. }
  163. @Test
  164. public void gen() {
  165. System.out.println(RandomStringUtils.randomAlphabetic(32));
  166. }
  167. @Test
  168. public void password() {
  169. String password = new BCryptPasswordEncoder().encode("123456");
  170. System.out.println(password);
  171. }
  172. @SneakyThrows
  173. @Test
  174. public void pngquant() {
  175. PngQuant pngQuant = new PngQuant();
  176. ImageIO.write(pngQuant
  177. .getRemapped(ImageIO.read(new File("/Users/drew/Downloads/2021-11-01-18-07-04JCDfFxKb.HEIC"))),
  178. "jpg", new File("/Users/drew/Downloads/111.jpg"));
  179. }
  180. @SneakyThrows
  181. @Test
  182. public void mozjpeg() {
  183. File out = TempFile.createTempFile("kljasdlkhfasldg", ".jpg");
  184. ImageProcessor processor = new ImageProcessorImpl();
  185. ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
  186. new File("/Users/drew/Downloads/2020-09-08-17-07-21zwBhaHeQ.jpg"),
  187. out, 75));
  188. FileCopyUtils.copy(out, new File("/Users/drew/Desktop/111.jpg"));
  189. System.out.println(out);
  190. }
  191. @Test
  192. public void thumbnailator() throws IOException, ImageProcessException {
  193. Thumbnails.of(new File("/Users/drew/Downloads/2021-11-01-17-47-55zMwbSlgJ.jpeg"))
  194. .size(3000, 3000)
  195. .outputFormat("jpg")
  196. .toFile("/Users/drew/Desktop/1.jpg");
  197. PngQuant pngQuant = new PngQuant();
  198. ImageIO.write(pngQuant
  199. .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.jpg"))),
  200. "jpg", new File("/Users/drew/Desktop/2.jpg"));
  201. ImageProcessor processor = new ImageProcessorImpl();
  202. ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
  203. new File("/Users/drew/Desktop/1.jpg"),
  204. new File("/Users/drew/Desktop/3.jpg"), 75));
  205. }
  206. @Test
  207. public void base64() {
  208. System.out.println(Base64.decode("e6e6vQJYhGmIkcA1pfnsipTovp10wJ"));
  209. }
  210. @Test
  211. public void resolveUrl() {
  212. try {
  213. System.out.println(new URLCodec().encode("http://www.baidu.com"));
  214. } catch (EncoderException e) {
  215. e.printStackTrace();
  216. }
  217. }
  218. @Test
  219. public void testIPFS() throws IOException {
  220. IPFS ipfs = new IPFS("121.40.132.44", 5001);
  221. HttpRequest request = HttpRequest.get("https://awesomeadmin.oss-cn-hangzhou.aliyuncs.com/image/2021-10-21-16-44-52kZqxuwhH.gif");
  222. File file = File.createTempFile("ipfs", ".tmp");
  223. request.receive(file);
  224. NamedStreamable.FileWrapper file1 = new NamedStreamable.FileWrapper(file);
  225. MerkleNode put = ipfs.add(file1).get(0);
  226. Multihash multihash = ipfs.pin.add(put.hash).get(0);
  227. System.out.println(put.hash.toBase58());
  228. System.out.println(multihash.toBase58());
  229. }
  230. @Test
  231. public void testWin() {
  232. List<BlindBoxItem> items = new ArrayList<>();
  233. items.add(BlindBoxItem.builder()
  234. .name("普通1")
  235. .total(100)
  236. .stock(100)
  237. .build());
  238. items.add(BlindBoxItem.builder()
  239. .name("普通2")
  240. .total(100)
  241. .stock(100)
  242. .build());
  243. items.add(BlindBoxItem.builder()
  244. .name("稀有1")
  245. .total(5)
  246. .stock(5)
  247. .rare(true)
  248. .build());
  249. items.add(BlindBoxItem.builder()
  250. .name("稀有2")
  251. .total(5)
  252. .stock(5)
  253. .rare(true)
  254. .build());
  255. for (int k = 0; k < items.stream().mapToInt(BlindBoxItem::getTotal).sum(); k++) {
  256. Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
  257. int c = 0, sum = 0;
  258. for (BlindBoxItem item : items) {
  259. randomRange.put(item, Range.between(c, c + item.getStock()));
  260. c += item.getStock();
  261. sum += item.getStock();
  262. }
  263. boolean win = false;
  264. int retry = 0;
  265. BlindBoxItem winItem = null;
  266. while (winItem == null) {
  267. int rand = RandomUtils.nextInt(0, sum + 1);
  268. for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
  269. BlindBoxItem item = entry.getKey();
  270. Range<Integer> range = entry.getValue();
  271. if (rand >= range.getMinimum() && rand < range.getMaximum()) {
  272. int total = items.stream().filter(i -> !i.isRare())
  273. .mapToInt(BlindBoxItem::getTotal).sum();
  274. int stock = items.stream().filter(i -> !i.isRare())
  275. .mapToInt(BlindBoxItem::getStock).sum();
  276. if (item.isRare()) {
  277. double nRate = stock / (double) total;
  278. double rRate = (item.getStock() - 1) / (double) item.getTotal();
  279. if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
  280. if (!(nRate > 0.1 && item.getStock() == 1)) {
  281. winItem = item;
  282. }
  283. } else {
  284. retry++;
  285. }
  286. } else {
  287. double nRate = (stock - 1) / (double) total;
  288. double rRate = item.getStock() / (double) item.getTotal();
  289. if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
  290. winItem = item;
  291. } else {
  292. retry++;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. winItem.setStock(winItem.getStock() - 1);
  299. System.out.println(winItem.getName() + (winItem.isRare() ? "\t+++" : ""));
  300. }
  301. }
  302. @Test
  303. public void testGrabFrame() throws IOException {
  304. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("/Users/drew/Downloads/video1627914878375.mp4");
  305. frameGrabber.start();
  306. Java2DFrameConverter aa = new Java2DFrameConverter();
  307. int length = frameGrabber.getLengthInVideoFrames();
  308. Frame frame = null;
  309. int i = 0;
  310. while (frame == null && i < length) {
  311. frame = frameGrabber.grabKeyFrame();
  312. i++;
  313. }
  314. Objects.requireNonNull(frame);
  315. BufferedImage thumbBi = aa.convert(frame);
  316. ImageIO.write(thumbBi, "jpg", new File("/Users/drew/Desktop/1.jpg"));
  317. }
  318. @Test
  319. public void testQuality() throws IOException {
  320. Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
  321. .size(1000, 1000)
  322. .outputFormat("jpg")
  323. .outputQuality(1)
  324. .toFile("/Users/drew/Desktop/1.jpg");
  325. Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
  326. .size(1000, 1000)
  327. .outputFormat("jpg")
  328. .outputQuality(0.6)
  329. .toFile("/Users/drew/Desktop/2.jpg");
  330. }
  331. @Test
  332. public void testJwt() {
  333. String token = Jwts.builder()
  334. .setClaims(new HashMap<>())
  335. .setSubject("15077886171")
  336. .setIssuedAt(new Date())
  337. .setExpiration(new Date(new Date().getTime() + 10 * 60 * 1000)) //10min
  338. .signWith(SignatureAlgorithm.HS512, Constants.SMS_TOKEN_SECRET)
  339. .compact();
  340. System.out.println(token);
  341. Claims claims = Jwts.parser()
  342. .setSigningKey(Constants.SMS_TOKEN_SECRET)
  343. .parseClaimsJws(token)
  344. .getBody();
  345. System.out.println(claims.getSubject());
  346. System.out.println(claims.getExpiration());
  347. }
  348. @Test
  349. public void testReplace() {
  350. System.out.println("15077886171".replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  351. }
  352. @Test
  353. public void sfsdf() {
  354. System.out.println(BigDecimal.valueOf(11111110.5).setScale(2, RoundingMode.HALF_UP).toPlainString());
  355. }
  356. @Test
  357. public void random256() throws NoSuchAlgorithmException {
  358. String tokenId = TokenUtils.genTokenId();
  359. System.out.println(tokenId);
  360. System.out.println(new BigInteger(tokenId, 16));
  361. }
  362. @Test
  363. public void dd() throws IOException {
  364. String[] arr1 = FileUtils.readFileToString(new File("/Users/drew/Desktop/未命名文件夹 2/111")).split("\n");
  365. List<String> arr2 = Arrays.asList(FileUtils.readFileToString(new File("/Users/drew/Desktop/未命名文件夹 2/222"))
  366. .split("\n"));
  367. for (String s : arr1) {
  368. if (!arr2.contains(s)) {
  369. System.out.println(s);
  370. }
  371. }
  372. }
  373. @Test
  374. public void jj() {
  375. final int parallelism = 4;
  376. ForkJoinPool forkJoinPool = null;
  377. try {
  378. forkJoinPool = new ForkJoinPool(parallelism);
  379. forkJoinPool.submit(() ->
  380. // Parallel task here, for example
  381. IntStream.range(1, 1_000_000).parallel()
  382. .forEach(i -> {
  383. })
  384. );
  385. } finally {
  386. if (forkJoinPool != null) {
  387. forkJoinPool.shutdown();
  388. }
  389. }
  390. }
  391. @Test
  392. public void testnewSingleThreadScheduledExecutor() throws InterruptedException {
  393. ExecutorService service = Executors.newFixedThreadPool(10);
  394. final int[] c = {0};
  395. for (int i = 0; i < 1000; i++) {
  396. service.submit(new Runnable() {
  397. @SneakyThrows
  398. @Override
  399. public void run() {
  400. Thread.sleep(300);
  401. System.out.println(++c[0]);
  402. }
  403. });
  404. }
  405. Thread.sleep(20000);
  406. }
  407. @Test
  408. public void testaes() throws Exception {
  409. String encrypted = "ccd97379f001d47895eb4293144b74f28de4fcf5b56daf4ce73d2db34f381984b2c2260f821593968e387dccdc11713a5b558a571b17aaae3e9e91a0b9dc576e";
  410. String qs = AESEncryptUtil.decrypt(encrypted);
  411. System.out.println(qs);
  412. List<NameValuePair> list = URLEncodedUtils.parse(qs, StandardCharsets.UTF_8);
  413. System.out.println(JSON.toJSONString(list, SerializerFeature.PrettyFormat));
  414. final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(qs);
  415. System.out.println(map);
  416. }
  417. @Test
  418. public void aasdf() {
  419. String body = HttpRequest.post("https://zid.market.alicloudapi.com/idcheck/Post")
  420. .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
  421. .contentType(HttpRequest.CONTENT_TYPE_FORM)
  422. .form("cardNo", "352228198905220012")
  423. .form("realName", "吴承培")
  424. .body();
  425. System.out.println(JSON.toJSONString(JSON.parseObject(body), SerializerFeature.PrettyFormat));
  426. }
  427. }