CommonTest.java 16 KB

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