CommonTest.java 16 KB

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