CommonTest.java 16 KB

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