CommonTest.java 19 KB

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