CommonTest.java 15 KB

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